answer
stringlengths 17
10.2M
|
|---|
package za.org.grassroot.webapp.controller.rest.whatsapp;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.MessageSource;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import za.org.grassroot.core.domain.BaseRoles;
import za.org.grassroot.core.domain.JpaEntityType;
import za.org.grassroot.core.domain.User;
import za.org.grassroot.core.domain.campaign.Campaign;
import za.org.grassroot.core.domain.campaign.CampaignActionType;
import za.org.grassroot.core.domain.campaign.CampaignMessage;
import za.org.grassroot.core.enums.Province;
import za.org.grassroot.core.enums.UserInterfaceType;
import za.org.grassroot.integration.authentication.CreateJwtTokenRequest;
import za.org.grassroot.integration.authentication.JwtService;
import za.org.grassroot.integration.authentication.JwtType;
import za.org.grassroot.services.AnalyticalService;
import za.org.grassroot.services.PermissionBroker;
import za.org.grassroot.services.async.AsyncUserLogger;
import za.org.grassroot.services.campaign.CampaignBroker;
import za.org.grassroot.services.user.UserManagementService;
import za.org.grassroot.webapp.controller.BaseController;
import za.org.grassroot.webapp.controller.rest.Grassroot2RestController;
import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@Slf4j @RestController @Grassroot2RestController
@RequestMapping("/v2/api/whatsapp") @Api("/v2/api/whatsapp")
@PreAuthorize("hasRole('ROLE_SYSTEM_CALL')")
public class WhatsAppRelatedController extends BaseController {
private final JwtService jwtService;
private final AsyncUserLogger userLogger;
private CampaignBroker campaignBroker;
private MessageSource messageSource;
private AnalyticalService analyticalService;
@Autowired
public WhatsAppRelatedController(UserManagementService userManagementService, PermissionBroker permissionBroker, JwtService jwtService, AsyncUserLogger userLogger) {
super(userManagementService, permissionBroker);
this.jwtService = jwtService;
this.userLogger = userLogger;
}
@Autowired
private void setCampaignBroker(CampaignBroker campaignBroker) {
this.campaignBroker = campaignBroker;
}
@Autowired
public void setMessageSource(@Qualifier("messageSource") MessageSource messageSource) {
this.messageSource = messageSource;
}
@Autowired(required = false)
public void setAnalyticalService(AnalyticalService analyticalService) {
this.analyticalService = analyticalService;
}
@PostConstruct
public void init() {
if (analyticalService != null) {
log.info("Starting up WhatsApp controller: number users opted in: {}, number users used : {}",
analyticalService.countUsersWithWhatsAppOptIn(), analyticalService.countUsersThatHaveUsedWhatsApp());
}
}
// this will get called _a lot_ during a sesion (each message to and fro), so not yet introducting a record user log in
@RequestMapping(value = "/user/id", method = RequestMethod.POST)
public ResponseEntity fetchUserId(String msisdn) {
User user = userManagementService.loadOrCreate(msisdn);
userLogger.recordUserSession(user.getUid(), UserInterfaceType.WHATSAPP);
return ResponseEntity.ok(user.getUid());
}
// for accessing standard user APIs, but is time limited, and does not include system roles
// so in case overall microservice token is compromised, only some features can be called
@RequestMapping(value = "/user/token", method = RequestMethod.POST)
public ResponseEntity fetchRestrictedUserToken(String userId) {
CreateJwtTokenRequest tokenRequest = new CreateJwtTokenRequest(JwtType.MSGING_CLIENT);
tokenRequest.addClaim(JwtService.USER_UID_KEY, userId);
tokenRequest.addClaim(JwtService.SYSTEM_ROLE_KEY, BaseRoles.ROLE_FULL_USER);
userLogger.logUserLogin(userId, UserInterfaceType.WHATSAPP); // keep an eye on how often this gets called (may become redundant)
return ResponseEntity.ok(jwtService.createJwt(tokenRequest));
}
@RequestMapping(value = "/phrase/search", method = RequestMethod.POST)
public ResponseEntity<PhraseSearchResponse> checkIfPhraseTriggersCampaign(@RequestParam String phrase, @RequestParam String userId) {
Campaign campaign = campaignBroker.findCampaignByJoinWord(phrase, userId, UserInterfaceType.WHATSAPP);
if (campaign != null) {
// passing null as channel because reusing USSD, for now
CampaignMessage message = campaignBroker.getOpeningMessage(campaign.getUid(), null, null, null);
LinkedHashMap<String, String> menu = getMenuFromMessage(message);
PhraseSearchResponse response = PhraseSearchResponse.builder()
.entityFound(true)
.entityType(JpaEntityType.CAMPAIGN)
.entityUid(campaign.getUid())
.responseMessages(getResponseMessages(message, menu.values()))
.responseMenu(menu)
.build();
return ResponseEntity.ok(response);
} else {
return ResponseEntity.ok(PhraseSearchResponse.notFoundResponse());
}
}
@RequestMapping(value = "/entity/respond/{entityType}/{entityUid}", method = RequestMethod.POST)
public ResponseEntity<EntityResponseToUser> processFurtherResponseToEntity(@PathVariable JpaEntityType entityType,
@PathVariable String entityUid,
@RequestParam String userId,
@RequestBody EntityReplyFromUser userReply) {
EntityResponseToUser response;
log.info("Received user response: {}", userReply);
if (userReply.getAuxProperties() != null && userReply.getAuxProperties().containsKey("requestDataType")) {
response = replyToDataRequest(userId, userReply, entityType, entityUid);
} else if (JpaEntityType.CAMPAIGN.equals(entityType)) {
response = replyToCampaignMessage(userId, entityUid, userReply.getAuxProperties().get("PRIOR"),
CampaignActionType.valueOf(userReply.getMenuOptionPayload()), userReply.getUserMessage());
} else {
response = EntityResponseToUser.cannotRespond(entityType, entityUid);
}
log.info("Sending back to user: {}", response);
return ResponseEntity.ok(response);
}
private EntityResponseToUser replyToDataRequest(String userId, EntityReplyFromUser userReply, JpaEntityType entityType, String entityId) {
RequestDataType requestType = RequestDataType.valueOf(userReply.getAuxProperties().get("requestDataType"));
switch (requestType) {
case USER_NAME:
userManagementService.updateDisplayName(userId, userId, userReply.getUserMessage());
break;
case LOCATION_GPS_REQUIRED:
log.info("Well, we would be setting it from GPS here");
break;
case LOCATION_PROVINCE_OKAY:
userManagementService.updateUserProvince(userId, Province.valueOf(userReply.getUserMessage()));
break;
default:
log.info("Got a user response we can't do anything with. Request type: {}, user response: {}", requestType, userReply);
break;
}
RequestDataType nextRequestType = checkForNextUserInfo(userId);
return EntityResponseToUser.builder()
.entityType(entityType).entityUid(entityId)
.requestDataType(nextRequestType)
.build();
}
private EntityResponseToUser replyToCampaignMessage(String userId,
String campaignUid,
String priorMessageUid,
CampaignActionType action,
String userResponse) {
log.info("Getting campaign message for action type {}, user response {}, campaign ID: {}", action, userResponse, campaignUid);
switch (action) {
case JOIN_GROUP:
campaignBroker.addUserToCampaignMasterGroup(campaignUid, userId, UserInterfaceType.WHATSAPP);
break;
case SIGN_PETITION:
campaignBroker.signPetition(campaignUid, userId, UserInterfaceType.WHATSAPP);
break;
case TAG_ME:
campaignBroker.setUserJoinTopic(campaignUid, userId, userResponse, UserInterfaceType.WHATSAPP);
break;
case SHARE_SEND:
campaignBroker.sendShareMessage(campaignUid, userId, userResponse, null, UserInterfaceType.WHATSAPP);
break;
default:
log.info("No action possible for incoming user action {}, just returning message", action);
break;
}
List<CampaignMessage> nextMsgs = campaignBroker.findCampaignMessage(campaignUid, action, null);
if (nextMsgs == null || nextMsgs.isEmpty()) {
nextMsgs = Collections.singletonList(campaignBroker.findCampaignMessage(campaignUid, priorMessageUid, action));
}
log.info("Next campaign messages found: {}", nextMsgs);
List<String> messageTexts = nextMsgs.stream().map(CampaignMessage::getMessage).collect(Collectors.toList());
LinkedHashMap<String, String> actionOptions = nextMsgs.stream().filter(CampaignMessage::hasMenuOptions)
.findFirst().map(this::getMenuFromMessage).orElse(new LinkedHashMap<>());
messageTexts.addAll(actionOptions.values());
RequestDataType requestDataType = actionOptions.isEmpty() ? checkForNextUserInfo(userId) : RequestDataType.MENU_SELECTION;
log.info("request data type: {}", requestDataType);
return EntityResponseToUser.builder()
.entityType(JpaEntityType.CAMPAIGN)
.entityUid(campaignUid)
.requestDataType(requestDataType)
.messages(messageTexts)
.menu(actionOptions)
.build();
}
private List<String> getResponseMessages(CampaignMessage message, Collection<String> menuOptionTexts) {
List<String> messages = new ArrayList<>();
messages.add(message.getMessage());
messages.addAll(menuOptionTexts);
return messages;
}
private LinkedHashMap<String, String> getMenuFromMessage(CampaignMessage message) {
LinkedHashMap<String, String> map = new LinkedHashMap<>();
List<CampaignActionType> options = new ArrayList<>(message.getNextMessages().values());
log.info("Next menu options, should be in order: {}", options);
IntStream.range(0, options.size()).forEach(i ->
map.put(options.get(i).toString(), (i + 1) + ". " + actionToMessage(options.get(i)))
);
return map;
}
private String actionToMessage(CampaignActionType action) {
return messageSource.getMessage("ussd.campaign." + action.toString().toLowerCase(),
null, action.toString(), Locale.ENGLISH);
}
private RequestDataType checkForNextUserInfo(String userId) {
User user = userManagementService.load(userId);
if (!user.hasName())
return RequestDataType.USER_NAME;
if (user.getProvince() == null)
return RequestDataType.LOCATION_PROVINCE_OKAY;
else
return RequestDataType.NONE;
}
}
|
import java.net.*;
import java.io.*;
import java.util.*;
import org.xbill.DNS.*;
import org.xbill.DNS.utils.*;
/** @author Brian Wellington <bwelling@xbill.org> */
public class update {
Message query, response;
Resolver res;
String server = null;
Name zone;
int defaultTTL;
short defaultClass = DClass.IN;
PrintStream log = null;
void
print(Object o) {
System.out.println(o);
if (log != null)
log.println(o);
}
public
update(InputStream in) throws IOException {
List inputs = new ArrayList();
List istreams = new ArrayList();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
inputs.add(br);
istreams.add(in);
while (true) {
try {
String line = null;
do {
InputStream is;
is = (InputStream)istreams.get(istreams.size()
- 1);
br = (BufferedReader)inputs.get(inputs.size()
- 1);
if (is == System.in)
System.out.print("> ");
line = Master.readExtendedLine(br);
if (line == null) {
br.close();
inputs.remove(br);
istreams.remove(is);
if (inputs.isEmpty())
return;
}
} while (line == null);
if (log != null)
log.println("> " + line);
if (line.length() == 0 || line.charAt(0) == '
continue;
/* Allows cut and paste from other update sessions */
if (line.charAt(0) == '>')
line = line.substring(1);
MyStringTokenizer st = new MyStringTokenizer(line);
if (!st.hasMoreTokens())
continue;
String operation = st.nextToken();
if (operation.equals("server")) {
server = st.nextToken();
res = new SimpleResolver(server);
if (st.hasMoreTokens()) {
String portstr = st.nextToken();
res.setPort(Short.parseShort(portstr));
}
}
else if (operation.equals("key")) {
String keyname = st.nextToken();
String keydata = st.nextToken();
if (res == null)
res = new SimpleResolver(server);
res.setTSIGKey(keyname, keydata);
}
else if (operation.equals("edns")) {
if (res == null)
res = new SimpleResolver(server);
res.setEDNS(Short.parseShort(st.nextToken()));
}
else if (operation.equals("port")) {
if (res == null)
res = new SimpleResolver(server);
res.setPort(Short.parseShort(st.nextToken()));
}
else if (operation.equals("tcp")) {
if (res == null)
res = new SimpleResolver(server);
res.setTCP(true);
}
else if (operation.equals("class")) {
String s = st.nextToken();
short newClass = DClass.value(s);
if (newClass > 0)
defaultClass = newClass;
else
print("Invalid class " + newClass);
}
else if (operation.equals("ttl"))
defaultTTL = TTL.parseTTL(st.nextToken());
else if (operation.equals("origin") ||
operation.equals("zone"))
{
zone = Name.fromString(st.nextToken(),
Name.root);
}
else if (operation.equals("require"))
doRequire(st);
else if (operation.equals("prohibit"))
doProhibit(st);
else if (operation.equals("add"))
doAdd(st);
else if (operation.equals("delete"))
doDelete(st);
else if (operation.equals("glue"))
doGlue(st);
else if (operation.equals("help") ||
operation.equals("?"))
{
if (st.hasMoreTokens())
help(st.nextToken());
else
help(null);
}
else if (operation.equals("echo"))
print(line.substring(4).trim());
else if (operation.equals("send")) {
if (res == null)
res = new SimpleResolver(server);
sendUpdate();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("show")) {
print(query);
}
else if (operation.equals("clear")) {
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("query"))
doQuery(st);
else if (operation.equals("quit") ||
operation.equals("q"))
{
if (log != null)
log.close();
Iterator it = inputs.iterator();
while (it.hasNext()) {
BufferedReader tbr;
tbr = (BufferedReader) it.next();
tbr.close();
}
System.exit(0);
}
else if (operation.equals("file"))
doFile(st, inputs, istreams);
else if (operation.equals("log"))
doLog(st);
else if (operation.equals("assert")) {
if (doAssert(st) == false)
return;
}
else if (operation.equals("sleep")) {
int interval = Integer.parseInt(st.nextToken());
try {
Thread.sleep(interval);
}
catch (InterruptedException e) {
}
}
else if (operation.equals("date")) {
Date now = new Date();
if (st.hasMoreTokens() &&
st.nextToken().equals("-ms"))
print(Long.toString(now.getTime()));
else
print(now);
}
else
print("invalid keyword: " + operation);
}
catch (NullPointerException npe) {
System.out.println("Parse error");
}
catch (InterruptedIOException iioe) {
System.out.println("Operation timed out");
}
catch (SocketException se) {
System.out.println("Socket error");
}
catch (IOException ioe) {
System.out.println(ioe);
}
}
}
void
sendUpdate() throws IOException {
if (query.getHeader().getCount(Section.UPDATE) == 0) {
print("Empty update message. Ignoring.");
return;
}
if (query.getHeader().getCount(Section.ZONE) == 0) {
Name updzone;
updzone = zone;
short dclass = defaultClass;
if (updzone == null) {
Record [] recs = query.getSectionArray(Section.UPDATE);
for (int i = 0; i < recs.length; i++) {
if (updzone == null)
updzone = new Name(recs[i].getName(),
1);
if (recs[i].getDClass() != DClass.NONE &&
recs[i].getDClass() != DClass.ANY)
{
dclass = recs[i].getDClass();
break;
}
}
}
Record soa = Record.newRecord(updzone, Type.SOA, dclass);
query.addRecord(soa, Section.ZONE);
}
response = res.send(query);
if (response == null)
return;
print(response);
}
/*
* <name> [ttl] [class] <type> <data>
* Ignore the class, if present.
*/
Record
parseRR(MyStringTokenizer st, short classValue, int TTLValue)
throws IOException
{
Name name = Name.fromString(st.nextToken(), zone);
int ttl;
short type;
Record record;
String s = st.nextToken();
try {
ttl = TTL.parseTTL(s);
s = st.nextToken();
}
catch (NumberFormatException e) {
ttl = TTLValue;
}
if (DClass.value(s) >= 0) {
classValue = DClass.value(s);
s = st.nextToken();
}
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
record = Record.fromString(name, type, classValue, ttl, st, zone);
if (record != null)
return (record);
else
throw new IOException("Parse error");
}
void
doRequire(MyStringTokenizer st) throws IOException {
String s;
Name name;
Record record;
short type;
short dclass;
s = st.nextToken();
if (s.startsWith("-")) {
print("qualifiers are now ignored");
s = st.nextToken();
}
name = Name.fromString(s, zone);
if (st.hasMoreTokens()) {
s = st.nextToken();
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
if (st.hasMoreTokens()) {
record = Record.fromString(name, type, defaultClass,
0, st, zone);
}
else
record = Record.newRecord(name, type, DClass.ANY, 0);
}
else
record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
query.addRecord(record, Section.PREREQ);
print(record);
}
void
doProhibit(MyStringTokenizer st) throws IOException {
String s;
Name name;
Record record;
short type;
s = st.nextToken();
if (s.startsWith("-")) {
print("qualifiers are now ignored");
s = st.nextToken();
}
name = Name.fromString(s, zone);
if (st.hasMoreTokens()) {
s = st.nextToken();
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
}
else
type = Type.ANY;
if (st.hasMoreTokens())
throw new IOException("Cannot specify rdata to prohibit");
record = Record.newRecord(name, type, DClass.NONE, 0);
query.addRecord(record, Section.PREREQ);
print(record);
}
void
doAdd(MyStringTokenizer st) throws IOException {
String s;
Record record;
s = st.nextToken();
if (s.startsWith("-"))
print("qualifiers are now ignored");
else
st.putBackToken(s);
record = parseRR(st, defaultClass, defaultTTL);
query.addRecord(record, Section.UPDATE);
print(record);
}
void
doDelete(MyStringTokenizer st) throws IOException {
String s;
Name name;
Record record;
short type;
short dclass;
s = st.nextToken();
if (s.startsWith("-")) {
print("qualifiers are now ignored");
s = st.nextToken();
}
name = Name.fromString(s, zone);
if (st.hasMoreTokens()) {
s = st.nextToken();
if ((dclass = DClass.value(s)) >= 0) {
if (!st.hasMoreTokens())
throw new IOException("Invalid format");
s = st.nextToken();
}
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
if (st.hasMoreTokens()) {
record = Record.fromString(name, type, DClass.NONE,
0, st, zone);
}
else
record = Record.newRecord(name, type, DClass.ANY, 0);
}
else
record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
query.addRecord(record, Section.UPDATE);
print(record);
}
void
doGlue(MyStringTokenizer st) throws IOException {
String s;
Record record;
s = st.nextToken();
if (s.startsWith("-"))
print("qualifiers are now ignored");
else
st.putBackToken(s);
record = parseRR(st, defaultClass, defaultTTL);
query.addRecord(record, Section.ADDITIONAL);
print(record);
}
void
doQuery(MyStringTokenizer st) throws IOException {
Record rec;
Name name = null;
short type = Type.A, dclass = defaultClass;
name = Name.fromString(st.nextToken(), zone);
if (st.hasMoreTokens()) {
type = Type.value(st.nextToken());
if (type < 0)
throw new IOException("Invalid type");
if (st.hasMoreTokens()) {
dclass = DClass.value(st.nextToken());
if (dclass < 0)
throw new IOException("Invalid class");
}
}
rec = Record.newRecord(name, type, dclass);
Message newQuery = Message.newQuery(rec);
if (res == null)
res = new SimpleResolver(server);
response = res.send(newQuery);
print(response);
}
void
doFile(MyStringTokenizer st, List inputs, List istreams) {
String s = st.nextToken();
try {
InputStreamReader isr2;
if (!s.equals("-")) {
FileInputStream fis = new FileInputStream(s);
isr2 = new InputStreamReader(fis);
istreams.add(fis);
}
else {
isr2 = new InputStreamReader(System.in);
istreams.add(System.in);
}
BufferedReader br2 = new BufferedReader(isr2);
inputs.add(br2);
}
catch (FileNotFoundException e) {
print(s + "not found");
}
}
void
doLog(MyStringTokenizer st) {
String s = st.nextToken();
try {
FileOutputStream fos = new FileOutputStream(s);
log = new PrintStream(fos);
}
catch (Exception e) {
print("Error opening " + s);
}
}
boolean
doAssert(MyStringTokenizer st) {
String field = st.nextToken();
String expected = st.nextToken();
String value = null;
boolean flag = true;
int section;
if (response == null) {
print("No response has been received");
return true;
}
if (field.equalsIgnoreCase("rcode")) {
short rcode = response.getHeader().getRcode();
if (rcode != Rcode.value(expected)) {
value = Rcode.string(rcode);
flag = false;
}
}
else if (field.equalsIgnoreCase("serial")) {
Record [] answers = response.getSectionArray(Section.ANSWER);
if (answers.length < 1 || !(answers[0] instanceof SOARecord))
print("Invalid response (no SOA)");
else {
SOARecord soa = (SOARecord) answers[0];
int serial = soa.getSerial();
if (serial != Integer.parseInt(expected)) {
value = new Integer(serial).toString();
flag = false;
}
}
}
else if (field.equalsIgnoreCase("tsig")) {
if (response.isSigned()) {
if (response.isVerified())
value = "ok";
else
value = "failed";
}
else
value = "unsigned";
if (!value.equalsIgnoreCase(expected))
flag = false;
}
else if ((section = Section.value(field)) >= 0) {
int count = response.getHeader().getCount(section);
if (count != Integer.parseInt(expected)) {
value = new Integer(count).toString();
flag = false;
}
}
else
print("Invalid assertion keyword: " + field);
if (flag == false) {
print("Expected " + field + " " + expected +
", received " + value);
if (st.hasMoreTokens())
print(st.nextToken());
}
return flag;
}
static void
help(String topic) {
System.out.println();
if (topic == null)
System.out.println("The following are supported commands:\n" +
"add assert class clear date delete\n" +
"echo file glue help log key\n" +
"edns origin port prohibit query quit\n" +
"require send server show sleep tcp\n" +
"ttl zone
else if (topic.equalsIgnoreCase("add"))
System.out.println(
"add <name> [ttl] [class] <type> <data>\n\n" +
"specify a record to be added\n");
else if (topic.equalsIgnoreCase("assert"))
System.out.println(
"assert <field> <value> [msg]\n\n" +
"asserts that the value of the field in the last\n" +
"response matches the value specified. If not,\n" +
"the message is printed (if present) and the\n" +
"program exits. The field may be any of <rcode>,\n" +
"<serial>, <tsig>, <qu>, <an>, <au>, or <ad>.\n");
else if (topic.equalsIgnoreCase("class"))
System.out.println(
"class <class>\n\n" +
"class of the zone to be updated (default: IN)\n");
else if (topic.equalsIgnoreCase("clear"))
System.out.println(
"clear\n\n" +
"clears the current update packet\n");
else if (topic.equalsIgnoreCase("date"))
System.out.println(
"date [-ms]\n\n" +
"prints the current date and time in human readable\n" +
"format or as the number of milliseconds since the\n" +
"epoch");
else if (topic.equalsIgnoreCase("delete"))
System.out.println(
"delete <name> [ttl] [class] <type> <data> \n" +
"delete <name> <type> \n" +
"delete <name>\n\n" +
"specify a record or set to be deleted, or that\n" +
"all records at a name should be deleted\n");
else if (topic.equalsIgnoreCase("echo"))
System.out.println(
"echo <text>\n\n" +
"prints the text\n");
else if (topic.equalsIgnoreCase("file"))
System.out.println(
"file <file>\n\n" +
"opens the specified file as the new input source\n" +
"(- represents stdin)\n");
else if (topic.equalsIgnoreCase("glue"))
System.out.println(
"glue <name> [ttl] [class] <type> <data>\n\n" +
"specify an additional record\n");
else if (topic.equalsIgnoreCase("help"))
System.out.println(
"?/help\n" +
"help [topic]\n\n" +
"prints a list of commands or help about a specific\n" +
"command\n");
else if (topic.equalsIgnoreCase("log"))
System.out.println(
"log <file>\n\n" +
"opens the specified file and uses it to log output\n");
else if (topic.equalsIgnoreCase("key"))
System.out.println(
"key <name> <data>\n\n" +
"TSIG key used to sign messages\n");
else if (topic.equalsIgnoreCase("edns"))
System.out.println(
"edns <level>\n\n" +
"EDNS level specified when sending messages\n");
else if (topic.equalsIgnoreCase("origin"))
System.out.println(
"origin <origin>\n\n" +
"<same as zone>\n");
else if (topic.equalsIgnoreCase("port"))
System.out.println(
"port <port>\n\n" +
"UDP/TCP port messages are sent to (default: 53)\n");
else if (topic.equalsIgnoreCase("prohibit"))
System.out.println(
"prohibit <name> <type> \n" +
"prohibit <name>\n\n" +
"require that a set or name is not present\n");
else if (topic.equalsIgnoreCase("query"))
System.out.println(
"query <name> [type [class]] \n\n" +
"issues a query\n");
else if (topic.equalsIgnoreCase("q") ||
topic.equalsIgnoreCase("quit"))
System.out.println(
"q/quit\n\n" +
"quits the program\n");
else if (topic.equalsIgnoreCase("require"))
System.out.println(
"require <name> [ttl] [class] <type> <data> \n" +
"require <name> <type> \n" +
"require <name>\n\n" +
"require that a record, set, or name is present\n");
else if (topic.equalsIgnoreCase("send"))
System.out.println(
"send\n\n" +
"sends and resets the current update packet\n");
else if (topic.equalsIgnoreCase("server"))
System.out.println(
"server <name> [port]\n\n" +
"server that receives send updates/queries\n");
else if (topic.equalsIgnoreCase("show"))
System.out.println(
"show\n\n" +
"shows the current update packet\n");
else if (topic.equalsIgnoreCase("sleep"))
System.out.println(
"sleep <milliseconds>\n\n" +
"pause for interval before next command\n");
else if (topic.equalsIgnoreCase("tcp"))
System.out.println(
"tcp\n\n" +
"TCP should be used to send all messages\n");
else if (topic.equalsIgnoreCase("ttl"))
System.out.println(
"ttl <ttl>\n\n" +
"default ttl of added records (default: 0)\n");
else if (topic.equalsIgnoreCase("zone"))
System.out.println(
"zone <zone>\n\n" +
"zone to update (default: .\n");
else if (topic.equalsIgnoreCase("
System.out.println(
"# <text>\n\n" +
"a comment\n");
else
System.out.println ("Topic '" + topic + "' unrecognized\n");
}
public static void
main(String args[]) throws IOException {
InputStream in = null;
if (args.length == 1) {
try {
in = new FileInputStream(args[0]);
}
catch (FileNotFoundException e) {
System.out.println(args[0] + " not found.");
System.exit(-1);
}
}
else
in = System.in;
update u = new update(in);
}
}
|
package org.geomajas.plugin.deskmanager.client.gwt.manager.datalayer.panels;
import com.google.gwt.core.client.GWT;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.ListGridEditEvent;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.ChangeEvent;
import com.smartgwt.client.widgets.grid.events.ChangeHandler;
import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler;
import com.smartgwt.client.widgets.grid.events.SelectionEvent;
import com.smartgwt.client.widgets.layout.VLayout;
import org.geomajas.configuration.AttributeInfo;
import org.geomajas.configuration.FeatureInfo;
import org.geomajas.configuration.PrimitiveAttributeInfo;
import org.geomajas.configuration.PrimitiveType;
import org.geomajas.gwt.client.Geomajas;
import org.geomajas.plugin.deskmanager.client.gwt.manager.i18n.ManagerMessages;
import org.geomajas.plugin.deskmanager.command.manager.dto.DynamicVectorLayerConfiguration;
import java.util.LinkedHashMap;
/**
* @author Kristof Heirwegh
*/
@SuppressWarnings("deprecation")
public class LayerAttributesGrid extends VLayout {
private static final ManagerMessages MESSAGES = GWT.create(ManagerMessages.class);
private static final String FLD_NAME = "name";
private static final String FLD_TYPE = "type";
private static final String FLD_IDENTIFYING = "identifying";
private static final String FLD_IDFIELD = "idField";
private static final String FLD_LABELFIELD = "labelField";
private static final String FLD_LABEL = "label";
private static final String FLD_OBJECT = "_object";
private DynamicVectorLayerConfiguration layerConfig;
private ListGrid grid;
private Label warnings;
private ListGridRecord currentIdField;
private ListGridRecord currentLabelField;
public LayerAttributesGrid() {
super(5);
grid = new ListGrid();
grid.setWidth100();
grid.setHeight("*");
grid.setSelectionType(SelectionStyle.SINGLE);
grid.setShowAllRecords(true);
grid.setSelectionType(SelectionStyle.SIMPLE);
grid.setSelectionAppearance(SelectionAppearance.CHECKBOX);
grid.setCanEdit(true);
grid.setEditEvent(ListGridEditEvent.NONE);
grid.setEditByCell(false);
grid.setShowEmptyMessage(true);
grid.setEmptyMessage("<i>" + MESSAGES.layerAttributesGridLoadingText() +
" <img src='" + Geomajas.getIsomorphicDir()
+ "/images/circle.gif' style='height: 1em' /></i>");
ListGridField nameFld = new ListGridField(FLD_NAME, MESSAGES.layerAttributesGridColumnAttribute());
nameFld.setType(ListGridFieldType.TEXT);
nameFld.setWidth("*");
nameFld.setCanEdit(false);
ListGridField typeFld = new ListGridField(FLD_TYPE, MESSAGES.layerAttributesGridColumnType());
typeFld.setType(ListGridFieldType.TEXT);
typeFld.setCanEdit(true);
typeFld.setWidth(55);
SelectItem editor = new SelectItem();
editor.setValueMap(getTypes());
typeFld.setEditorType(editor);
ListGridField identifyingFld = new ListGridField(FLD_IDENTIFYING, MESSAGES.layerAttributesGridColumnCoreInfo());
identifyingFld.setType(ListGridFieldType.BOOLEAN);
identifyingFld.setCanEdit(true);
identifyingFld.setPrompt(MESSAGES.layerAttributesGridColumnCoreInfoTooltip());
identifyingFld.addChangeHandler(new ChangeHandler() {
public void onChange(ChangeEvent event) {
Object value = event.getValue();
if (value instanceof Boolean && Boolean.TRUE.equals(value)) {
grid.selectRecord(grid.getRecord(event.getRowNum()));
}
}
});
ListGridField idFieldFld = new ListGridField(FLD_IDFIELD, MESSAGES.layerAttributesGridColumnIdField());
idFieldFld.setType(ListGridFieldType.BOOLEAN);
idFieldFld.setCanEdit(true);
idFieldFld.setPrompt(MESSAGES.layerAttributesGridColumnIdFieldTooltip());
idFieldFld.addChangeHandler(new ChangeHandler() {
public void onChange(ChangeEvent event) {
ListGridRecord lgr = grid.getRecord(event.getRowNum());
if (!lgr.equals(currentIdField)) {
// deselect id checkbox in former id field
currentIdField.setAttribute(FLD_IDFIELD, false);
// update currentIdField
currentIdField = lgr;
if (!isRecordSelected(lgr)) {
grid.selectRecord(lgr);
}
}
}
});
ListGridField labelFieldFld = new ListGridField(FLD_LABELFIELD, MESSAGES.layerAttributesGridColumnLabelField());
labelFieldFld.setType(ListGridFieldType.BOOLEAN);
labelFieldFld.setCanEdit(true);
labelFieldFld.setPrompt(MESSAGES.layerAttributesGridColumnLabelFieldTooltip());
labelFieldFld.addChangeHandler(new ChangeHandler() {
public void onChange(ChangeEvent event) {
ListGridRecord lgr = grid.getRecord(event.getRowNum());
if (!lgr.equals(currentLabelField)) {
// deselect label checkbox in former label field
currentLabelField.setAttribute(FLD_LABELFIELD, false);
// update currentLabelField
currentLabelField = lgr;
if (!isRecordSelected(lgr)) {
grid.selectRecord(lgr);
}
}
}
});
ListGridField labelFld = new ListGridField(FLD_LABEL, MESSAGES.layerAttributesGridColumnName());
labelFld.setType(ListGridFieldType.TEXT);
labelFld.setCanEdit(true);
labelFld.setPrompt(MESSAGES.layerAttributesGridColumnNameTooltip());
grid.setFields(nameFld, typeFld, identifyingFld, idFieldFld, labelFieldFld, labelFld);
grid.setCanResizeFields(true);
grid.addSelectionChangedHandler(new SelectionChangedHandler() {
public void onSelectionChanged(SelectionEvent event) {
ListGridRecord lgr = event.getRecord();
// on deselection of record, set FLD_IDENTIFYING false
if (!isRecordSelected(lgr)) {
lgr.setAttribute(FLD_IDENTIFYING, false);
}
checkSelectionStatusOfRecordForIdAndLabelFields(event.getRecord());
}
});
warnings = new Label();
warnings.setWidth100();
warnings.setAutoHeight();
warnings.setPadding(3);
warnings.setOverflow(Overflow.VISIBLE);
warnings.setVisible(false);
warnings.setBackgroundColor("#FFCCCC");
addMember(grid);
addMember(warnings);
}
public void setData(DynamicVectorLayerConfiguration layerConfig) {
this.layerConfig = layerConfig;
FeatureInfo fi = layerConfig.getClientVectorLayerInfo().getFeatureInfo();
String labelFieldName = layerConfig.getClientVectorLayerInfo().getNamedStyleInfo().getLabelStyle()
.getLabelAttributeName();
PrimitiveAttributeInfo idField = fi.getIdentifier();
for (AttributeInfo ai : fi.getAttributes()) {
if (ai instanceof PrimitiveAttributeInfo) {
ListGridRecord lgr = new ListGridRecord();
PrimitiveAttributeInfo pai = (PrimitiveAttributeInfo) ai;
lgr.setAttribute(FLD_NAME, pai.getName());
lgr.setAttribute(FLD_TYPE, pai.getType().toString());
lgr.setAttribute(FLD_IDENTIFYING, pai.isIdentifying());
lgr.setAttribute(FLD_IDFIELD, (pai.equals(idField)));
lgr.setAttribute(FLD_LABELFIELD, pai.getName().equals(labelFieldName));
lgr.setAttribute(FLD_LABEL, pai.getLabel());
lgr.setAttribute(FLD_OBJECT, pai);
grid.addData(lgr);
if (pai.getName().equals(labelFieldName)) {
currentLabelField = lgr;
}
if (pai.equals(idField)) {
currentIdField = lgr;
}
if (!pai.isHidden()) {
grid.selectRecord(lgr);
}
} // else unsupported
}
}
public DynamicVectorLayerConfiguration getData() {
if (currentIdField == null || currentLabelField == null) {
return null;
}
FeatureInfo fi = layerConfig.getClientVectorLayerInfo().getFeatureInfo();
fi.setIdentifier((PrimitiveAttributeInfo) currentIdField.getAttributeAsObject(FLD_OBJECT));
layerConfig.getClientVectorLayerInfo().getNamedStyleInfo().getLabelStyle()
.setLabelAttributeName(currentLabelField.getAttributeAsString(FLD_NAME));
for (ListGridRecord r : grid.getRecords()) {
PrimitiveAttributeInfo pai = (PrimitiveAttributeInfo) r.getAttributeAsObject(FLD_OBJECT);
pai.setLabel(r.getAttributeAsString(FLD_LABEL));
pai.setIdentifying(r.getAttributeAsBoolean(FLD_IDENTIFYING));
pai.setHidden(!grid.isSelected(r));
pai.setType(PrimitiveType.fromValue(r.getAttributeAsString(FLD_TYPE)));
}
return layerConfig;
}
public void reset() {
grid.deselectAllRecords();
grid.setData(new Record[]{});
warnings.setVisible(false);
warnings.setContents("");
}
public void setWarning(String warning) {
if (warning == null || "".equals(warning)) {
warnings.setVisible(false);
warnings.setContents("");
} else {
warnings.setVisible(true);
warnings.setContents(warning);
}
}
public boolean isValid() {
return (!warnings.isVisible());
}
private LinkedHashMap<String, String> getTypes() {
LinkedHashMap<String, String> values = new LinkedHashMap<String, String>();
for (PrimitiveType type : PrimitiveType.values()) {
values.put(type.toString(), type.toString());
}
return values;
}
/**
* Checks whether {@link ListGridRecord} can be deselected. When deselected, but the record
* contains id or label check, the record is selected again and a warning is shown.
*
* @param lgr
*/
private void checkSelectionStatusOfRecordForIdAndLabelFields(ListGridRecord lgr) {
if (!isRecordSelected(lgr)) { // deselected
warnings.setVisible(false);
if (lgr.equals(currentIdField)) {
warnings.setContents(MESSAGES.layerAttributesGriDeselectIdAttribute());
warnings.setVisible(true);
grid.selectRecord(lgr);
} else if (lgr.equals(currentLabelField)) {
warnings.setContents(MESSAGES.layerAttributesGriDeselectLabelAttribute());
warnings.setVisible(true);
grid.selectRecord(lgr);
}
}
}
private boolean isRecordSelected(ListGridRecord lgr) {
return grid.isSelected(lgr);
}
}
|
package com.worth.ifs.application.controller;
import com.worth.ifs.application.resource.FormInputResponseFileEntryId;
import com.worth.ifs.application.resource.FormInputResponseFileEntryResource;
import com.worth.ifs.application.transactional.ApplicationService;
import com.worth.ifs.commons.controller.ServiceFailureToJsonResponseHandler;
import com.worth.ifs.commons.controller.SimpleServiceFailureToJsonResponseHandler;
import com.worth.ifs.file.resource.FileEntryResource;
import com.worth.ifs.transactional.ServiceFailure;
import com.worth.ifs.transactional.ServiceSuccess;
import com.worth.ifs.util.Either;
import com.worth.ifs.util.JsonStatusResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import static com.worth.ifs.application.controller.FormInputResponseFileEntryJsonStatusResponse.fileEntryCreated;
import static com.worth.ifs.application.transactional.ApplicationServiceImpl.ServiceFailures.UNABLE_TO_FIND_FILE;
import static com.worth.ifs.transactional.BaseTransactionalService.Failures.*;
import static com.worth.ifs.util.Either.left;
import static com.worth.ifs.util.Either.right;
import static com.worth.ifs.util.JsonStatusResponse.*;
import static com.worth.ifs.util.ParsingFunctions.validLong;
import static java.util.Arrays.asList;
import static java.util.Optional.empty;
import static java.util.stream.Collectors.joining;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController
@RequestMapping("/forminputresponse")
public class FormInputResponseFileUploadController {
private static final Log LOG = LogFactory.getLog(FormInputResponseFileUploadController.class);
@Value("${ifs.data.service.file.storage.fileinputresponse.max.filesize.bytes}")
private Long maxFilesizeBytes;
@Value("${ifs.data.service.file.storage.fileinputresponse.valid.media.types}")
private List<String> validMediaTypes;
@Autowired
private ApplicationService applicationService;
private List<ServiceFailureToJsonResponseHandler> serviceFailureHandlers = asList(
new SimpleServiceFailureToJsonResponseHandler(asList(UNABLE_TO_FIND_FILE), (serviceFailure, response) -> notFound("Unable to find file", response)),
new SimpleServiceFailureToJsonResponseHandler(asList(FORM_INPUT_NOT_FOUND), (serviceFailure, response) -> notFound("Unable to find Form Input", response)),
new SimpleServiceFailureToJsonResponseHandler(asList(APPLICATION_NOT_FOUND), (serviceFailure, response) -> notFound("Unable to find Application", response)),
new SimpleServiceFailureToJsonResponseHandler(asList(PROCESS_ROLE_NOT_FOUND), (serviceFailure, response) -> notFound("Unable to find Process Role", response)),
new SimpleServiceFailureToJsonResponseHandler(asList(FORM_INPUT_RESPONSE_NOT_FOUND), (serviceFailure, response) -> notFound("Unable to find Form Input Response", response))
);
@RequestMapping(value = "/file", method = POST, produces = "application/json")
public JsonStatusResponse createFile(
@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam("formInputId") long formInputId,
@RequestParam("applicationId") long applicationId,
@RequestParam("processRoleId") long processRoleId,
@RequestParam(value = "filename", required = false) String originalFilename,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
Supplier<JsonStatusResponse> internalServerError = () -> internalServerError("Error creating file", response);
return handlingErrors(internalServerError, () -> {
Either<JsonStatusResponse, JsonStatusResponse> result =
validContentLengthHeader(contentLength, response).
map(lengthFromHeader -> validContentTypeHeader(contentType, response).
map(typeFromHeader -> validFilename(originalFilename, response).
map(filenameParameter -> validContentLength(lengthFromHeader, response).
map(validLength -> validMediaType(typeFromHeader, response).
map(validType -> createFormInputResponseFile(validType, lengthFromHeader, originalFilename, formInputId, applicationId, processRoleId, request, response).
map(fileEntry -> returnFileEntryId(fileEntry)
))))));
return result;
}).mapLeftOrRight(failure -> failure, success -> success);
}
@RequestMapping(value = "/file", method = GET)
public @ResponseBody ResponseEntity<?> getFile(
@RequestParam("formInputId") long formInputId,
@RequestParam("applicationId") long applicationId,
@RequestParam("processRoleId") long processRoleId,
HttpServletResponse response) throws IOException {
Supplier<JsonStatusResponse> internalServerError = () -> internalServerError("Error retrieving file", response);
return handlingErrorsWithResponseEntity(internalServerError, () -> {
Either<JsonStatusResponse, Pair<FormInputResponseFileEntryResource, Supplier<InputStream>>> result =
doGetFile(formInputId, applicationId, processRoleId, response);
return result.mapLeftOrRight(
failure ->
Either. <ResponseEntity<JsonStatusResponse>, ResponseEntity<?>> left(new ResponseEntity<>(failure, failure.getStatus())),
success -> {
FormInputResponseFileEntryResource fileEntry = success.getKey();
InputStream inputStream = success.getValue().get();
InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentLength(fileEntry.getFileEntryResource().getFilesizeBytes());
httpHeaders.setContentType(fileEntry.getFileEntryResource().getMediaType());
return Either. <ResponseEntity<JsonStatusResponse>, ResponseEntity<?>> right(new ResponseEntity<>(inputStreamResource, httpHeaders, HttpStatus.OK));
}
);
}).mapLeftOrRight(failure -> failure, success -> success);
}
private Either<JsonStatusResponse, Pair<FormInputResponseFileEntryResource, Supplier<InputStream>>> doGetFile(long formInputId, long applicationId, long processRoleId, HttpServletResponse response) {
FormInputResponseFileEntryId formInputResponseFileEntryId = new FormInputResponseFileEntryId(formInputId, applicationId, processRoleId);
Either<ServiceFailure, ServiceSuccess<Pair<FormInputResponseFileEntryResource, Supplier<InputStream>>>> file =
applicationService.getFormInputResponseFileUpload(formInputResponseFileEntryId);
return file.mapLeftOrRight(
failure ->
Either. <JsonStatusResponse, Pair<FormInputResponseFileEntryResource, Supplier<InputStream>>> left(handleServiceFailure(failure, response).orElseGet(() -> internalServerError("Error retrieving file", response))),
success ->
Either. <JsonStatusResponse, Pair<FormInputResponseFileEntryResource, Supplier<InputStream>>> right(success.getResult())
);
}
private Optional<JsonStatusResponse> handleServiceFailure(ServiceFailure serviceFailure, HttpServletResponse response) {
for (ServiceFailureToJsonResponseHandler handler : serviceFailureHandlers) {
Optional<JsonStatusResponse> result = handler.handle(serviceFailure, response);
if (result.isPresent()) {
return result;
}
}
return empty();
}
/**
* This wrapper wraps the serviceCode function and rolls back transactions upon receiving a ServiceFailure
* response (an Either with a left of ServiceFailure).
*
* It will also catch all exceptions thrown from within serviceCode and convert them into ServiceFailures of
* type UNEXPECTED_ERROR.
*
* @param serviceCode
* @return
*/
protected Either<JsonStatusResponse, JsonStatusResponse> handlingErrors(Supplier<JsonStatusResponse> catchAllError, Supplier<Either<JsonStatusResponse, JsonStatusResponse>> serviceCode) {
try {
Either<JsonStatusResponse, JsonStatusResponse> response = serviceCode.get();
if (response.isLeft()) {
LOG.debug("Controller failure encountered");
}
return response;
} catch (Exception e) {
LOG.warn("Uncaught exception encountered while performing Controller call - returning catch-all error", e);
return left(catchAllError.get());
}
}
/**
* This wrapper wraps the serviceCode function, catching all exceptions thrown from within serviceCode and converting them into failing JsonStatusResponses.
*
* @param serviceCode
* @return
*/
protected Either<ResponseEntity<JsonStatusResponse>, ResponseEntity<?>> handlingErrorsWithResponseEntity(
Supplier<JsonStatusResponse> catchAllError,
Supplier<Either<ResponseEntity<JsonStatusResponse>, ResponseEntity<?>>> serviceCode) {
try {
Either<ResponseEntity<JsonStatusResponse>, ResponseEntity<?>> response = serviceCode.get();
if (response.isLeft()) {
LOG.debug("Controller failure encountered");
}
return response;
} catch (Exception e) {
LOG.warn("Uncaught exception encountered while performing Controller call - returning catch-all error", e);
return left(new ResponseEntity<>(catchAllError.get(), HttpStatus.INTERNAL_SERVER_ERROR));
}
}
private Either<JsonStatusResponse, JsonStatusResponse> returnFileEntryId(FormInputResponseFileEntryResource fileEntry) {
return right(fileEntryCreated(fileEntry.getFileEntryResource().getId()));
}
private Either<JsonStatusResponse, FormInputResponseFileEntryResource> createFormInputResponseFile(MediaType mediaType, long length, String originalFilename, long formInputId, long applicationId, long processRoleId, HttpServletRequest request, HttpServletResponse response) {
LOG.debug("Creating file with filename - " + originalFilename + "; Content Type - " + mediaType + "; Content Length - " + length);
FileEntryResource fileEntry = new FileEntryResource(null, originalFilename, mediaType, length);
FormInputResponseFileEntryResource formInputResponseFile = new FormInputResponseFileEntryResource(fileEntry, formInputId, applicationId, processRoleId);
Either<ServiceFailure, ServiceSuccess<Pair<File, FormInputResponseFileEntryResource>>> creationResult = applicationService.createFormInputResponseFileUpload(formInputResponseFile, inputStreamSupplier(request));
return creationResult.mapLeftOrRight(
failure -> left(handleServiceFailure(failure, response).orElseGet(() -> internalServerError("Error creating file", response))),
success -> right(success.getResult().getValue()));
}
private Supplier<InputStream> inputStreamSupplier(HttpServletRequest request) {
return () -> {
try {
return request.getInputStream();
} catch (IOException e) {
LOG.error("Unable to open an input stream from request", e);
throw new RuntimeException("Unable to open an input stream from request", e);
}
};
}
private Either<JsonStatusResponse, Long> validContentLengthHeader(String contentLengthHeader, HttpServletResponse response) {
return validLong(contentLengthHeader).map(length -> Either.<JsonStatusResponse, Long> right(length)).
orElseGet(() -> left(lengthRequired("Please supply a valid Content-Length HTTP header. Maximum " + maxFilesizeBytes, response)));
}
private Either<JsonStatusResponse, String> validContentTypeHeader(String contentTypeHeader, HttpServletResponse response) {
return !StringUtils.isBlank(contentTypeHeader) ? right(contentTypeHeader) :
left(unsupportedMediaType("Please supply a valid Content-Type HTTP header. Valid types are " + validMediaTypes.stream().collect(joining(", ")), response));
}
private Either<JsonStatusResponse, Long> validContentLength(long length, HttpServletResponse response) {
if (length > maxFilesizeBytes) {
return left(payloadTooLarge("File upload was too large for FormInputResponse. Max filesize in bytes is " + maxFilesizeBytes, response));
}
return right(length);
}
private Either<JsonStatusResponse, String> validFilename(String filename, HttpServletResponse response) {
return checkParameterIsPresent(filename, "Please supply an original filename as a \"filename\" HTTP Request Parameter", response);
}
private Either<JsonStatusResponse, MediaType> validMediaType(String contentType, HttpServletResponse response) {
if (!validMediaTypes.contains(contentType)) {
return left(unsupportedMediaType("Please supply a valid Content-Type HTTP header. Valid types are " + validMediaTypes.stream().collect(joining(", ")), response));
}
return right(MediaType.valueOf(contentType));
}
private Either<JsonStatusResponse, String> checkParameterIsPresent(String parameterValue, String failureMessage, HttpServletResponse response) {
return !StringUtils.isBlank(parameterValue) ? right(parameterValue) : left(badRequest(failureMessage, response));
}
void setMaxFilesizeBytes(Long maxFilesizeBytes) {
this.maxFilesizeBytes = maxFilesizeBytes;
}
void setValidMediaTypes(List<String> validMediaTypes) {
this.validMediaTypes = validMediaTypes;
}
}
|
package org.languagetool.rules.sv;
import org.junit.Test;
import org.languagetool.rules.spelling.SpellcheckerTest;
import java.io.IOException;
public class LanguageSpecificSpellcheckerTest extends SpellcheckerTest {
@Test
public void testRules() throws IOException {
runLanguageSpecificTest();
}
}
|
package de.qaware.oss.cloud.service.billing.integration;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.logging.Logger;
@Singleton
@Startup
public class AutostartBean {
@Inject
private Logger logger;
@PersistenceContext
private EntityManager entityManager;
@PostConstruct
void autostart() {
logger.info("Autostarting Billing service entity manager.");
entityManager.clear();
}
}
|
package org.activiti.cycle.impl.connector.fs.provider;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.activiti.cycle.Content;
import org.activiti.cycle.ContentType;
import org.activiti.cycle.RepositoryArtifact;
import org.activiti.cycle.RepositoryException;
public class FileSystemTextProvider extends FileSystemContentRepresentationProvider {
public static final String NAME = "Text";
public FileSystemTextProvider() {
super(NAME, ContentType.TEXT, true);
}
@Override
public void addValueToContent(Content content, RepositoryArtifact artifact) {
File file = new File(getConnector(artifact).getConfiguration().getBasePath() + artifact.getId());
try{
content.setValue(new FileInputStream(file));
} catch (FileNotFoundException fnfe) {
throw new RepositoryException("Unable to find artifact " + artifact, fnfe);
}
}
}
|
package org.nuxeo.ecm.automation.jbpm;
import java.io.Serializable;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.automation.OperationContext;
import org.nuxeo.ecm.automation.OperationException;
import org.nuxeo.ecm.automation.core.Constants;
import org.nuxeo.ecm.automation.core.annotations.Context;
import org.nuxeo.ecm.automation.core.annotations.Operation;
import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
import org.nuxeo.ecm.automation.core.annotations.Param;
import org.nuxeo.ecm.automation.core.util.StringList;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.api.NuxeoPrincipal;
import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
import org.nuxeo.ecm.platform.jbpm.JbpmTaskService;
/**
* Creates a task
*
* @author Anahide Tchertchian
*/
@Operation(id = CreateTask.ID, category = Constants.CAT_SERVICES, label = "Create task", since = "5.3.2", description = "Enable to create a task binded to the document. "
+ "<p><b>Directive</b>, <b>comment</b> and <b>due date</b> will be displayed in the task list of the user. "
+ "In <b>accept operation chain</b> and <b>reject operation chain</b> fields, "
+ "you can put the operation chain ID of your choice among the one you contributed. "
+ "Those operations will be executed when the user validates the task, "
+ "depending on whether he accepts or rejects the task. "
+ "You have to specifiy a variable name (the <b>key for ... </b> parameter) to resolve target users and groups to which the task will be assigned. "
+ "You can use Get Users and Groups to update a context variable with some users and groups. "
+ "If you check <b>create one task per actor</b>, each of the actors will have a task to achieve, "
+ "versus \"the first who achieve the task makes it disappear for the others\".</p>")
public class CreateTask {
public final static String ID = "Workflow.CreateTask";
private static final Log log = LogFactory.getLog(CreateTask.class);
public enum OperationTaskVariableName {
acceptOperationChain, rejectOperationChain, createdFromCreateTaskOperation
}
@Context
protected OperationContext ctx;
@Context
protected CoreSession coreSession;
@Context
protected JbpmTaskService jbpmTaskService;
@Param(name = "task name", required = true, order = 0)
protected String taskName;
@Param(name = "due date", required = false, order = 1)
protected Date dueDate;
@Param(name = "directive", required = false, order = 2)
protected String directive;
@Param(name = "comment", required = false, order = 3)
protected String comment;
@Param(name = "accept operation chain", required = false, order = 4)
protected String acceptOperationChain;
@Param(name = "reject operation chain", required = false, order = 5)
protected String rejectOperationChain;
@Param(name = "variable name for actors prefixed ids", required = false, order = 6)
protected String keyForActors;
@Param(name = "additional list of actors prefixed ids", required = false, order = 7)
protected StringList additionalPrefixedActors;
@Param(name = "create one task per actor", required = false, values = "true", order = 8)
protected boolean createOneTaskPerActor = true;
@OperationMethod
public DocumentModelList run(DocumentModelList docs) throws Exception {
DocumentModelListImpl result = new DocumentModelListImpl(
(int) docs.totalSize());
for (DocumentModel doc : docs) {
result.add(run(doc));
}
return result;
}
@OperationMethod
@SuppressWarnings("unchecked")
public DocumentModel run(DocumentModel document) throws Exception {
Principal pal = coreSession.getPrincipal();
if (!(pal instanceof NuxeoPrincipal)) {
throw new OperationException(
"Principal is not an instance of NuxeoPrincipal");
}
List<String> prefixedActorIds = new ArrayList<String>();
Object actors = ctx.get(keyForActors);
if (actors != null) {
try {
prefixedActorIds.addAll((List) actors);
} catch (ClassCastException e) {
throw new OperationException(String.format(
"Invalid key to retrieve a list of prefixed actor "
+ "ids '%s', value is not correct: %s",
keyForActors, actors));
}
}
if (additionalPrefixedActors != null) {
prefixedActorIds.addAll(additionalPrefixedActors);
}
if (prefixedActorIds == null || prefixedActorIds.isEmpty()) {
// no actors: do nothing
log.debug("No actors could be resolved => do not create any task");
return document;
}
// create the task, passing operation chains in task variables
Map<String, Serializable> taskVariables = new HashMap<String, Serializable>();
taskVariables.put(
OperationTaskVariableName.createdFromCreateTaskOperation.name(),
"true");
if (!StringUtils.isEmpty(acceptOperationChain)) {
taskVariables.put(
OperationTaskVariableName.acceptOperationChain.name(),
acceptOperationChain);
}
if (!StringUtils.isEmpty(rejectOperationChain)) {
taskVariables.put(
OperationTaskVariableName.rejectOperationChain.name(),
rejectOperationChain);
}
if (jbpmTaskService == null) {
throw new OperationException("Service jbpmTaskService not found");
}
jbpmTaskService.createTask(coreSession, (NuxeoPrincipal) pal, document,
taskName, prefixedActorIds, createOneTaskPerActor, directive,
comment, dueDate, taskVariables);
return document;
}
}
|
package org.opencms.gwt.client.ui;
import org.opencms.gwt.client.ui.css.I_CmsLayoutBundle;
import org.opencms.gwt.client.util.CmsDomUtil;
import org.opencms.gwt.client.util.CmsDomUtil.Method;
import java.util.Map;
import com.google.gwt.dom.client.FormElement;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
/**
* Frame dialog utility class.<p>
*
* Use to render the dialog content within an iFrame on top of a regular {@link org.opencms.gwt.client.ui.CmsPopup}.
* May also be used to wrap the popup if no iFrame is needed.<p>
*
* Provides function to show an iFrame dialog.<p>
*
* @since 8.5
*/
public class CmsFrameDialog {
/** The name of the close function. */
public static final String CLOSE_FUNCTION = "cmsDialogClose";
/** The dialog height. */
public static final int DIALOG_HEIGHT = 300;
/** The dialog width. */
public static final int DIALOG_WIDTH = 200;
/** The name of the dialog height function. */
public static final String HEIGHT_FUNCTION = "cmsDialogHeight";
/** The name of the IFrame used for displaying the upload hook page. */
public static final String IFRAME_NAME = "upload_hook";
/** The name of the dialog title function. */
public static final String TITLE_FUNCTION = "cmsDialogTitle";
/** The name of the dialog width function. */
public static final String WIDTH_FUNCTION = "cmsUploadHookDialogWidth";
/** The button panel. */
private FlowPanel m_buttonPanel;
/** The content widget. */
private Widget m_content;
/** The panel holding the content widget. */
private SimplePanel m_contentPanel;
/** Flag indicating if this dialog is displayed within an iFrame on top of a popup. */
private boolean m_isFrame;
/** Flag indicating that the dialog is showing.< */
private boolean m_isShowing;
/** The main panel. */
private FlowPanel m_main;
/** The popup. */
private CmsPopup m_popup;
/**
* Constructor.<p>
*/
public CmsFrameDialog() {
m_isFrame = hasParentFrame();
if (m_isFrame) {
m_main = new FlowPanel();
m_contentPanel = new SimplePanel();
m_contentPanel.addStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().popupMainContent());
m_contentPanel.addStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().contentPadding());
m_main.add(m_contentPanel);
} else {
m_popup = new CmsPopup();
m_popup.setGlassEnabled(true);
}
}
/**
* Returns if this dialog has a parent frame.<p>
*
* @return <code>true</code> if the parent frame is available
*/
public static native boolean hasParentFrame() /*-{
if ($wnd.parent[@org.opencms.gwt.client.ui.CmsFrameDialog::CLOSE_FUNCTION]) {
return true;
}
return false;
}-*/;
/**
* Shows an iFrame dialog popup.<p>
*
* @param title the dialog title
* @param dialogUri the dialog URI
* @param parameters the dialog post parameters
* @param closeHandler the dialog close handler
*
* @return the opened popup
*/
public static CmsPopup showFrameDialog(
String title,
String dialogUri,
Map<String, String> parameters,
CloseHandler<PopupPanel> closeHandler) {
CmsPopup popup = new CmsPopup(title);
popup.addStyleName(I_CmsLayoutBundle.INSTANCE.contentEditorCss().contentEditor());
popup.removePadding();
popup.setGlassEnabled(true);
CmsIFrame editorFrame = new CmsIFrame(IFRAME_NAME, "");
popup.add(editorFrame);
final FormElement formElement = CmsDomUtil.generateHiddenForm(dialogUri, Method.post, IFRAME_NAME, parameters);
RootPanel.getBodyElement().appendChild(formElement);
exportDialogFunctions(popup);
popup.addCloseHandler(new CloseHandler<PopupPanel>() {
public void onClose(CloseEvent<PopupPanel> event) {
formElement.removeFromParent();
removeExportedFunctions();
}
});
popup.addCloseHandler(closeHandler);
popup.center();
formElement.submit();
return popup;
}
/**
* Removes exported functions from the window context.<p>
*/
protected static native void removeExportedFunctions() /*-{
$wnd[@org.opencms.gwt.client.ui.CmsFrameDialog::CLOSE_FUNCTION] = null;
$wnd[@org.opencms.gwt.client.ui.CmsFrameDialog::HEIGHT_FUNCTION] = null;
$wnd[@org.opencms.gwt.client.ui.CmsFrameDialog::WIDTH_FUNCTION] = null;
$wnd[@org.opencms.gwt.client.ui.CmsFrameDialog::TITLE_FUNCTION] = null;
}-*/;
/**
* Installs the Javascript function which should be called by the child iframe when the dialog should be closed.<p>
*
* @param popup the popup
*/
private static native void exportDialogFunctions(final CmsPopup popup) /*-{
var self = this;
$wnd[@org.opencms.gwt.client.ui.CmsFrameDialog::CLOSE_FUNCTION] = function() {
popup.@org.opencms.gwt.client.ui.CmsPopup::hide()();
};
$wnd[@org.opencms.gwt.client.ui.CmsFrameDialog::HEIGHT_FUNCTION] = function(
height) {
popup.@org.opencms.gwt.client.ui.CmsPopup::setHeight(I)(height);
if (popup.@org.opencms.gwt.client.ui.CmsPopup::isShowing()) {
popup.@org.opencms.gwt.client.ui.CmsPopup::center()();
}
};
$wnd[@org.opencms.gwt.client.ui.CmsFrameDialog::WIDTH_FUNCTION] = function(
width) {
popup.@org.opencms.gwt.client.ui.CmsPopup::setWidth(I)(width);
if (popup.@org.opencms.gwt.client.ui.CmsPopup::isShowing()) {
popup.@org.opencms.gwt.client.ui.CmsPopup::center()();
}
};
$wnd[@org.opencms.gwt.client.ui.CmsFrameDialog::TITLE_FUNCTION] = function(
title) {
popup.@org.opencms.gwt.client.ui.CmsPopup::setCaption(Ljava/lang/String;)(title);
};
}-*/;
/**
* Adds a new button to the button bar.<p>
*
* @param button the button to add
*/
public void addButton(Widget button) {
if (m_isFrame) {
if (m_buttonPanel == null) {
m_buttonPanel = new FlowPanel();
m_buttonPanel.addStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().popupButtonPanel());
m_main.add(m_buttonPanel);
}
m_buttonPanel.add(button);
} else {
m_popup.addButton(button);
}
}
/**
* Adds a new button to the button bar at the specified index position.<p>
*
* @param button the button to add
* @param index the index position
*/
public void addButton(Widget button, int index) {
if (m_isFrame) {
if (m_buttonPanel == null) {
m_buttonPanel = new FlowPanel();
m_buttonPanel.addStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().popupButtonPanel());
m_main.add(m_buttonPanel);
}
m_buttonPanel.insert(button, index);
} else {
m_popup.addButton(button, index);
}
}
/**
* Hides the dialog.<p>
*/
public void hide() {
if (m_isFrame) {
hideParent();
} else {
m_popup.hide();
}
}
/**
* Returns if the popup is showing and the content is rendered.<p>
*
* @return <code>true</code> if the popup and content are showing
*/
public boolean isShowing() {
if (m_isFrame) {
return m_isShowing;
} else {
return m_popup.isShowing();
}
}
/**
* Removes the given button from the button bar.<p>
*
* @param button the button to remove
*/
public void removeButton(Widget button) {
if (m_isFrame) {
if (m_buttonPanel != null) {
m_buttonPanel.remove(button);
}
} else {
m_popup.removeButton(button);
}
}
/**
* Sets the content widget.<p>
*
* @param content the content widget
*/
public void setContent(Widget content) {
if (m_content != null) {
m_content.removeFromParent();
}
if (m_isFrame) {
m_contentPanel.setWidget(content);
} else {
m_popup.setMainContent(content);
}
m_content = content;
}
/**
* Sets the popup height.<p>
*
* @param height the height
*/
public void setHeight(int height) {
if (m_isFrame) {
setParentHeight(height);
} else {
m_popup.setHeight(height);
if (m_popup.isShowing()) {
m_popup.center();
}
}
}
/**
* Sets the dialog title.<p>
*
* @param title the title
*/
public void setTitle(String title) {
if (m_isFrame) {
setParentTitle(title);
} else {
m_popup.setCaption(title);
}
}
/**
* Sets the popup width.<p>
*
* @param width the width
*/
public void setWidth(int width) {
if (m_isFrame) {
setParentWidth(width);
} else {
m_popup.setWidth(width);
if (m_popup.isShowing()) {
m_popup.center();
}
}
}
/**
* Shows the dialog.<p>
*/
public void show() {
if (m_isFrame) {
RootPanel root = RootPanel.get();
root.getElement().getStyle().setMargin(0, Unit.PX);
root.getElement().getStyle().setPadding(0, Unit.PX);
RootPanel.get().add(m_main);
m_isShowing = true;
} else {
m_popup.center();
}
}
/**
* Hides the parent dialog.<p>
*/
private native void hideParent() /*-{
$wnd.parent[@org.opencms.gwt.client.ui.CmsFrameDialog::CLOSE_FUNCTION]
();
}-*/;
/**
* Sets the parent dialog height.<p>
*
* @param height the height to set
*/
private native void setParentHeight(int height) /*-{
$wnd.parent[@org.opencms.gwt.client.ui.CmsFrameDialog::HEIGHT_FUNCTION]
(height);
}-*/;
/**
* Sets the title of the parent dialog.<p>
*
* @param title the title
*/
private native void setParentTitle(String title) /*-{
$wnd.parent[@org.opencms.gwt.client.ui.CmsFrameDialog::TITLE_FUNCTION]
(title);
}-*/;
/**
* Sets the parent dialog width.<p>
*
* @param width the width to set
*/
private native void setParentWidth(int width) /*-{
$wnd.parent[@org.opencms.gwt.client.ui.CmsFrameDialog::WIDTH_FUNCTION]
(width);
}-*/;
}
|
package org.openhab.binding.megadevice.internal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import org.openhab.core.events.EventPublisher;
import org.openhab.core.library.types.OnOffType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MegaDeviceHttpSocket extends Thread {
private final Socket s;
private InputStream is;
private OutputStream os;
private static Logger logger = LoggerFactory.getLogger(MegaDeviceHttpSocket.class);
public MegaDeviceHttpSocket(Socket s) {
this.s = s;
try {
this.is = s.getInputStream();
this.os = s.getOutputStream();
} catch (IOException e) {
logger.debug("ERROR: " + e.getMessage());
// e.printStackTrace();
}
}
@Override
public void run() {
readInput();
writeResponse();
}
private void readInput() {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (true) {
String s;
String[] getCommands;
try {
s = br.readLine();
if (s == null || s.trim().length() == 0) {
break;
}
if (s.contains("GET") && s.contains("?")) {
logger.debug(this.s.getInetAddress().getHostAddress() + " " + s);
String[] CommandParse = s.split("[/ ]");
String command = CommandParse[2];
getCommands = command.split("[?&>=]");
if (s.contains("m=1")) {
MegaDeviceBinding.updateValues(this.s.getInetAddress().getHostAddress(), getCommands,
OnOffType.OFF);
} else if (s.contains("m=1")) {
// do nothing -- long pressed
} else {
MegaDeviceBinding.updateValues(this.s.getInetAddress().getHostAddress(), getCommands,
OnOffType.ON);
for (int i = 0; getCommands.length > i; i++) {
logger.debug(i + " value " + getCommands[i]);
}
}
break;
} else
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void writeResponse() {
String result = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + 0 + "\r\n"
+ "Connection: close\r\n\r\n";
try {
os.write(result.getBytes());
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setEventPublisher(EventPublisher eventPublisher) {
}
}
|
package org.python.pydev.editor.codecompletion.shell;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.python.pydev.core.docutils.StringUtils;
import org.python.pydev.runners.ThreadStreamReader;
public class ProcessCreationInfo{
public final String[] parameters;
public final String[] envp;
public final File workingDir;
public final Process process;
private ThreadStreamReader stdReader;
private ThreadStreamReader errReader;
public ProcessCreationInfo(String[] parameters, String[] envp, File workingDir, Process process) {
this.parameters = parameters;
if(envp != null){
Arrays.sort(envp); //Keep it sorted!
}
this.envp = envp;
this.workingDir = workingDir;
this.process = process;
try {
process.getOutputStream().close(); //we won't write to it...
} catch (IOException e2) {
}
//will print things if we are debugging or just get it (and do nothing except emptying it)
stdReader = new ThreadStreamReader(process.getInputStream());
errReader = new ThreadStreamReader(process.getErrorStream());
stdReader.setName("Shell reader (stdout)");
errReader.setName("Shell reader (stderr)");
stdReader.start();
errReader.start();
}
public String getProcessLog() {
String joinedParams = StringUtils.join(" ", parameters);
String environment = "EMPTY ENVIRONMENT";
if (envp != null) {
environment = StringUtils.join("\n", envp);
}
String workDir = "NULL WORK DIR";
if (workingDir != null) {
workDir = workingDir.toString();
}
String osName = System.getProperty("os.name");
if (osName == null) {
osName = "Unknown OS!";
}
String stdContents = stdReader.getContents();
String errContents = errReader.getContents();
//Pre-allocate it in a proper size.
String[] splitted = new String[] {
"ProcessInfo:\n\n - Executed: ",
joinedParams,
"\n\n - Environment:\n",
environment,
"\n\n - Working Dir:\n",
workDir,
"\n\n - OS:\n",
osName,
"\n\n - Std output:\n",
stdContents,
"\n\n - Err output:\n",
errContents };
return StringUtils.join("", splitted);
}
}
|
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// persons to whom the Software is furnished to do so, subject to the
// notice shall be included in all copies or substantial portions of the
// Software.
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
package phasereditor.scene.ui.editor.interactive;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Transform;
import org.eclipse.wb.swt.SWTResourceManager;
import phasereditor.scene.core.ObjectModel;
import phasereditor.scene.core.TileSpriteComponent;
import phasereditor.scene.ui.editor.SceneEditor;
import phasereditor.scene.ui.editor.undo.SingleObjectSnapshotOperation;
import phasereditor.ui.PhaserEditorUI;
/**
* @author arian
*
*/
@SuppressWarnings("boxing")
public class TileSizeElement extends RenderInteractiveElement {
private static final int BOX = 14;
private int _globalX;
private int _globalY;
private boolean _dragging;
private int _initialGlobalY;
private int _initialGlobalX;
private boolean _changeX;
private boolean _changeY;
private boolean _hightlights;
public TileSizeElement(SceneEditor editor, List<ObjectModel> models, boolean changeX, boolean changeY) {
super(editor, models);
_changeX = changeX;
_changeY = changeY;
}
@Override
public void render(GC gc) {
var renderer = getRenderer();
var globalX = 0;
var globalY = 0;
var globalAngle = 0f;
for (var model : getModels()) {
var modelX = 0;
var modelY = 0;
var width = TileSpriteComponent.get_width(model);
var height = TileSpriteComponent.get_height(model);
globalAngle += renderer.globalAngle(model);
float[] xy;
if (_changeX && _changeY) {
xy = renderer.localToScene(model, modelX + width, modelY + height);
} else if (_changeX) {
xy = renderer.localToScene(model, modelX + width, modelY + height / 2);
} else {
xy = renderer.localToScene(model, modelX + width / 2, modelY + height);
}
globalX += (int) xy[0];
globalY += (int) xy[1];
}
var size = getModels().size();
globalX = globalX / size;
globalY = globalY / size;
globalAngle = globalAngle / size;
gc.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
var color = SWTResourceManager.getColor(_hightlights ? SWT.COLOR_WHITE
: (_changeX && _changeY ? SWT.COLOR_YELLOW : (_changeX ? SWT.COLOR_RED : SWT.COLOR_GREEN)));
gc.setBackground(color);
gc.setForeground(color);
fillRect(gc, globalX, globalY, globalAngle + (_changeY ? 90 : 0), BOX, color);
_globalX = globalX;
_globalY = globalY;
}
private static void fillRect(GC gc, int globalX, int globalY, float globalAngle, int size, Color color) {
var tx = new Transform(gc.getDevice());
tx.translate(globalX, globalY);
tx.rotate(globalAngle);
gc.setTransform(tx);
gc.setBackground(color);
gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
gc.fillRectangle(-size / 2, -size / 2, size, size);
gc.drawRectangle(-size / 2, -size / 2, size, size);
gc.setTransform(null);
tx.dispose();
}
@Override
public boolean contains(int sceneX, int sceneY) {
if (_dragging) {
return true;
}
var contains = PhaserEditorUI.distance(sceneX, sceneY, _globalX, _globalY) <= BOX;
_hightlights = contains;
return contains;
}
@Override
public void mouseMove(MouseEvent e) {
if (_dragging && contains(e.x, e.y)) {
for (var model : getModels()) {
var initialLocalXY = (float[]) model.get("initial-local-xy");
var localXY = getRenderer().sceneToLocal(model, e.x, e.y);
var dx = localXY[0] - initialLocalXY[0];
var dy = localXY[1] - initialLocalXY[1];
var initialWidth = (float) model.get("initial-width");
var initialHeight = (float) model.get("initial-height");
var width = initialWidth + dx;
var height = initialHeight + dy;
{
// snap
var sceneModel = getEditor().getSceneModel();
if (sceneModel.isSnapEnabled()) {
var snapWidth = sceneModel.getSnapWidth();
var snapHeight = sceneModel.getSnapHeight();
width = Math.round(width / snapWidth) * snapWidth;
height = Math.round(height / snapHeight) * snapHeight;
}
}
if (width <= 0 || height <= 0) {
continue;
}
if (_changeX) {
TileSpriteComponent.set_width(model, width);
}
if (_changeY) {
TileSpriteComponent.set_height(model, height);
}
model.setDirty(true);
getEditor().updatePropertyPagesContentWithSelection();
}
}
}
@Override
public void mouseDown(MouseEvent e) {
if (contains(e.x, e.y)) {
_dragging = true;
_initialGlobalX = _globalX;
_initialGlobalY = _globalY;
for (var model : getModels()) {
model.put("initial-width", TileSpriteComponent.get_width(model));
model.put("initial-height", TileSpriteComponent.get_height(model));
var xy = getRenderer().sceneToLocal(model, _initialGlobalX, _initialGlobalY);
model.put("initial-local-xy", xy);
}
}
}
@Override
public void mouseUp(MouseEvent e) {
if (_dragging) {
var editor = getEditor();
getModels().forEach(model -> {
model.put("final-width", TileSpriteComponent.get_width(model));
model.put("final-height", TileSpriteComponent.get_height(model));
TileSpriteComponent.set_width(model, (float) model.get("initial-width"));
TileSpriteComponent.set_height(model, (float) model.get("initial-height"));
});
var before = SingleObjectSnapshotOperation.takeSnapshot(getModels());
getModels().forEach(model -> {
TileSpriteComponent.set_width(model, (float) model.get("final-width"));
TileSpriteComponent.set_height(model, (float) model.get("final-height"));
});
var after = SingleObjectSnapshotOperation.takeSnapshot(getModels());
editor.executeOperation(new SingleObjectSnapshotOperation(before, after, "Set tile position.", true));
editor.setDirty(true);
}
_dragging = false;
}
}
|
package com.simpligility.maven.plugins.android.phase_prebuild;
import com.simpligility.maven.plugins.android.common.AndroidExtension;
import com.simpligility.maven.plugins.android.common.ArtifactResolverHelper;
import com.simpligility.maven.plugins.android.common.DependencyResolver;
import com.simpligility.maven.plugins.android.common.PomConfigurationHelper;
import com.simpligility.maven.plugins.android.common.UnpackedLibHelper;
import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder;
import org.apache.maven.shared.dependency.graph.DependencyGraphBuilderException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* Adds classes from AAR and APK dependencies to the project compile classpath.
*
* @author William Ferguson
* @author Benoit Billington
* @author Manfred Moser
*/
@Component( role = AbstractMavenLifecycleParticipant.class, hint = "default" )
public final class ClasspathModifierLifecycleParticipant extends AbstractMavenLifecycleParticipant
{
/**
* Mojo configuration parameter to determine if jar files found inside an apklib are
* pulled onto the classpath and into the resulting apk, defaults to false
* @see INCLUDE_FROM_APKLIB_DEFAULT
*/
private static final String INCLUDE_FROM_APKLIB_PARAM = "includeLibsJarsFromApklib";
/**
* Mojo configuration parameter to determine if jar files found inside an aar are
* pulled onto the classpath and into the resulting apk, defaults to false
* @see INCLUDE_FROM_AAR_DEFAULT
*/
private static final String INCLUDE_FROM_AAR_PARAM = "includeLibsJarsFromAar";
/**
* Mojo configuration parameter to determine if we should warn about dependency conflicts with the provided
* dependencies.
*
* @see DISABLE_CONFLICTING_DEPENDENCIES_WARNING_DEFAULT
*/
private static final String DISABLE_CONFLICTING_DEPENDENCIES_WARNING_PARAM
= "disableConflictingDependenciesWarning";
private static final boolean INCLUDE_FROM_APKLIB_DEFAULT = false;
private static final boolean INCLUDE_FROM_AAR_DEFAULT = true;
private static final boolean DISABLE_CONFLICTING_DEPENDENCIES_WARNING_DEFAULT = false;
/**
* Mojo configuration parameter that defines where AAR files should be unpacked.
* Default is /target/unpacked-libs
*/
private static final String UNPACKED_LIBS_FOLDER_PARAM = "unpackedLibsFolder";
@Requirement
private ArtifactResolver artifactResolver;
@Requirement( hint = "default" )
private DependencyGraphBuilder dependencyGraphBuilder;
@Requirement
private Logger log;
private boolean addedJarFromLibs = false;
@Override
public void afterProjectsRead( MavenSession session ) throws MavenExecutionException
{
log.debug( "" );
log.debug( "ClasspathModifierLifecycleParticipant#afterProjectsRead - start" );
log.debug( "" );
log.debug( "CurrentProject=" + session.getCurrentProject() );
final List<MavenProject> projects = session.getProjects();
final DependencyResolver dependencyResolver = new DependencyResolver( log, dependencyGraphBuilder );
final ArtifactResolverHelper artifactResolverHelper = new ArtifactResolverHelper( artifactResolver, log );
for ( MavenProject project : projects )
{
log.debug( "" );
log.debug( "project=" + project.getArtifact() );
if ( ! AndroidExtension.isAndroidPackaging( project.getPackaging() ) )
{
continue; // do not modify classpath if not an android project.
}
final String unpackedLibsFolder
= getMojoConfigurationParameter( project, UNPACKED_LIBS_FOLDER_PARAM, null );
final UnpackedLibHelper helper = new UnpackedLibHelper( artifactResolverHelper, project, log,
unpackedLibsFolder == null ? null : new File( unpackedLibsFolder )
);
final Set<Artifact> artifacts;
// If there is an extension ClassRealm loaded for this project then use that
// as the ContextClassLoader so that Wagon extensions can be used to resolves dependencies.
final ClassLoader projectClassLoader = ( project.getClassRealm() != null )
? project.getClassRealm()
: Thread.currentThread().getContextClassLoader();
final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader( projectClassLoader );
artifacts = dependencyResolver.getProjectDependenciesFor( project, session );
}
catch ( DependencyGraphBuilderException e )
{
// Nothing to do. The resolution failure will be displayed by the standard resolution mechanism.
continue;
}
finally
{
Thread.currentThread().setContextClassLoader( originalClassLoader );
}
boolean includeFromAar = getMojoConfigurationParameter( project, INCLUDE_FROM_AAR_PARAM,
INCLUDE_FROM_AAR_DEFAULT );
boolean includeFromApklib = getMojoConfigurationParameter( project, INCLUDE_FROM_APKLIB_PARAM,
INCLUDE_FROM_APKLIB_DEFAULT );
boolean disableConflictingDependenciesWarning = getMojoConfigurationParameter( project,
DISABLE_CONFLICTING_DEPENDENCIES_WARNING_PARAM, DISABLE_CONFLICTING_DEPENDENCIES_WARNING_DEFAULT );
log.debug( "projects deps: : " + artifacts );
if ( !disableConflictingDependenciesWarning )
{
ProvidedDependencyChecker checker = new ProvidedDependencyChecker();
checker.checkProvidedDependencies( artifacts, log );
}
for ( Artifact artifact : artifacts )
{
final String type = artifact.getType();
if ( type.equals( AndroidExtension.AAR ) )
{
// An AAR lib contains a classes jar that needs to be added to the classpath.
// Create a placeholder classes.jar and add it to the compile classpath.
// It will replaced with the real classes.jar by GenerateSourcesMojo.
addClassesToClasspath( helper, project, artifact );
// An AAR may also contain zero or more internal libs in the libs folder.
// If 'includeLibsJarsFromAar' config param is true then include them too.
if ( includeFromAar )
{
// Add jar files in 'libs' into classpath.
addLibsJarsToClassPath( helper, project, artifact );
}
}
else if ( type.equals( AndroidExtension.APK ) )
{
// The only time that an APK will likely be a dependency is when this an an APK test project.
// So add a placeholder (we cannot resolve the actual dep pre build) to the compile classpath.
// The placeholder will be replaced with the real APK jar later.
addClassesToClasspath( helper, project, artifact );
}
else if ( type.equals( AndroidExtension.APKLIB ) )
{
if ( includeFromApklib )
{
// Add jar files in 'libs' into classpath.
addLibsJarsToClassPath( helper, project, artifact );
}
}
}
}
if ( addedJarFromLibs )
{
log.warn(
"Transitive dependencies should really be provided by Maven dependency management.\n"
+ " We suggest you to ask the above providers to package their component properly.\n"
+ " Things may break at compile and/or runtime due to multiple copies of incompatible libraries." );
}
log.debug( "" );
log.debug( "ClasspathModifierLifecycleParticipant#afterProjectsRead - finish" );
}
private String getMojoConfigurationParameter( MavenProject project, String name, String defaultValue )
{
String value = PomConfigurationHelper.getPluginConfigParameter( project,
name, defaultValue );
log.debug( name + " set to " + value );
return value;
}
private boolean getMojoConfigurationParameter( MavenProject project, String name, boolean defaultValue )
{
return Boolean.valueOf( getMojoConfigurationParameter( project, name, Boolean.toString( defaultValue ) ) );
}
/**
* Add jar files in libs into the project classpath.
*/
private void addLibsJarsToClassPath( UnpackedLibHelper helper, MavenProject project, Artifact artifact )
throws MavenExecutionException
{
try
{
final File unpackLibFolder = helper.getUnpackedLibFolder( artifact );
final File artifactFile = helper.getArtifactToFile( artifact );
ZipFile zipFile = new ZipFile( artifactFile );
Enumeration enumeration = zipFile.entries();
while ( enumeration.hasMoreElements() )
{
ZipEntry entry = ( ZipEntry ) enumeration.nextElement();
String entryName = entry.getName();
// Only jar files under 'libs' directory to be processed.
if ( Pattern.matches( "^libs/.+\\.jar$", entryName ) )
{
final File libsJarFile = new File( unpackLibFolder, entryName );
log.warn( "Adding jar from libs folder to classpath: " + libsJarFile );
// In order to satisfy the LifecycleDependencyResolver on execution up to a phase that
// has a Mojo requiring dependency resolution I need to create a dummy classesJar here.
if ( !libsJarFile.getParentFile().exists() )
{
libsJarFile.getParentFile().mkdirs();
}
libsJarFile.createNewFile();
// Add the jar to the classpath.
final Dependency dependency =
createSystemScopeDependency( artifact, libsJarFile, libsJarFile.getName() );
project.getModel().addDependency( dependency );
addedJarFromLibs = true;
}
}
}
catch ( MojoExecutionException e )
{
log.debug( "Error extract jars" );
}
catch ( ZipException e )
{
log.debug( "Error" );
}
catch ( IOException e )
{
log.debug( "Error" );
}
}
/**
* Add the dependent library classes to the project classpath.
*/
private void addClassesToClasspath( UnpackedLibHelper helper, MavenProject project, Artifact artifact )
throws MavenExecutionException
{
// Work out where the dep will be extracted and calculate the file path to the classes jar.
// This is location where the GenerateSourcesMojo will extract the classes.
final File classesJar = helper.getUnpackedClassesJar( artifact );
log.debug( "Adding to classpath : " + classesJar );
// In order to satisfy the LifecycleDependencyResolver on execution up to a phase that
// has a Mojo requiring dependency resolution I need to create a dummy classesJar here.
classesJar.getParentFile().mkdirs();
try
{
final ZipOutputStream zipOutputStream = new ZipOutputStream( new FileOutputStream( classesJar ) );
zipOutputStream.close();
log.debug( "Created dummy " + classesJar.getName() + " exist=" + classesJar.exists() );
}
catch ( IOException e )
{
throw new MavenExecutionException( "Could not add " + classesJar.getName() + " as dependency", e );
}
// Modify the classpath to use an extracted dex file. This will overwrite
// any exisiting dependencies with the same information.
final Dependency dependency = createSystemScopeDependency( artifact, classesJar, null );
final Dependency providedJar = findProvidedDependencies( dependency, project );
if ( providedJar != null )
{
project.getModel().removeDependency( providedJar );
}
project.getModel().addDependency( dependency );
}
private Dependency createSystemScopeDependency( Artifact artifact, File location, String suffix )
{
String artifactId = artifact.getArtifactId();
if ( suffix != null )
{
artifactId += "_" + suffix;
}
final Dependency dependency = new Dependency();
dependency.setGroupId( artifact.getGroupId() );
dependency.setArtifactId( artifactId );
dependency.setVersion( artifact.getVersion() );
dependency.setScope( Artifact.SCOPE_SYSTEM );
dependency.setSystemPath( location.getAbsolutePath() );
return dependency;
}
private Dependency findProvidedDependencies( Dependency dexDependency, MavenProject project )
{
for ( Dependency dependency : project.getDependencies() )
{
if ( dependency.getScope().equals( Artifact.SCOPE_PROVIDED ) )
{
if ( dependency.getArtifactId().equals( dexDependency.getArtifactId() )
&& dependency.getGroupId().equals( dexDependency.getGroupId() )
&& dependency.getType().equals( dexDependency.getType() )
&& dependency.getVersion().equals( dexDependency.getVersion() ) )
{
return dependency;
}
}
}
return null;
}
}
|
package com.puppycrawl.tools.checkstyle.imports;
import org.antlr.v4.runtime.*;
import java.util.Set;
import static java.lang.Math.*;
import static org.antlr.v4.runtime.CommonToken.*;
public class InputImportOrderStaticOnDemandGroupOrderBottom
{
}
|
//package org.cytoscape.tableimport.internal.task;
//import static javax.swing.GroupLayout.DEFAULT_SIZE;
//import static javax.swing.GroupLayout.PREFERRED_SIZE;
//import static javax.swing.GroupLayout.Alignment.LEADING;
//import java.awt.Dialog.ModalityType;
//import java.awt.event.ActionEvent;
//import javax.swing.AbstractAction;
//import javax.swing.GroupLayout;
//import javax.swing.JButton;
//import javax.swing.JDialog;
//import javax.swing.JPanel;
//import org.cytoscape.application.swing.AbstractCyAction;
//import org.cytoscape.application.swing.CySwingApplication;
//import org.cytoscape.io.read.InputStreamTaskFactory;
//import org.cytoscape.service.util.CyServiceRegistrar;
//import org.cytoscape.tableimport.internal.ui.ImportTablePanel;
//import org.cytoscape.tableimport.internal.util.ImportType;
//import org.cytoscape.util.swing.LookAndFeelUtil;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//public class ImportOntologyAndAnnotationAction extends AbstractCyAction {
// private static final long serialVersionUID = 3000065764000826333L;
// private static final Logger logger = LoggerFactory.getLogger("org.cytoscape.application.userlog");
// private ImportTablePanel ontologyPanel;
// private final InputStreamTaskFactory isTaskfactory;
// private final CyServiceRegistrar serviceRegistrar;
// public ImportOntologyAndAnnotationAction(
// final InputStreamTaskFactory isTaskfactory,
// final CyServiceRegistrar serviceRegistrar
// // Removing from menu options until fixed or replaced per #3697
// super("Ontology and Annotation...");
// // setPreferredMenu("File.Import");
// // setMenuGravity(4.0f);
// this.isTaskfactory = isTaskfactory;
// this.serviceRegistrar = serviceRegistrar;
// @Override
// public void actionPerformed(ActionEvent e) {
// final JDialog dialog = layout();
// dialog.pack();
// dialog.setLocationRelativeTo(serviceRegistrar.getService(CySwingApplication.class).getJFrame());
// dialog.setVisible(true);
// @SuppressWarnings("serial")
// private JDialog layout() {
// final JDialog dialog = new JDialog(serviceRegistrar.getService(CySwingApplication.class).getJFrame());
// dialog.setModalityType(ModalityType.APPLICATION_MODAL);
// dialog.setTitle(ImportType.ONTOLOGY_IMPORT.getTitle());
// final JButton importButton = new JButton(new AbstractAction("Import") {
// @Override
// public void actionPerformed(ActionEvent ae) {
// dialog.dispose();
// try {
// ontologyPanel.importTable();
// } catch (Exception e) {
// logger.error("Could not import ontology.", e);
// final JButton cancelButton = new JButton(new AbstractAction("Cancel") {
// @Override
// public void actionPerformed(ActionEvent ae) {
// dialog.dispose();
// final JPanel contentPane = new JPanel();
// final GroupLayout layout = new GroupLayout(contentPane);
// contentPane.setLayout(layout);
// layout.setAutoCreateContainerGaps(true);
// layout.setAutoCreateGaps(true);
// try {
// ontologyPanel =
// new ImportTablePanel(ImportType.ONTOLOGY_IMPORT, null, null, isTaskfactory, serviceRegistrar);
// final JPanel buttonPanel = LookAndFeelUtil.createOkCancelPanel(importButton, cancelButton, "Ontology_and_Annotation_Import");
// layout.setHorizontalGroup(layout.createParallelGroup(LEADING, true)
// .addComponent(ontologyPanel, DEFAULT_SIZE, DEFAULT_SIZE, Short.MAX_VALUE)
// .addComponent(buttonPanel, DEFAULT_SIZE, DEFAULT_SIZE, Short.MAX_VALUE)
// layout.setVerticalGroup(layout.createSequentialGroup()
// .addComponent(ontologyPanel, PREFERRED_SIZE, DEFAULT_SIZE, PREFERRED_SIZE)
// .addComponent(buttonPanel, PREFERRED_SIZE, DEFAULT_SIZE, PREFERRED_SIZE)
// dialog.getRootPane().setDefaultButton(importButton);
// } catch (Exception e) {
// logger.error("Cannot create Ontology Import Panel", e);
// dialog.setContentPane(contentPane);
// dialog.setResizable(false);
// LookAndFeelUtil.setDefaultOkCancelKeyStrokes(dialog.getRootPane(), importButton.getAction(),
// cancelButton.getAction());
// return dialog;
|
package BeanPlant.the_DJDJ.JavaText.npc;
import BeanPlant.the_DJDJ.JavaText.handlers.EventHandler;
import BeanPlant.the_DJDJ.JavaText.io.CommandParser;
import BeanPlant.the_DJDJ.JavaText.world.Location;
import BeanPlant.the_DJDJ.JavaText.world.exit.Exit;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* A mobile entity object. This is exactly the same as an Entity, with the
* exception that it has a chance of moving to another location every time a
* command is entered.
*
* @author the_DJDJ
*/
public class MobileEntity extends Entity implements Serializable, EventHandler {
public static final MobileEntity sheep = new MobileEntity("sheep", "a harmless sheep", "a flock of relatively harmless sheep", 10, 0.1f);
/** What percentage chance the entity has of moving every time a command is entered. */
private float movingChance;
/** Whether or not the entity can use the up/down directions, ie climbing. */
private boolean canClimb;
/** The current location of this MobileEntity. */
private Location location;
/** Whether or not this MobileEntity moved on the last turn. */
private boolean hasMovedRecently = false;
/**
* The default constructor. This assigns the name, the amount of health, and
* the change of moving that the entity has.
*
* @param name The name of the entity
* @param single The name given to a single unit of this entity
* @param plural The name given to multiple units of this entity
* @param health The amount of health the entity has
* @param movingChance the chance of moving to a random location that the
* entity has.
*/
public MobileEntity(String name, String single, String plural, int health, float movingChance){
this(name, single, plural, health, movingChance, null, true);
}
/**
* The default constructor. This assigns the name, the amount of health, and
* the change of moving that the entity has.
*
* @param name The name of the entity
* @param single The name given to a single unit of this entity
* @param plural The name given to multiple units of this entity
* @param health The amount of health the entity has
* @param movingChance the chance of moving to a random location that the
* entity has.
* @param location Where this MobileEntity currently is
*/
public MobileEntity(String name, String single, String plural, int health, float movingChance, Location location){
this(name, single, plural, health, movingChance, location, true);
}
/**
* A slightly random constructor, used so that other objects can register
* themselves as MobileEntities
*
* @param entity the MobileEntity to register
*/
public MobileEntity(MobileEntity entity){
this(entity.getName(), entity.getSingleName(), entity.getPluralName(), entity.getHealth(), entity.getMovingChance(), entity.getLocation(), entity.isAvoidable());
}
/**
* The second constructor. This assigns the name, the amount of health, the
* chance of moving that the entity has, and whether or not the entity is
* avoidable.
*
* @param name The name of the entity
* @param single The name given to a single unit of this entity
* @param plural The name given to multiple units of this entity
* @param health The amount of health the entity has
* @param movingChance the chance of moving to a random location that the
* entity has.
* @param avoidable Whether or not the player can run away from the entity
*/
public MobileEntity(String name, String single, String plural, int health, float movingChance, boolean avoidable){
this(name, single, plural, health, movingChance, null, avoidable);
}
/**
* The second constructor. This assigns the name, the amount of health, the
* chance of moving that the entity has, and whether or not the entity is
* avoidable.
*
* @param name The name of the entity
* @param single The name given to a single unit of this entity
* @param plural The name given to multiple units of this entity
* @param health The amount of health the entity has
* @param movingChance the chance of moving to a random location that the
* entity has.
* @param location Where this MobileEntity currently is
* @param avoidable Whether or not the player can run away from the entity
*/
public MobileEntity(String name, String single, String plural, int health, float movingChance, Location location, boolean avoidable){
super(name, single, plural, health, avoidable);
this.movingChance = movingChance;
this.location = location;
// Register this MobileEntity with the CommandParser
if(location != null) CommandParser.addEventHandler(this);
}
/**
* Returns the chance that the entity has of moving to a random location
* after each entered command
*
* @return the chance that the entity has of being of mobile
*/
public float getMovingChance(){
return this.movingChance;
}
/**
* Sets the chance that the entity has of moving to a random location after
* each entered command
*
* @param movingChance the chance that the entity has of being of mobile
*/
public void setMovingChance(float movingChance){
this.movingChance = movingChance;
}
/**
* Returns the current location of the entity.
*
* @return Where the entity is at the moment
*/
public Location getLocation(){
return this.location;
}
/**
* Sets the current location of the entity.
*
* @param location Where the entity is at the moment
*/
public void setLocation(Location location){
this.location = location;
}
/**
* Returns whether or not the entity can climb upwards or downwards.
*
* @return whether or not the entity can climb
*/
public boolean canClimb(){
return this.canClimb;
}
/**
* Sets whether or not the entity is able to climb vertically
*
* @param canClimb whether or not the entity is able to climb vertically
*/
public void setCanClimb(boolean canClimb){
this.canClimb = canClimb;
}
/**
* The method that calculates whether or not the mobile entity will be
* moving, and, if so, in which direction.
*/
private void move(){
// First check if our animal will move
if(Math.random() <= this.movingChance){
// A list of places where we can go
List<Exit> possibleExits = new ArrayList<>();
for (int i = 0; i < this.location.getExits().size(); i++) {
switch(this.location.getExits().get(i).getDirectionName()){
case "UP":
case "DOWN":
if(canClimb) possibleExits.add(this.location.getExits().get(i));
break;
default:
possibleExits.add(this.location.getExits().get(i));
break;
}
}
// Check that we can actually go somewhere
if(possibleExits.size() > 0){
// Now choose a random location to move to
Location newLocation = possibleExits.get((int) (Math.random() * possibleExits.size())).getLeadsTo();
// And do the move
this.getLocation().removeEntity(this);
this.getLocation().addEntityShadow(new EntityShadow(this));
this.setLocation(newLocation);
newLocation.addEntity(this);
// Make sure this MobileEntity won't move immediately
this.hasMovedRecently = true;
}
}
}
/**
* A method that creates a duplicate copy of this MobileEntity, at a
* specified location
*
* @param location the location of this new MobileEntity
*
* @return a new clone of this object, at a specified location
*/
public MobileEntity place(Location location){
return new MobileEntity(this.getName(), this.getSingleName(), this.getPluralName(), this.getHealth(), this.getMovingChance(), location, this.isAvoidable());
}
/**
* @{inheritDoc}
*/
@Override
public void fireEvent(String event) {
switch(event){
case "GO":
if(hasMovedRecently){
hasMovedRecently = false;
} else this.move();
break;
}
}
}
|
package won.matcher.service.nodemanager.actor;
import akka.actor.*;
import akka.cluster.pubsub.DistributedPubSub;
import akka.cluster.pubsub.DistributedPubSubMediator;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.japi.Function;
import org.apache.commons.collections.IteratorUtils;
import org.apache.jena.query.Dataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import scala.concurrent.duration.Duration;
import won.cryptography.service.RegistrationClient;
import won.cryptography.ssl.MessagingContext;
import won.matcher.service.common.event.BulkHintEvent;
import won.matcher.service.common.event.HintEvent;
import won.matcher.service.common.event.WonNodeEvent;
import won.matcher.service.common.spring.SpringExtension;
import won.matcher.service.crawler.actor.MasterCrawlerActor;
import won.matcher.service.nodemanager.config.ActiveMqWonNodeConnectionFactory;
import won.matcher.service.nodemanager.config.WonNodeControllerConfig;
import won.matcher.service.nodemanager.pojo.WonNodeConnection;
import won.matcher.service.nodemanager.service.HintDBService;
import won.matcher.service.nodemanager.service.WonNodeSparqlService;
import won.protocol.service.WonNodeInfo;
import won.protocol.service.WonNodeInformationService;
import won.protocol.util.linkeddata.LinkedDataSource;
import java.net.URI;
import java.util.*;
@Component
@Scope("prototype")
public class WonNodeControllerActor extends UntypedActor {
private LoggingAdapter log = Logging.getLogger(getContext().system(), this);
private ActorRef pubSubMediator;
private ActorRef crawler;
private ActorRef saveNeedActor;
private Map<String, WonNodeConnection> crawlWonNodes = new HashMap<>();
private Set<String> skipWonNodeUris = new HashSet<>();
private Set<String> failedWonNodeUris = new HashSet<>();
private static final String LIFE_CHECK_TICK = "life_check_tick";
@Autowired
private WonNodeSparqlService sparqlService;
@Autowired
private WonNodeControllerConfig config;
@Autowired
private WonNodeInformationService wonNodeInformationService;
@Autowired
private RegistrationClient registrationClient;
@Autowired
LinkedDataSource linkedDataSource;
@Autowired
private MessagingContext messagingContext;
@Autowired
private HintDBService hintDatabase;
@Override
public void preStart() {
// Create a scheduler to execute the life check for each won node regularly
getContext().system().scheduler().schedule(config.getLifeCheckDuration(), config.getLifeCheckDuration(),
getSelf(), LIFE_CHECK_TICK, getContext().dispatcher(), null);
// Subscribe for won node events
pubSubMediator = DistributedPubSub.get(getContext().system()).mediator();
pubSubMediator.tell(new DistributedPubSubMediator.Subscribe(WonNodeEvent.class.getName(), getSelf()), getSelf());
// Subscribe for hint events
pubSubMediator.tell(new DistributedPubSubMediator.Subscribe(HintEvent.class.getName(), getSelf()), getSelf());
pubSubMediator.tell(new DistributedPubSubMediator.Subscribe(BulkHintEvent.class.getName(), getSelf()), getSelf());
// set won nodes to skip by configuration
skipWonNodeUris.addAll(config.getSkipWonNodes());
// get all known won node uris from RDF store
Set<WonNodeInfo> wonNodeInfo = new HashSet<>();
try {
wonNodeInfo = sparqlService.retrieveAllWonNodeInfo();
} catch (Exception e) {
log.error("Error querying SPARQL endpoint {}. SPARQL endpoint must be running at matcher service startup!",
sparqlService.getSparqlEndpoint());
log.error("Exception was: {}", e);
log.info("Shut down matcher service!");
System.exit(-1);
}
// Treat the known won nodes as newly discovered won nodes to register them again at startup of matcher service
for (WonNodeInfo nodeInfo : wonNodeInfo) {
if (!config.getCrawlWonNodes().contains(nodeInfo.getWonNodeURI())) {
WonNodeEvent e = new WonNodeEvent(nodeInfo.getWonNodeURI(), WonNodeEvent.STATUS.NEW_WON_NODE_DISCOVERED);
pubSubMediator.tell(new DistributedPubSubMediator.Publish(e.getClass().getName(), e), getSelf());
}
}
// initialize the won nodes from the config file to crawl
for (String nodeUri : config.getCrawlWonNodes()) {
if (!skipWonNodeUris.contains(nodeUri)) {
if (!crawlWonNodes.containsKey(nodeUri)) {
WonNodeEvent e = new WonNodeEvent(nodeUri, WonNodeEvent.STATUS.NEW_WON_NODE_DISCOVERED);
pubSubMediator.tell(new DistributedPubSubMediator.Publish(e.getClass().getName(), e), getSelf());
}
}
}
// initialize the crawler
crawler = getContext().actorOf(SpringExtension.SpringExtProvider.get(
getContext().system()).props(MasterCrawlerActor.class), "MasterCrawlerActor");
// initialize the need event save actor
saveNeedActor = getContext().actorOf(SpringExtension.SpringExtProvider.get(
getContext().system()).props(SaveNeedEventActor.class), "SaveNeedEventActor");
}
/**
* Receive messages about newly discovered won node and decide to crawl or skip
* processing these won nodes.
*
* @param message
* @throws Exception
*/
@Override
public void onReceive(final Object message) {
if (message instanceof Terminated) {
// if it is some other actor handle it differently
handleConnectionErrors((Terminated) message);
return;
}
if (message.equals(LIFE_CHECK_TICK)) {
lifeCheck();
return;
}
if (message instanceof WonNodeEvent) {
WonNodeEvent event = (WonNodeEvent) message;
if (event.getStatus().equals(WonNodeEvent.STATUS.NEW_WON_NODE_DISCOVERED) ||
event.getStatus().equals(WonNodeEvent.STATUS.GET_WON_NODE_INFO_FOR_CRAWLING) ||
event.getStatus().equals(WonNodeEvent.STATUS.RETRY_REGISTER_FAILED_WON_NODE)) {
// won node has already been discovered and connected
if (crawlWonNodes.containsKey(event.getWonNodeUri())) {
log.debug("Won node uri '{}' already discovered", event.getWonNodeUri());
if (event.equals(WonNodeEvent.STATUS.GET_WON_NODE_INFO_FOR_CRAWLING)) {
WonNodeInfo wonNodeInfo = crawlWonNodes.get(event.getWonNodeUri()).getWonNodeInfo();
WonNodeEvent e = new WonNodeEvent(event.getWonNodeUri(), WonNodeEvent.STATUS.CONNECTED_TO_WON_NODE, wonNodeInfo);
pubSubMediator.tell(new DistributedPubSubMediator.Publish(e.getClass().getName(), e), getSelf());
}
return;
}
// skip crawling of won nodes in the skip list
if (skipWonNodeUris.contains(event.getWonNodeUri())) {
log.debug("Skip crawling won node with uri '{}'", event.getWonNodeUri());
WonNodeEvent e = new WonNodeEvent(event.getWonNodeUri(), WonNodeEvent.STATUS.SKIP_WON_NODE);
pubSubMediator.tell(new DistributedPubSubMediator.Publish(e.getClass().getName(), e), getSelf());
return;
}
// shall we try to connect to the won node or has it failed already ?
if (failedWonNodeUris.contains(event.getWonNodeUri())) {
log.debug("Suppress connection to already failed won node with uri {} , will try to connect later ...", event.getWonNodeUri());
return;
}
// try the connect to won node
boolean logRegisterWarningForWonNode = event.getStatus().equals(WonNodeEvent.STATUS.RETRY_REGISTER_FAILED_WON_NODE);
WonNodeConnection wonNodeConnection = addWonNodeForCrawling(event.getWonNodeUri(), logRegisterWarningForWonNode);
// connection failed ?
if (failedWonNodeUris.contains(event.getWonNodeUri())) {
log.debug("Still could not connect to won node with uri: {}, will retry later ...", event.getWonNodeUri());
return;
}
// tell the crawler about discovered won nodes
if (wonNodeConnection == null || wonNodeConnection.getWonNodeInfo() == null) {
log.error("Cannot retrieve won node info from won node connection!");
return;
}
WonNodeEvent e = new WonNodeEvent(event.getWonNodeUri(), WonNodeEvent.STATUS.CONNECTED_TO_WON_NODE, wonNodeConnection.getWonNodeInfo());
pubSubMediator.tell(new DistributedPubSubMediator.Publish(e.getClass().getName(), e), getSelf());
return;
}
}
// send back hints to won nodes
if (message instanceof HintEvent) {
processHint((HintEvent) message);
return;
} else if (message instanceof BulkHintEvent) {
BulkHintEvent bulkHintEvent = (BulkHintEvent) message;
for (HintEvent hint : bulkHintEvent.getHintEvents()) {
processHint(hint);
}
return;
}
unhandled(message);
}
private void processHint(HintEvent hint) {
// hint duplicate filter
if (hintDatabase.mightHintSaved(hint)) {
log.debug("Hint " + hint + " is filtered out by duplicate filter!");
hintDatabase.saveHint(hint);
return;
}
// save the hint and send it to the won node controller which sends it to the responsible won node
hintDatabase.saveHint(hint);
sendHint(hint);
}
/**
* Send hint event out to won node
*
* @param hint
*/
private void sendHint(HintEvent hint) {
if (!crawlWonNodes.containsKey(hint.getFromWonNodeUri())) {
log.warning("cannot send hint to won node {}! Is registered with the won node controller?",
hint.getFromWonNodeUri());
return;
}
// send hint to first won node
URI eventUri = wonNodeInformationService.generateEventURI(URI.create(hint.getFromWonNodeUri()));
hint.setGeneratedEventUri(eventUri);
WonNodeConnection fromWonNodeConnection = crawlWonNodes.get(hint.getFromWonNodeUri());
log.info("Send hint {} to won node {}", hint, hint.getFromWonNodeUri());
fromWonNodeConnection.getHintProducer().tell(hint, getSelf());
}
/**
* Try to register at won nodes and add them for crawling
*
* @param wonNodeUri URI of the won node meta data resource
* @param logWonNodeRegisterWarning if true then log the failed register attempts as warning, otherwise as debug level
* @return won node connection if successfully connected, otherwise null
*/
private WonNodeConnection addWonNodeForCrawling(String wonNodeUri, boolean logWonNodeRegisterWarning) {
WonNodeConnection con = null;
Dataset ds = null;
WonNodeInfo nodeInfo = null;
// try register at won node
try {
registrationClient.register(wonNodeUri);
ds = linkedDataSource.getDataForResource(URI.create(wonNodeUri));
} catch (Exception e) {
addFailedWonNode(wonNodeUri, con);
if (logWonNodeRegisterWarning) {
log.warning("Error requesting won node information from {}", wonNodeUri);
log.warning("Exception message: {} \nCause: {} ", e.getMessage(), e.getCause());
} else {
log.debug("Error requesting won node information from {}", wonNodeUri);
log.debug("Exception message: {} \nCause: {} ", e.getMessage(), e.getCause());
}
return null;
}
// try save won node info in local rdf store
try {
sparqlService.updateNamedGraphsOfDataset(ds);
nodeInfo = sparqlService.getWonNodeInfoFromDataset(ds);
} catch (Exception e) {
addFailedWonNode(wonNodeUri, con);
log.error("Error saving won node information from {} into RDF store with SPARQL endpoint {}", wonNodeUri,
sparqlService.getSparqlEndpoint());
log.error("Exception message: {} \nCause: {} ", e.getMessage(), e.getCause());
return null;
}
// try subscribe need updates at won node
try {
con = subscribeNeedUpdates(nodeInfo);
crawlWonNodes.put(nodeInfo.getWonNodeURI(), con);
failedWonNodeUris.remove(nodeInfo.getWonNodeURI());
log.info("registered won node {} and start crawling it", nodeInfo.getWonNodeURI());
} catch (Exception e) {
addFailedWonNode(wonNodeUri, con);
log.error("Error subscribing for need updates at won node {}", wonNodeUri);
log.error("Exception message: {} \nCause: {} ", e.getMessage(), e.getCause());
}
return con;
}
/**
* Try to connect to unreachable won nodes from time to time
*/
private void lifeCheck() {
List<String> failedNodes = IteratorUtils.toList(failedWonNodeUris.iterator());
log.debug("retry to connect to all failed won nodes again: {}", failedNodes);
failedWonNodeUris.clear();
for (String uri : failedNodes) {
// try register at the wonnode again
WonNodeEvent e = new WonNodeEvent(uri, WonNodeEvent.STATUS.RETRY_REGISTER_FAILED_WON_NODE);
pubSubMediator.tell(new DistributedPubSubMediator.Publish(e.getClass().getName(), e), getSelf());
}
}
/**
* Add a won node to the failed list and stop all its consumers
*
* @param wonNodeUri
* @param con
*/
private void addFailedWonNode(String wonNodeUri, WonNodeConnection con) {
if (con != null) {
getContext().stop(con.getNeedCreatedConsumer());
getContext().stop(con.getNeedActivatedConsumer());
getContext().stop(con.getNeedDeactivatedConsumer());
}
crawlWonNodes.remove(wonNodeUri);
failedWonNodeUris.add(wonNodeUri);
}
private WonNodeConnection subscribeNeedUpdates(WonNodeInfo wonNodeInfo) {
return ActiveMqWonNodeConnectionFactory.createWonNodeConnection(getContext(), wonNodeInfo, messagingContext);
}
/**
* Handles connections errors that occur when the need consumer actors are terminated.
*
* @param t messages that holds a reference to consumer actor that was terminated
*/
private void handleConnectionErrors(Terminated t) {
for (String uri : crawlWonNodes.keySet()) {
WonNodeConnection con = crawlWonNodes.get(uri);
if (con != null) {
if (con.getNeedCreatedConsumer().equals(t.getActor())) {
log.error("NeedCreatedConsumer '{}' of won '{}' has been shut down", t.getActor(), uri);
addFailedWonNode(con.getWonNodeInfo().getWonNodeURI(), con);
} else if (con.getNeedActivatedConsumer().equals(t.getActor())) {
log.error("NeedActivatedConsumer '{}' of won '{}' has been shut down", t.getActor(), uri);
addFailedWonNode(con.getWonNodeInfo().getWonNodeURI(), con);
} else if (con.getNeedDeactivatedConsumer().equals(t.getActor())) {
log.error("NeedDeactivatedConsumer '{}' of won '{}' has been shut down", t.getActor(), uri);
addFailedWonNode(con.getWonNodeInfo().getWonNodeURI(), con);
} else if (con.getHintProducer().equals(t.getActor())) {
log.error("HintProducer '{}' of won '{}' has been shut down", t.getActor(), uri);
addFailedWonNode(con.getWonNodeInfo().getWonNodeURI(), con);
}
}
}
}
@Override
public SupervisorStrategy supervisorStrategy() {
SupervisorStrategy supervisorStrategy = new OneForOneStrategy(
0, Duration.Zero(), new Function<Throwable, SupervisorStrategy.Directive>() {
@Override
public SupervisorStrategy.Directive apply(Throwable t) throws Exception {
log.warning("Actor encountered error: {}", t);
// default behaviour
return SupervisorStrategy.escalate();
}
});
return supervisorStrategy;
}
}
|
package ch.puzzle.itc.mobiliar.business.property.control;
import ch.puzzle.itc.mobiliar.business.auditview.control.GenericAuditHandler;
import ch.puzzle.itc.mobiliar.business.auditview.entity.AuditViewEntry;
import ch.puzzle.itc.mobiliar.business.auditview.entity.AuditViewEntryContainer;
import ch.puzzle.itc.mobiliar.business.resourcegroup.entity.ResourceContextEntity;
import ch.puzzle.itc.mobiliar.common.util.Tuple;
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;
import org.hibernate.envers.query.AuditEntity;
import javax.ejb.Stateless;
import javax.inject.Named;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import java.math.BigDecimal;
@Stateless
@Named("propertyEntityAuditviewHandler")
public class PropertyEntityAuditviewHandler extends GenericAuditHandler {
// Property on Master Resource
private static final String SELECT_FOR_RESOURCE = "SELECT TAMW_RESOURCECONTEXT_ID " +
"FROM TAMW_RESOURCECTX_PROP " +
"WHERE PROPERTIES_ID = :propertyId";
private static final String SELECT_FOR_RESOURCE_FROM_AUDIT = "SELECT TAMW_RESOURCECONTEXT_ID " +
"FROM TAMW_RESOURCECTX_PROP_AUD " +
"WHERE rev >= :rev " +
"AND PROPERTIES_ID = :propertyId";
private static final String SELECT_FOR_PROP_ON_RESOURCE = String.format("%s UNION %s", SELECT_FOR_RESOURCE, SELECT_FOR_RESOURCE_FROM_AUDIT);
// Property on Consumed Resource
private static final String SELECT_NAME_AND_CONTEXT_FOR_PROP_ON_CONSUMED_RESOURCE =
" SELECT " +
" consumed_resource.NAME || " +
" CASE WHEN consumed_resource_relation.IDENTIFIER IS NOT NULL " +
" THEN ' (' || consumed_resource_relation.IDENTIFIER || ')' " +
" ELSE '' " +
" END, " +
" resource_relation_context.CONTEXT_ID " +
" FROM TAMW_RESOURCE consumed_resource " +
" JOIN TAMW_CONSUMEDRESREL consumed_resource_relation " +
" ON consumed_resource_relation.SLAVERESOURCE_ID = consumed_resource.ID " +
" JOIN TAMW_RESRELCONTEXT resource_relation_context " +
" ON consumed_resource_relation.ID = resource_relation_context.CONSUMEDRESOURCERELATION_ID " +
" JOIN TAMW_RESRELCTX_PROP resource_relation_context_prop " +
" ON resource_relation_context_prop.TAMW_RESRELCONTEXT_ID = resource_relation_context.ID " +
" WHERE resource_relation_context_prop.PROPERTIES_ID = :propertyId";
private static final String SELECT_NAME_AND_CONTEXT_FOR_PROP_ON_CONSUMED_RESOURCE_FROM_AUDIT =
" SELECT DISTINCT " +
"consumed_resource.NAME || " +
" CASE WHEN consumed_resource_relation.IDENTIFIER IS NOT NULL " +
" THEN ' (' || consumed_resource_relation.IDENTIFIER || ')' " +
" ELSE '' " +
" END, " +
"resource_relation_context.CONTEXT_ID " +
"FROM TAMW_RESOURCE_AUD consumed_resource " +
"JOIN TAMW_CONSUMEDRESREL_AUD consumed_resource_relation ON consumed_resource_relation.SLAVERESOURCE_ID = consumed_resource.ID " +
"JOIN TAMW_RESRELCONTEXT_AUD resource_relation_context ON consumed_resource_relation.ID = resource_relation_context.CONSUMEDRESOURCERELATION_ID " +
"JOIN TAMW_RESRELCTX_PROP_AUD resource_relation_context_prop ON resource_relation_context_prop.TAMW_RESRELCONTEXT_ID = resource_relation_context.ID " +
"JOIN TAMW_PROPERTY_AUD property on resource_relation_context_prop.PROPERTIES_ID = property.ID " +
"WHERE " +
"resource_relation_context_prop.PROPERTIES_ID = :propertyId " +
"AND property.REV = :revision " +
"AND rownum <= 1 " +
"ORDER BY property.REV";
private static final String SELECT_NAME_AND_CONTEXT_FOR_PROP_ON_PROVIDED_RESOURCE =
" SELECT provided_resource.NAME, resource_relation_context.CONTEXT_ID " +
" FROM TAMW_RESOURCE provided_resource " +
" JOIN TAMW_PROVIDEDRESREL provided_resource_relation " +
" ON provided_resource_relation.SLAVERESOURCE_ID = provided_resource.ID " +
" JOIN TAMW_RESRELCONTEXT resource_relation_context " +
" ON provided_resource_relation.ID = resource_relation_context.PROVIDEDRESOURCERELATION_ID " +
" JOIN TAMW_RESRELCTX_PROP resource_relation_context_prop " +
" ON resource_relation_context_prop.TAMW_RESRELCONTEXT_ID = resource_relation_context.ID " +
" WHERE resource_relation_context_prop.PROPERTIES_ID = :propertyId";
private static final String SELECT_NAME_AND_CONTEXT_FOR_PROP_ON_PROVIDED_RESOURCE_FROM_AUDIT =
" SELECT provided_resource.NAME, resource_relation_context.CONTEXT_ID " +
" FROM TAMW_RESOURCE_AUD provided_resource " +
" JOIN TAMW_PROVIDEDRESREL_AUD provided_resource_relation " +
" ON provided_resource_relation.SLAVERESOURCE_ID = provided_resource.ID " +
" JOIN TAMW_RESRELCONTEXT_AUD resource_relation_context " +
" ON provided_resource_relation.ID = resource_relation_context.PROVIDEDRESOURCERELATION_ID " +
" JOIN TAMW_RESRELCTX_PROP_AUD resource_relation_context_prop " +
" ON resource_relation_context_prop.TAMW_RESRELCONTEXT_ID = resource_relation_context.ID " +
" JOIN TAMW_PROPERTY_AUD prop " +
" ON prop.ID = resource_relation_context_prop.PROPERTIES_ID " +
" WHERE resource_relation_context_prop.PROPERTIES_ID = :propertyId " +
" AND ROWNUM = 1" +
" ORDER BY provided_resource_relation.REV DESC";
@Override
public AuditViewEntry createAuditViewEntry(AuditViewEntryContainer container) {
ResourceContextEntity resourceContextEntity = getResourceContextEntityForPropertyOnMasterResource(container);
boolean isPropertyOnMasterResource = resourceContextEntity != null;
if (isPropertyOnMasterResource) {
container.setEditContextId(resourceContextEntity.getId());
} else {
// property is on related resource (provided/consumed)
Tuple<String, Integer> nameAndContext = getNameAndContextOfConsumedResource(container);
boolean isPropertyOnConsumedResource = nameAndContext != null;
if (isPropertyOnConsumedResource){
container.setRelationName(String.format("%s: %s", AuditViewEntry.RELATION_CONSUMED_RESOURCE, nameAndContext.getA()));
container.setEditContextId(nameAndContext.getB());
} else {
// property is on provided resource
nameAndContext = getNameAndContextOfProvidedResource(container);
container.setRelationName(String.format("%s: %s", AuditViewEntry.RELATION_PROVIDED_RESOURCE, nameAndContext.getA()));
container.setEditContextId(nameAndContext.getB());
}
}
return super.createAuditViewEntry(container);
}
private Tuple<String, Integer> getNameAndContextOfProvidedResource(AuditViewEntryContainer container) {
Object[] nameAndId;
try {
nameAndId = (Object[]) entityManager
.createNativeQuery(SELECT_NAME_AND_CONTEXT_FOR_PROP_ON_PROVIDED_RESOURCE)
.setParameter("propertyId", container.getEntityForRevision().getId())
.getSingleResult();
} catch (NoResultException e) {
// deleted property, get it from audit tables
nameAndId = (Object[]) entityManager
.createNativeQuery(SELECT_NAME_AND_CONTEXT_FOR_PROP_ON_PROVIDED_RESOURCE_FROM_AUDIT)
.setParameter("propertyId", container.getEntityForRevision().getId())
.getSingleResult();
}
String name = (String) nameAndId[0];
int resourceContextId = ((BigDecimal) nameAndId[1]).intValue();
return new Tuple<>(name, resourceContextId);
}
/**
*
* @param container
* @return a Tuple<Name of consumed Resource, ContextId> or null
*/
private Tuple<String, Integer> getNameAndContextOfConsumedResource(AuditViewEntryContainer container) {
Object[] nameAndId;
try {
nameAndId = (Object[]) entityManager
.createNativeQuery(SELECT_NAME_AND_CONTEXT_FOR_PROP_ON_CONSUMED_RESOURCE)
.setParameter("propertyId", container.getEntityForRevision().getId())
.getSingleResult();
} catch (NoResultException e) {
nameAndId = (Object[]) entityManager
.createNativeQuery(SELECT_NAME_AND_CONTEXT_FOR_PROP_ON_CONSUMED_RESOURCE_FROM_AUDIT)
.setParameter("propertyId", container.getEntityForRevision().getId())
.setParameter("revision", container.getRevEntity().getId())
.getSingleResult();
}
String name = (String) nameAndId[0];
int resourceContextId = ((BigDecimal) nameAndId[1]).intValue();
return new Tuple<>(name, resourceContextId);
}
public ResourceContextEntity getResourceContextEntityForPropertyOnMasterResource(AuditViewEntryContainer container) {
try {
Query query = entityManager
.createNativeQuery(SELECT_FOR_PROP_ON_RESOURCE)
.setParameter("rev", container.getRevEntity().getId())
.setParameter("propertyId", container.getEntityForRevision().getId());
BigDecimal resourceContextId = (BigDecimal) query.getSingleResult();
AuditReader reader = AuditReaderFactory.get(entityManager);
return (ResourceContextEntity) reader.createQuery()
.forRevisionsOfEntity(ResourceContextEntity.class, true, true)
.add(AuditEntity.id().eq(resourceContextId.intValue()))
.setMaxResults(1)
.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
}
|
package fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.modules.tees;
import java.io.IOException;
import javax.xml.bind.JAXBException;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Corpus;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.DefaultNames;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.NameType;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.ResolverException;
import fr.inra.maiage.bibliome.alvisnlp.core.module.ModuleException;
import fr.inra.maiage.bibliome.alvisnlp.core.module.ProcessingContext;
import fr.inra.maiage.bibliome.alvisnlp.core.module.ProcessingException;
import fr.inra.maiage.bibliome.alvisnlp.core.module.lib.AlvisNLPModule;
import fr.inra.maiage.bibliome.alvisnlp.core.module.lib.Param;
import fr.inra.maiage.bibliome.util.files.InputFile;
/**
*
* @author mba
*
*/
@AlvisNLPModule
public abstract class TEESClassify extends TEESMapper {
private String dependencyRelationName = DefaultNames.getDependencyRelationName();
private String dependencyLabelFeatureName = DefaultNames.getDependencyLabelFeatureName();
private String sentenceRole = DefaultNames.getDependencySentenceRole();
private String headRole = DefaultNames.getDependencyHeadRole();
private String dependentRole = DefaultNames.getDependencyDependentRole();
private InputFile teesModel;
@Override
public void process(ProcessingContext<Corpus> ctx, Corpus corpus) throws ModuleException {
try {
new TEESClassifyExternalHandler(ctx, this, corpus).start();
}
catch (JAXBException | IOException | InterruptedException e) {
throw new ProcessingException(e);
}
}
/**
* Object resolver and Feature Handlers
*/
@Override
protected SectionResolvedObjects createResolvedObjects(ProcessingContext<Corpus> ctx) throws ResolverException {
return new SectionResolvedObjects(ctx, this);
}
@Override
protected String[] addLayersToSectionFilter() {
return new String[] {
getTokenLayerName(),
getSentenceLayerName()
};
}
@Override
protected String[] addFeaturesToSectionFilter() {
return null;
}
@Param(nameType = NameType.FEATURE)
public String getDependencyLabelFeatureName() {
return dependencyLabelFeatureName;
}
@Param(nameType = NameType.ARGUMENT)
public String getSentenceRole() {
return sentenceRole;
}
@Param(nameType = NameType.ARGUMENT)
public String getHeadRole() {
return headRole;
}
@Param(nameType = NameType.ARGUMENT)
public String getDependentRole() {
return dependentRole;
}
@Param(nameType = NameType.RELATION)
public String getDependencyRelationName() {
return dependencyRelationName;
}
public void setDependencyRelationName(String dependencyRelationName) {
this.dependencyRelationName = dependencyRelationName;
}
public void setDependencyLabelFeatureName(String dependencyLabelFeatureName) {
this.dependencyLabelFeatureName = dependencyLabelFeatureName;
}
public void setSentenceRole(String sentenceRole) {
this.sentenceRole = sentenceRole;
}
public void setHeadRole(String headRole) {
this.headRole = headRole;
}
public void setDependentRole(String dependentRole) {
this.dependentRole = dependentRole;
}
@Param
public InputFile getTeesModel() {
return teesModel;
}
public void setTeesModel(InputFile model) {
this.teesModel = model;
}
}
|
package org.csstudio.archive.reader.rdb;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.csstudio.archive.vtype.TimestampHelper;
import org.csstudio.platform.utility.rdb.RDBUtil.Dialect;
import org.epics.util.time.Timestamp;
import org.epics.vtype.VType;
/** Value Iterator that reads from the SAMPLE table.
* @author Kay Kasemir
* @author Lana Abadie (PostgreSQL)
*/
public class RawSampleIterator extends AbstractRDBValueIterator
{
/** SELECT ... for the start .. end samples. */
private PreparedStatement sel_samples = null;
/** Result of <code>sel_samples</code> */
private ResultSet result_set = null;
/** 'Current' value that <code>next()</code> will return,
* or <code>null</code>
*/
private VType value = null;
/** Initialize
* @param reader RDBArchiveReader
* @param channel_id ID of channel
* @param start Start time
* @param end End time
* @throws Exception on error
*/
public RawSampleIterator(final RDBArchiveReader reader,
final int channel_id, final Timestamp start,
final Timestamp end) throws Exception
{
super(reader, channel_id);
try
{
determineInitialSample(start, end);
}
catch (Exception ex)
{
if (! RDBArchiveReader.isCancellation(ex))
throw ex;
// Else: Not a real error; return empty iterator
value = null;
}
}
/** Get the samples: <code>result_set</code> will have the samples,
* <code>value</code> will contain the first sample
* @param start Start time
* @param end End time
* @throws Exception on error, including cancellation
*/
private void determineInitialSample(final Timestamp start, final Timestamp end) throws Exception
{
boolean autoCommit = reader.getRDB().getConnection().getAutoCommit();
// Disable auto-commit to determine sample with PostgreSQL
if (reader.getRDB().getDialect() == Dialect.PostgreSQL) {
reader.getRDB().getConnection().setAutoCommit(false);
}
java.sql.Timestamp start_stamp = TimestampHelper.toSQLTimestamp(start);
final java.sql.Timestamp end_stamp = TimestampHelper.toSQLTimestamp(end);
// Get time of initial sample
final PreparedStatement statement =
reader.getRDB().getConnection().prepareStatement(reader.getSQL().sample_sel_initial_time);
reader.addForCancellation(statement);
try
{
statement.setInt(1, channel_id);
statement.setTimestamp(2, start_stamp);
final ResultSet result = statement.executeQuery();
if (result.next())
{
// System.out.print("Start time corrected from " + start_stamp);
start_stamp = result.getTimestamp(1);
// Oracle has nanoseconds in TIMESTAMP, MySQL in separate column
if (reader.getRDB().getDialect() == Dialect.MySQL || reader.getRDB().getDialect() == Dialect.PostgreSQL)
start_stamp.setNanos(result.getInt(2));
// System.out.println(" to " + start_stamp);
}
}
finally
{
reader.removeFromCancellation(statement);
statement.close();
}
// Fetch the samples
if (reader.useArrayBlob())
sel_samples = reader.getRDB().getConnection().prepareStatement(
reader.getSQL().sample_sel_by_id_start_end_with_blob);
else
sel_samples = reader.getRDB().getConnection().prepareStatement(
reader.getSQL().sample_sel_by_id_start_end);
sel_samples.setFetchDirection(ResultSet.FETCH_FORWARD);
// Test w/ ~170000 raw samples:
// 10 17 seconds
// 100 6 seconds
// 1000 4.x seconds
// 10000 4.x seconds
// 100000 4.x seconds
// So default is bad. 100 or 1000 are good.
// Bigger numbers don't help much in repeated tests, but
// just to be on the safe side, use a bigger number.
sel_samples.setFetchSize(Preferences.getFetchSize());
reader.addForCancellation(sel_samples);
sel_samples.setInt(1, channel_id);
sel_samples.setTimestamp(2, start_stamp);
sel_samples.setTimestamp(3, end_stamp);
result_set = sel_samples.executeQuery();
// Get first sample
if (result_set.next())
value = decodeSampleTableValue(result_set, true);
// else leave value null to indicate end of samples
// Restore auto-commit value as defined before execution of this method
reader.getRDB().getConnection().setAutoCommit(autoCommit);
}
/** {@inheritDoc} */
@Override
public boolean hasNext()
{
return value != null;
}
/** {@inheritDoc} */
@Override
@SuppressWarnings("nls")
public VType next() throws Exception
{
// This should not happen...
if (result_set == null)
throw new Exception("RawSampleIterator.next(" + channel_id + ") called after end");
// Remember value to return...
final VType result = value;
// ... and prepare next value
try
{
if (result_set.next())
value = decodeSampleTableValue(result_set, true);
else
close();
}
catch (Exception ex)
{
close();
if (! RDBArchiveReader.isCancellation(ex))
throw ex;
// Else: Not a real error; return empty iterator
}
return result;
}
/** Release all database resources.
* OK to call more than once.
*/
@Override
public void close()
{
super.close();
value = null;
if (result_set != null)
{
try
{
result_set.close();
}
catch (Exception ex)
{
// Ignore
}
result_set = null;
}
if (sel_samples != null)
{
reader.removeFromCancellation(sel_samples);
try
{
sel_samples.close();
}
catch (Exception ex)
{
// Ignore
}
sel_samples = null;
}
}
}
|
package io.beanmother.joda.converter;
import com.google.common.reflect.TypeToken;
import io.beanmother.core.converter.AbstractConverter;
import io.beanmother.core.converter.ConverterException;
import org.joda.time.base.BaseLocal;
import java.lang.reflect.Constructor;
import java.util.Date;
/**
* Date to BaseLocal({@link org.joda.time.LocalDate}, {@link org.joda.time.LocalTime} and {@link org.joda.time.LocalDateTime} converter.
*/
public class DateToJodaTimeBaseLocalConverter extends AbstractConverter {
@SuppressWarnings("unchecked")
@Override
public Object convert(Object source, TypeToken<?> targetTypeToken) {
if (!canHandle(source, targetTypeToken)) {
throw new ConverterException(source, targetTypeToken.getRawType());
}
Constructor constructor;
try {
constructor = ((Class) targetTypeToken.getType()).getConstructor(Object.class);
} catch (NoSuchMethodException e) {
throw new ConverterException(source, targetTypeToken.getRawType(), e);
}
try {
return constructor.newInstance(source);
} catch (Exception e) {
throw new ConverterException(source, targetTypeToken.getRawType(), e);
}
}
@Override
public boolean canHandle(Object source, TypeToken<?> targetTypeToken) {
return targetTypeToken.isSubtypeOf(BaseLocal.class) && (source instanceof Date);
}
}
|
package de.martinreinhardt.cordova.plugins.hotspot;
import android.app.Activity;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.util.Log;
import com.mady.wifi.api.WifiAddresses;
import com.mady.wifi.api.WifiHotSpots;
import com.mady.wifi.api.WifiStatus;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
public class HotSpotPlugin extends CordovaPlugin {
/**
* Logging Tag
*/
private static final String LOG_TAG = "HotSpotPlugin";
private CallbackContext command;
/**
* Executes the request.
* <p/>
* This method is called from the WebView thread.
* To do a non-trivial amount of work, use:
* cordova.getThreadPool().execute(runnable);
* <p/>
* To run on the UI thread, use:
* cordova.getActivity().runOnUiThread(runnable);
*
* @param action The action to execute.
* @param args The exec() arguments in JSON form.
* @param callback The callback context used when calling
* back into JavaScript.
* @return Whether the action was valid.
*/
@Override
public boolean execute(String action, JSONArray args,
CallbackContext callback) throws JSONException {
this.command = callback;
if ("isWifiOn".equals(action)) {
if (isWifiOn()) {
callback.success();
} else {
callback.error("Wifi is off.");
}
return true;
}
if ("toggleWifi".equals(action)) {
try {
if (toggleWifi()) {
callback.success(1);
} else {
callback.success(1);
}
} catch (Exception e) {
Log.e(LOG_TAG, "Got unknown error during toggle wifi", e);
callback.error("Toggle wifi failed.");
return true;
}
}
if ("createHotspot".equals(action)) {
createHotspot(args, true, true, callback);
return true;
}
if ("configureHotspot".equals(action)) {
createHotspot(null, false, true, callback);
return true;
}
if ("startHotspot".equals(action)) {
createHotspot(null, true, false, callback);
return true;
}
if ("stopHotspot".equals(action)) {
stopHotspot(callback);
return true;
}
if ("isHotspotEnabled".equals(action)) {
isHotspotEnabled(callback);
return true;
}
if ("getAllHotspotDevices".equals(action)) {
getAllHotspotDevices(callback);
return true;
}
if ("scanWifi".equals(action)) {
scanWifi(callback);
return true;
}
if ("scanWifiByLevel".equals(action)) {
scanWifiByLevel(callback);
return true;
}
if ("startPeriodicallyScan".equals(action)) {
startPeriodicallyScan(args, callback);
return true;
}
if ("stopPeriodicallyScan".equals(action)) {
stopPeriodicallyScan(callback);
return true;
}
if ("isConnectedToInternet".equals(action)) {
if (isConnectedToInternet()) {
callback.success();
} else {
callback.error("Device is not connected to internet");
}
return true;
}
if ("isConnectedToInternetViaWifi".equals(action)) {
if (isConnectedToInternetViaWifi()) {
callback.success();
} else {
callback.error("Device is not connected to internet via WiFi");
}
return true;
}
if ("getNetConfig".equals(action)) {
getNetConfig(callback);
return true;
}
if ("getConnectionInfo".equals(action)) {
getConnectionInfo(callback);
return true;
}
if ("pingHost".equals(action)) {
pingHost(args, callback);
return true;
}
if ("dnsLive".equals(action)) {
dnsLive(args, callback);
return true;
}
if ("portLive".equals(action)) {
portLive(args, callback);
return true;
}
if ("getMacAddressOfHost".equals(action)) {
getMacAddressOfHost(args, callback);
return true;
}
if ("checkRoot".equals(action)) {
checkRoot(callback);
return true;
}
if ("isWifiSupported".equals(action)) {
if (isWifiSupported()) {
callback.success();
} else {
callback.error("Wifi is not supported.");
}
return true;
}
if ("isWifiDirectSupported".equals(action)) {
if (isWifiDirectSupported()) {
callback.success();
} else {
callback.error("Wifi direct is not supported.");
}
return true;
}
if ("addWifiNetwork".equals(action)) {
addWifiNetwork(args, callback);
return true;
}
if ("removeWifiNetwork".equals(action)) {
removeWifiNetwork(args, callback);
return true;
}
if ("connectToHotspot".equals(action)) {
connectToHotspot(args, callback);
return true;
}
if ("configureHotspot".equals(action)) {
configureHotspot(args, callback);
return true;
}
// Returning false results in a "MethodNotFound" error.
return false;
}
// IMPLEMENTATION
private void checkRoot(CallbackContext callback) {
WifiAddresses wu = new WifiAddresses(this.cordova.getActivity());
if (wu.CheckRoot()) {
callback.success(1);
} else {
callback.success(0);
}
}
private void dnsLive(JSONArray args, CallbackContext callback) {
try {
final String host = args.getString(0);
WifiAddresses wu = new WifiAddresses(this.cordova.getActivity());
if (wu.dnsIsALive(host)) {
callback.success(1);
} else {
callback.success(0);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error checking DNS.", e);
callback.error("Error checking DNS.");
}
}
private void portLive(JSONArray args, CallbackContext callback) {
try {
final String host = args.getString(0);
WifiAddresses wu = new WifiAddresses(this.cordova.getActivity());
if (wu.portIsALive(host)) {
callback.success(1);
} else {
callback.success(0);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error checking port.", e);
callback.error("Error checking port.");
}
}
private void getConnectionInfo(CallbackContext callback) {
WifiInfo wifiInfo = new WifiHotSpots(this.cordova.getActivity()).getConnectionInfo();
JSONObject result = new JSONObject();
try {
result.put("SSID", wifiInfo.getSSID());
result.put("BSSID", wifiInfo.getBSSID());
result.put("linkSpeed", wifiInfo.getLinkSpeed());
result.put("IPAddress", intToInetAddress(wifiInfo.getIpAddress())).toString();
result.put("networkID", wifiInfo.getNetworkId());
callback.success(result);
} catch (JSONException e) {
Log.e(LOG_TAG, "Error during reading connection info.", e);
callback.error("Error during reading connection info.");
}
}
private void getNetConfig(CallbackContext callback) {
WifiAddresses wu = new WifiAddresses(this.cordova.getActivity());
JSONObject result = new JSONObject();
try {
result.put("deviceIPAddress", wu.getDeviceIPAddress());
result.put("deviceMacAddress", wu.getDeviceMacAddress());
result.put("gatewayIPAddress", wu.getGatewayIPAddress());
result.put("gatewayMacAddress", wu.getGatWayMacAddress());
callback.success(result);
} catch (JSONException e) {
Log.e(LOG_TAG, "Error during reading network config.", e);
callback.error("Error during reading network config.");
}
}
private void pingHost(JSONArray args, CallbackContext pCallback) throws JSONException {
final String host = args.getString(0);
final Activity activity = this.cordova.getActivity();
final CallbackContext callback = pCallback;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
WifiAddresses wu = new WifiAddresses(activity);
if (wu.pingCmd(host)) {
callback.success(wu.getPingResulta(host));
} else {
callback.success();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Ping to host " + host + " failed", e);
callback.error("Ping failed");
}
}
});
}
private void getMacAddressOfHost(JSONArray args, CallbackContext pCallback) throws JSONException {
final String host = args.getString(0);
final Activity activity = this.cordova.getActivity();
final CallbackContext callback = pCallback;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
WifiAddresses wu = new WifiAddresses(activity);
if (wu.pingCmd(host)) {
callback.success(wu.getArpMacAddress(host));
} else {
callback.success();
}
} catch (Exception e) {
Log.e(LOG_TAG, "ARP request to host " + host + " failed", e);
callback.error("ARP request");
}
}
});
}
private void startPeriodicallyScan(JSONArray args, CallbackContext pCallback) throws JSONException {
final long interval = args.getLong(0);
final long duration = args.getLong(1);
final Activity activity = this.cordova.getActivity();
final CallbackContext callback = pCallback;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
new WifiHotSpots(activity).startScan(interval, duration);
} catch (Exception e) {
Log.e(LOG_TAG, "Got unkown error during starting scan", e);
callback.error("Scan start failed");
}
}
});
}
private void stopPeriodicallyScan(CallbackContext pCallback) {
final Activity activity = this.cordova.getActivity();
final CallbackContext callback = pCallback;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
new WifiHotSpots(activity).stopScan();
} catch (Exception e) {
Log.e(LOG_TAG, "Got unkown error during stopping scan", e);
callback.error("Scan stop failed");
}
}
});
}
private void configureHotspot(JSONArray args, CallbackContext pCallback) throws JSONException {
final String ssid = args.getString(0);
final String password = args.getString(1);
final String mode = args.getString(2);
final Activity activity = this.cordova.getActivity();
final CallbackContext callback = pCallback;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (isHotspotEnabled()) {
WifiHotSpots hotspot = new WifiHotSpots(activity);
if (hotspot.setHotSpot(ssid, mode, password)) {
callback.success();
} else {
callback.error("Hotspot config was not successfull");
}
} else {
callback.error("Hotspot not enabled");
}
}
});
}
private void scanWifi(CallbackContext pCallback, final boolean sortByLevel) {
final Activity activity = this.cordova.getActivity();
final CallbackContext callback = pCallback;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
WifiHotSpots hotspot = new WifiHotSpots(activity);
List<ScanResult> response = sortByLevel ? hotspot.getHotspotsList() : hotspot.sortHotspotsByLevel();
// if null wait and try again
if (response == null || response.size() == 0) {
Thread.sleep(4000);
response = sortByLevel ? hotspot.getHotspotsList() : hotspot.sortHotspotsByLevel();
}
JSONArray results = new JSONArray();
if (response != null && response.size() > 0) {
for (ScanResult scanResult : response) {
JSONObject result = new JSONObject();
result.put("SSID", scanResult.SSID);
result.put("BSSID", scanResult.BSSID);
result.put("frequency", scanResult.frequency);
result.put("level", scanResult.level);
result.put("timestamp", String.valueOf(scanResult.timestamp));
result.put("capabilities", scanResult.capabilities);
results.put(result);
}
}
callback.success(results);
} catch (Exception e) {
Log.e(LOG_TAG, "Wifi scan failed", e);
callback.error("Wifi scan failed.");
}
}
});
}
private void scanWifi(CallbackContext pCallback) {
scanWifi(pCallback, false);
}
private void scanWifiByLevel(CallbackContext pCallback) {
scanWifi(pCallback, true);
}
private void removeWifiNetwork(JSONArray args, CallbackContext pCallback) throws JSONException {
final String ssid = args.getString(0);
final Activity activity = this.cordova.getActivity();
final CallbackContext callback = pCallback;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
WifiHotSpots hotspot = new WifiHotSpots(activity);
hotspot.removeWifiNetwork(ssid);
callback.success();
}
});
}
public void addWifiNetwork(JSONArray args, CallbackContext pCallback) throws JSONException {
final String ssid = args.getString(0);
final String password = args.getString(1);
final String mode = args.getString(2);
final Activity activity = this.cordova.getActivity();
final CallbackContext callback = pCallback;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
WifiHotSpots hotspot = new WifiHotSpots(activity);
hotspot.addWifiNetwork(ssid, password, mode);
callback.success();
}
});
}
public void isHotspotEnabled(CallbackContext pCallback) {
final CallbackContext callback = pCallback;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (isHotspotEnabled()) {
callback.success();
} else {
callback.error("Hotspot check failed.");
}
}
});
}
public void createHotspot(JSONArray args, final boolean start, boolean configure, CallbackContext pCallback) throws JSONException {
final Activity activity = this.cordova.getActivity();
final CallbackContext callback = pCallback;
if (configure) {
final String ssid = args.getString(0);
final String password = args.getString(1);
final String mode = args.getString(2);
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
WifiHotSpots hotspot = new WifiHotSpots(activity);
if (isHotspotEnabled() && start) {
hotspot.startHotSpot(false);
}
if (hotspot.setHotSpot(ssid, mode, password)) {
try {
if (start) {
// Wait to connect
Thread.sleep(4000);
if (hotspot.startHotSpot(true)) {
callback.success();
} else {
callback.error("Hotspot customization failed.");
}
} else {
callback.success();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Got unknown error during hotspot configuration", e);
callback.error("Hotspot configuration failed.");
}
} else {
callback.error("Hotspot creation failed.");
}
}
});
} else {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
WifiHotSpots hotspot = new WifiHotSpots(activity);
if (isHotspotEnabled()) {
hotspot.startHotSpot(false);
}
try {
if (hotspot.startHotSpot(true)) {
// Wait to connect
Thread.sleep(4000);
callback.success();
} else {
callback.error("Hotspot start failed.");
}
} catch (Exception e) {
Log.e(LOG_TAG, "Got unknown error during hotspot start", e);
callback.error("Hotspot start failed.");
}
}
});
}
}
public void stopHotspot(CallbackContext pCallback) throws JSONException {
final Activity activity = this.cordova.getActivity();
final CallbackContext callback = pCallback;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
WifiHotSpots hotspot = new WifiHotSpots(activity);
if (isHotspotEnabled()) {
if (!hotspot.startHotSpot(false)) {
callback.error("Hotspot creation failed.");
}
}
callback.success();
}
});
}
public void getAllHotspotDevices(CallbackContext callback) {
WifiAddresses au = new WifiAddresses(this.cordova.getActivity());
ArrayList<String> ipList = au.getAllDevicesIp();
if (ipList != null) {
try {
Log.d(LOG_TAG, "Checking following IPs: " + ipList);
JSONArray result = new JSONArray();
for (String ip : ipList) {
String mac = au.getArpMacAddress(ip);
JSONObject entry = new JSONObject();
entry.put("ip", ip);
entry.put("mac", mac);
// push entry to list
result.put(entry);
}
callback.success(result);
} catch (JSONException e) {
Log.e(LOG_TAG, "Got JSON error during device listing", e);
callback.error("Hotspot device listing failed.");
}
} else {
callback.error("Hotspot device listing failed.");
}
}
public boolean connectToHotspot(JSONArray args, CallbackContext pCallback) throws JSONException {
final String ssid = args.getString(0);
final String password = args.getString(1);
final Activity activity = this.cordova.getActivity();
final CallbackContext callback = pCallback;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
WifiHotSpots hotspot = new WifiHotSpots(activity);
try {
if (hotspot.connectToHotspot(ssid, password)) {
// Wait to connect
Thread.sleep(4000);
if (isConnectedToWifi()) {
callback.success();
} else {
callback.error("Connection was not successfull");
}
} else {
callback.error("Connection was not successfull");
}
} catch (Exception e) {
Log.e(LOG_TAG, "Got unknown error during hotspot connect", e);
callback.error("Hotspot connect failed.");
}
}
});
return true;
}
public boolean isHotspotEnabled() {
if (new WifiHotSpots(this.cordova.getActivity()).isWifiApEnabled()) {
return true;
} else {
return false;
}
}
public boolean toggleWifi() {
WifiStatus wu = new WifiStatus(this.cordova.getActivity());
return wu.wifiToggle();
}
public boolean isWifiOn() {
WifiStatus wu = new WifiStatus(this.cordova.getActivity());
return wu.isWifiEnabled();
}
public boolean isWifiSupported() {
WifiStatus wu = new WifiStatus(this.cordova.getActivity());
return wu.isSupportWifi();
}
public boolean isWifiDirectSupported() {
WifiStatus wu = new WifiStatus(this.cordova.getActivity());
return wu.isSupportWifiDirect();
}
private boolean isConnectedToInternetViaWifi() {
WifiStatus wu = new WifiStatus(this.cordova.getActivity());
return isConnectedToWifi() && wu.isConnectedToInternet();
}
private boolean isConnectedToWifi() {
WifiStatus wu = new WifiStatus(this.cordova.getActivity());
return wu.checkWifi(wu.DATA_BY_WIFI);
}
private boolean isConnectedToInternet() {
WifiStatus wu = new WifiStatus(this.cordova.getActivity());
return wu.isConnectedToInternet();
}
// HELPER
/**
* Called when an activity you launched exits, giving you the reqCode you
* started it with, the resCode it returned, and any additional data from it.
*
* @param reqCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resCode The integer result code returned by the child activity
* through its setResult().
* @param intent An Intent, which can return result data to the caller
* (various data can be attached to Intent "extras").
*/
@Override
public void onActivityResult(int reqCode, int resCode, Intent intent) {
command.success();
}
/**
* Convert a IPv4 address from an integer to an InetAddress.
*
* @param hostAddress an int corresponding to the IPv4 address in network byte order
*/
public InetAddress intToInetAddress(int hostAddress) {
byte[] addressBytes = {(byte) (0xff & hostAddress),
(byte) (0xff & (hostAddress >> 8)),
(byte) (0xff & (hostAddress >> 16)),
(byte) (0xff & (hostAddress >> 24))};
try {
return InetAddress.getByAddress(addressBytes);
} catch (UnknownHostException e) {
throw new AssertionError();
}
}
}
|
package com.maddyhome.idea.vim.action.copy;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.action.VimCommandAction;
import com.maddyhome.idea.vim.command.Command;
import com.maddyhome.idea.vim.command.MappingMode;
import com.maddyhome.idea.vim.common.TextRange;
import com.maddyhome.idea.vim.handler.CaretOrder;
import com.maddyhome.idea.vim.handler.VisualOperatorActionHandler;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.List;
import java.util.Set;
/**
* @author vlan
*/
public class PutVisualTextMoveCursorAction extends VimCommandAction {
public PutVisualTextMoveCursorAction() {
super(new VisualOperatorActionHandler(true, CaretOrder.DECREASING_OFFSET) {
@Override
protected boolean execute(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context,
@NotNull Command cmd, @NotNull TextRange range) {
return VimPlugin.getCopy().putVisualRange(editor, caret, context, range, cmd.getCount(), true, true);
}
});
}
@NotNull
@Override
public Set<MappingMode> getMappingModes() {
return MappingMode.V;
}
@NotNull
@Override
public Set<List<KeyStroke>> getKeyStrokesSet() {
return parseKeysSet("gp", "gP");
}
@NotNull
@Override
public Command.Type getType() {
return Command.Type.PASTE;
}
@Override
public int getFlags() {
return Command.FLAG_EXIT_VISUAL;
}
}
|
package com.mbppower;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import org.apache.cordova.LOG;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class CameraActivity extends Fragment {
public interface CameraPreviewListener {
public void onPictureTaken(String originalPicturePath);//, String previewPicturePath);
}
private CameraPreviewListener eventListener;
private static final String TAG = "CameraActivity";
public FrameLayout mainLayout;
public FrameLayout frameContainerLayout;
private Preview mPreview;
private boolean canTakePicture = true;
private View view;
private Camera.Parameters cameraParameters;
private Camera mCamera;
private int numberOfCameras;
private int cameraCurrentlyLocked;
// The first rear facing camera
private int defaultCameraId;
public String defaultCamera;
public boolean tapToTakePicture;
public boolean dragEnabled;
public int width;
public int height;
public int x;
public int y;
public void setEventListener(CameraPreviewListener listener){
eventListener = listener;
}
private String appResourcesPackage;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
appResourcesPackage = getActivity().getPackageName();
// Inflate the layout for this fragment
view = inflater.inflate(getResources().getIdentifier("camera_activity", "layout", appResourcesPackage), container, false);
createCameraPreview();
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void setRect(int x, int y, int width, int height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
private void createCameraPreview(){
if(mPreview == null) {
setDefaultCameraId();
//set box position and size
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, height);
layoutParams.setMargins(x, y, 0, 0);
frameContainerLayout = (FrameLayout) view.findViewById(getResources().getIdentifier("frame_container", "id", appResourcesPackage));
frameContainerLayout.setLayoutParams(layoutParams);
//video view
mPreview = new Preview(getActivity());
mainLayout = (FrameLayout) view.findViewById(getResources().getIdentifier("video_view", "id", appResourcesPackage));
mainLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
mainLayout.addView(mPreview);
mainLayout.setEnabled(false);
}
}
private void setDefaultCameraId(){
// Find the total number of cameras available
numberOfCameras = Camera.getNumberOfCameras();
int camId = defaultCamera.equals("front") ? Camera.CameraInfo.CAMERA_FACING_FRONT : Camera.CameraInfo.CAMERA_FACING_BACK;
// Find the ID of the default camera
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == camId) {
defaultCameraId = camId;
break;
}
}
}
@Override
public void onResume() {
super.onResume();
mCamera = Camera.open(defaultCameraId);
if (cameraParameters != null) {
mCamera.setParameters(cameraParameters);
}
cameraCurrentlyLocked = defaultCameraId;
mPreview.setCamera(mCamera, cameraCurrentlyLocked);
Log.d(TAG, "cameraCurrentlyLocked:" + cameraCurrentlyLocked);
final FrameLayout frameContainerLayout = (FrameLayout) view.findViewById(getResources().getIdentifier("frame_container", "id", appResourcesPackage));
ViewTreeObserver viewTreeObserver = frameContainerLayout.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
frameContainerLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
frameContainerLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
final RelativeLayout frameCamContainerLayout = (RelativeLayout) view.findViewById(getResources().getIdentifier("frame_camera_cont", "id", appResourcesPackage));
FrameLayout.LayoutParams camViewLayout = new FrameLayout.LayoutParams(frameContainerLayout.getWidth(), frameContainerLayout.getHeight());
camViewLayout.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
frameCamContainerLayout.setLayoutParams(camViewLayout);
}
});
}
}
@Override
public void onPause() {
super.onPause();
// Because the Camera object is a shared resource, it's very
// important to release it when the activity is paused.
if (mCamera != null) {
mPreview.setCamera(null, -1);
mCamera.release();
mCamera = null;
}
}
public Camera getCamera() {
return mCamera;
}
public void switchCamera() {
// check for availability of multiple cameras
if (numberOfCameras == 1) {
//There is only one camera available
}
Log.d(TAG, "numberOfCameras: " + numberOfCameras);
// OK, we have multiple cameras.
// Release this camera -> cameraCurrentlyLocked
if (mCamera != null) {
mCamera.stopPreview();
mPreview.setCamera(null, -1);
mCamera.release();
mCamera = null;
}
// Acquire the next camera and request Preview to reconfigure
// parameters.
mCamera = Camera.open((cameraCurrentlyLocked + 1) % numberOfCameras);
if (cameraParameters != null) {
mCamera.setParameters(cameraParameters);
}
cameraCurrentlyLocked = (cameraCurrentlyLocked + 1) % numberOfCameras;
mPreview.switchCamera(mCamera, cameraCurrentlyLocked);
Log.d(TAG, "cameraCurrentlyLocked new: " + cameraCurrentlyLocked);
// Start the preview
mCamera.startPreview();
}
public void setCameraParameters(Camera.Parameters params) {
cameraParameters = params;
if (mCamera != null && cameraParameters != null) {
mCamera.setParameters(cameraParameters);
}
}
public boolean hasFrontCamera(){
return getActivity().getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);
}
public Bitmap cropBitmap(Bitmap bitmap, Rect rect){
int w = rect.right - rect.left;
int h = rect.bottom - rect.top;
Bitmap ret = Bitmap.createBitmap(w, h, bitmap.getConfig());
Canvas canvas= new Canvas(ret);
canvas.drawBitmap(bitmap, -rect.left, -rect.top, null);
return ret;
}
public void takePicture(final double maxWidth, final double maxHeight){
final ImageView pictureView = (ImageView) view.findViewById(getResources().getIdentifier("picture_view", "id", appResourcesPackage));
if(mPreview != null) {
if(!canTakePicture)
return;
canTakePicture = false;
mPreview.setOneShotPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(final byte[] data, final Camera camera) {
new Thread() {
public void run() {
//raw picture
byte[] bytes = mPreview.getFramePicture(data, camera);
final Bitmap pic = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//scale down
float scale = (float)pictureView.getWidth()/(float)pic.getWidth();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(pic, (int)(pic.getWidth()*scale), (int)(pic.getHeight()*scale), false);
final Matrix matrix = new Matrix();
if (cameraCurrentlyLocked == Camera.CameraInfo.CAMERA_FACING_FRONT) {
Log.d(TAG, "mirror y axis");
matrix.preScale(-1.0f, 1.0f);
}
Log.d(TAG, "preRotate " + mPreview.getDisplayOrientation() + "deg");
matrix.postRotate(mPreview.getDisplayOrientation());
final Bitmap fixedPic = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, false);
final Rect rect = new Rect(mPreview.mSurfaceView.getLeft(), mPreview.mSurfaceView.getTop(), mPreview.mSurfaceView.getRight(), mPreview.mSurfaceView.getBottom());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
pictureView.setImageBitmap(fixedPic);
pictureView.layout(rect.left, rect.top, rect.right, rect.bottom);
Bitmap finalPic = null;
//scale final picture
if(maxWidth > 0 && maxHeight > 0){
final double scaleHeight = maxWidth/(double)pic.getHeight();
final double scaleWidth = maxHeight/(double)pic.getWidth();
final double scale = scaleHeight < scaleWidth ? scaleWidth : scaleHeight;
finalPic = Bitmap.createScaledBitmap(pic, (int)(pic.getWidth()*scale), (int)(pic.getHeight()*scale), false);
}
else{
finalPic = pic;
}
Bitmap originalPicture = Bitmap.createBitmap(finalPic, 0, 0, (int)(finalPic.getWidth()), (int)(finalPic.getHeight()), matrix, false);
Bitmap picture;/*
//get bitmap and compress
Bitmap picture = loadBitmapFromView(view.findViewById(getResources().getIdentifier("frame_camera_cont", "id", appResourcesPackage)));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
picture.compress(Bitmap.CompressFormat.PNG, 80, stream);*/
generatePictureFromView(originalPicture, picture);
canTakePicture = true;
}
});
}
}.start();
}
});
}
else{
canTakePicture = true;
}
}
private void generatePictureFromView(final Bitmap originalPicture, final Bitmap picture){
final FrameLayout cameraLoader = (FrameLayout)view.findViewById(getResources().getIdentifier("camera_loader", "id", appResourcesPackage));
cameraLoader.setVisibility(View.VISIBLE);
final ImageView pictureView = (ImageView) view.findViewById(getResources().getIdentifier("picture_view", "id", appResourcesPackage));
new Thread() {
public void run() {
try {
// final File picFile = storeImage(picture, "_preview");
final File originalPictureFile = storeImage(originalPicture, "_original");
eventListener.onPictureTaken(originalPictureFile.getAbsolutePath());//, picFile.getAbsolutePath());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
cameraLoader.setVisibility(View.INVISIBLE);
pictureView.setImageBitmap(null);
}
});
}
catch(Exception e){
//An unexpected error occurred while saving the picture.
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
cameraLoader.setVisibility(View.INVISIBLE);
pictureView.setImageBitmap(null);
}
});
}
}
}.start();
}
private File getOutputMediaFile(String suffix){
File mediaStorageDir = getActivity().getApplicationContext().getFilesDir();
/*if(Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED && Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED_READ_ONLY) {
mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Android/data/" + getActivity().getApplicationContext().getPackageName() + "/Files");
}*/
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("dd_MM_yyyy_HHmm_ss").format(new Date());
File mediaFile;
String mImageName = "camerapreview_" + timeStamp + suffix + ".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
private File storeImage(Bitmap image, String suffix) {
File pictureFile = getOutputMediaFile(suffix);
if (pictureFile != null) {
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.JPEG, 80, fos);
fos.close();
return pictureFile;
}
catch (Exception ex) {
}
}
return null;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap( v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
return b;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
class Preview extends RelativeLayout implements SurfaceHolder.Callback {
private final String TAG = "Preview";
CustomSurfaceView mSurfaceView;
SurfaceHolder mHolder;
Camera.Size mPreviewSize;
List<Camera.Size> mSupportedPreviewSizes;
Camera mCamera;
int cameraId;
int displayOrientation;
Preview(Context context) {
super(context);
mSurfaceView = new CustomSurfaceView(context);
addView(mSurfaceView);
requestLayout();
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void setCamera(Camera camera, int cameraId) {
mCamera = camera;
this.cameraId = cameraId;
if (mCamera != null) {
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
setCameraDisplayOrientation();
//mCamera.getParameters().setRotation(getDisplayOrientation());
//requestLayout();
}
}
public int getDisplayOrientation() {
return displayOrientation;
}
private void setCameraDisplayOrientation() {
Camera.CameraInfo info=new Camera.CameraInfo();
int rotation=
((Activity)getContext()).getWindowManager().getDefaultDisplay()
.getRotation();
int degrees=0;
DisplayMetrics dm=new DisplayMetrics();
Camera.getCameraInfo(cameraId, info);
((Activity)getContext()).getWindowManager().getDefaultDisplay().getMetrics(dm);
switch (rotation) {
case Surface.ROTATION_0:
degrees=0;
break;
case Surface.ROTATION_90:
degrees=90;
break;
case Surface.ROTATION_180:
degrees=180;
break;
case Surface.ROTATION_270:
degrees=270;
break;
}
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
displayOrientation=(info.orientation + degrees) % 360;
displayOrientation=(360 - displayOrientation) % 360;
} else {
displayOrientation=(info.orientation - degrees + 360) % 360;
}
Log.d(TAG, "screen is rotated " + degrees + "deg from natural");
Log.d(TAG, (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ? "front" : "back")
+ " camera is oriented -" + info.orientation + "deg from natural");
Log.d(TAG, "need to rotate preview " + displayOrientation + "deg");
mCamera.setDisplayOrientation(displayOrientation);
}
public void switchCamera(Camera camera, int cameraId) {
setCamera(camera, cameraId);
try {
camera.setPreviewDisplay(mHolder);
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
camera.setParameters(parameters);
}
catch (IOException exception) {
Log.e(TAG, exception.getMessage());
}
//requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// We purposely disregard child measurements because act as a
// wrapper to a SurfaceView that centers the camera preview instead
// of stretching it.
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if (mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed && getChildCount() > 0) {
final View child = getChildAt(0);
int width = r - l;
int height = b - t;
int previewWidth = width;
int previewHeight = height;
if (mPreviewSize != null) {
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
if(displayOrientation == 90 || displayOrientation == 270) {
previewWidth = mPreviewSize.height;
previewHeight = mPreviewSize.width;
}
LOG.d(TAG, "previewWidth:" + previewWidth + " previewHeight:" + previewHeight);
}
int nW;
int nH;
int top;
int left;
float scale = 1.0f;
// Center the child SurfaceView within the parent.
if (width * previewHeight < height * previewWidth) {
Log.d(TAG, "center horizontally");
int scaledChildWidth = (int)((previewWidth * height / previewHeight) * scale);
nW = (width + scaledChildWidth) / 2;
nH = (int)(height * scale);
top = 0;
left = (width - scaledChildWidth) / 2;
}
else {
Log.d(TAG, "center vertically");
int scaledChildHeight = (int)((previewHeight * width / previewWidth) * scale);
nW = (int)(width * scale);
nH = (height + scaledChildHeight) / 2;
top = (height - scaledChildHeight) / 2;
left = 0;
}
child.layout(left, top, nW, nH);
Log.d("layout", "left:" + left);
Log.d("layout", "top:" + top);
Log.d("layout", "right:" + nW);
Log.d("layout", "bottom:" + nH);
}
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
try {
if (mCamera != null) {
mSurfaceView.setWillNotDraw(false);
mCamera.setPreviewDisplay(holder);
}
} catch (IOException exception) {
Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
if (mCamera != null) {
mCamera.stopPreview();
}
}
private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h;
if (displayOrientation == 90 || displayOrientation == 270) {
targetRatio = (double) h / w;
}
if (sizes == null) return null;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Camera.Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
Log.d(TAG, "optimal preview size: w: " + optimalSize.width + " h: " + optimalSize.height);
return optimalSize;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if(mCamera != null) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
requestLayout();
//mCamera.setDisplayOrientation(90);
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
public byte[] getFramePicture(byte[] data, Camera camera) {
Camera.Parameters parameters = camera.getParameters();
int format = parameters.getPreviewFormat();
//YUV formats require conversion
if (format == ImageFormat.NV21 || format == ImageFormat.YUY2 || format == ImageFormat.NV16) {
int w = parameters.getPreviewSize().width;
int h = parameters.getPreviewSize().height;
// Get the YuV image
YuvImage yuvImage = new YuvImage(data, format, w, h, null);
// Convert YuV to Jpeg
Rect rect = new Rect(0, 0, w, h);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
yuvImage.compressToJpeg(rect, 80, outputStream);
return outputStream.toByteArray();
}
return data;
}
public void setOneShotPreviewCallback(Camera.PreviewCallback callback) {
if(mCamera != null) {
mCamera.setOneShotPreviewCallback(callback);
}
}
}
class TapGestureDetector extends GestureDetector.SimpleOnGestureListener{
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return true;
}
}
class CustomSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
private final String TAG = "CustomSurfaceView";
CustomSurfaceView(Context context){
super(context);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
|
package io.cloudsoft.tosca.a4c.brooklyn.spec;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.apache.brooklyn.api.entity.Entity;
import org.apache.brooklyn.api.entity.EntitySpec;
import org.apache.brooklyn.api.mgmt.ManagementContext;
import org.apache.brooklyn.api.typereg.RegisteredType;
import org.apache.brooklyn.entity.software.base.SameServerEntity;
import org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess;
import io.cloudsoft.tosca.a4c.brooklyn.Alien4CloudApplication;
import io.cloudsoft.tosca.a4c.brooklyn.Alien4CloudFacade;
import io.cloudsoft.tosca.a4c.brooklyn.ToscaFacade;
@Component
public class Alien4CloudEntitySpecFactory implements EntitySpecFactory<Alien4CloudApplication> {
private static final Logger LOG = LoggerFactory.getLogger(Alien4CloudEntitySpecFactory.class);
private final ManagementContext mgmt;
private ToscaFacade<Alien4CloudApplication> alien4CloudFacade;
@Inject
public Alien4CloudEntitySpecFactory(ManagementContext mgmt, ToscaFacade<Alien4CloudApplication> alien4CloudFacade) {
this.mgmt = mgmt;
this.alien4CloudFacade = alien4CloudFacade;
}
@Override
public EntitySpec<?> create(String nodeId, Alien4CloudApplication toscaApplication) {
// TODO: decide on how to behave if indexedNodeTemplate.getElementId is abstract.
// Currently we create a VanillaSoftwareProcess.
EntitySpec<?> spec;
String type = toscaApplication.getNodeTemplate(nodeId).getType();
RegisteredType registeredType = mgmt.getTypeRegistry().get(type);
if(registeredType != null) {
spec = mgmt.getTypeRegistry().create(registeredType, null, null);
} else if (isComputeType(nodeId, toscaApplication)) {
spec = EntitySpec.create(SameServerEntity.class);
} else {
try {
LOG.info("Found Brooklyn entity that match node type: " + type);
spec = EntitySpec.create((Class<? extends Entity>) Class.forName(type));
} catch (ClassNotFoundException e) {
LOG.info("Cannot find any Brooklyn catalog item nor Brooklyn entities that match node type: " +
type + ". Defaulting to a VanillaSoftwareProcess");
spec = EntitySpec.create(VanillaSoftwareProcess.class);
}
}
return spec;
}
private boolean isComputeType(String nodeId, Alien4CloudApplication toscaApplication) {
return alien4CloudFacade.isDerivedFrom(nodeId, toscaApplication, Alien4CloudFacade.COMPUTE_TYPE);
}
}
|
package org.openhealthtools.mdht.uml.cda.ui.builder;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.eclipse.ant.core.AntCorePlugin;
import org.eclipse.ant.core.IAntClasspathEntry;
import org.eclipse.ant.internal.core.AntClasspathEntry;
import org.eclipse.ant.internal.launching.launchConfigurations.AntHomeClasspathEntry;
import org.eclipse.ant.internal.launching.launchConfigurations.ContributedClasspathEntriesEntry;
import org.eclipse.ant.launching.IAntLaunchConstants;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.emf.codegen.ecore.generator.Generator;
import org.eclipse.emf.codegen.ecore.genmodel.GenAnnotation;
import org.eclipse.emf.codegen.ecore.genmodel.GenJDKLevel;
import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
import org.eclipse.emf.codegen.ecore.genmodel.GenModelPackage;
import org.eclipse.emf.codegen.ecore.genmodel.GenRuntimeVersion;
import org.eclipse.emf.codegen.ecore.genmodel.generator.GenBaseGeneratorAdapter;
import org.eclipse.emf.common.util.BasicMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.uml2.codegen.ecore.genmodel.GenModelFactory;
import org.eclipse.uml2.codegen.ecore.genmodel.GenPackage;
import org.eclipse.uml2.uml.UMLPackage;
import org.eclipse.uml2.uml.ecore.importer.UMLImporter;
import org.openhealthtools.mdht.uml.cda.ui.internal.Activator;
import org.openhealthtools.mdht.uml.cda.ui.util.CDAUIUtil;
import org.osgi.framework.Bundle;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class CDABuilder extends IncrementalProjectBuilder {
class CheckForModelChanged implements IResourceDeltaVisitor {
public boolean hasModelChanged = false;
public boolean visit(IResourceDelta delta) throws CoreException {
IResource resource = delta.getResource();
if (delta.getKind() == IResourceDelta.CHANGED && resource.getName().endsWith(".uml")) {
hasModelChanged = true;
}
return true;
}
}
public static final String BUILDER_ID = "org.openhealthtools.mdht.uml.cda.ui.org.openhealthtools.mdht.uml.cda.builder.id";
private static final String ANNOTATIONSOURCE = "http:
private static final String ECOREIMPORTER = "org.eclipse.uml2.uml.ecore.importer";
private static final String VALIDATEPREFIX = "validate";
private static final String TEMPLATESDIR = "/org.openhealthtools.mdht.uml.cda/templates";
private static final String CDABASE = "org.openhealthtools.mdht.uml.cda";
private static boolean checkBuildStatus(IProject modelProject, IProject project) {
long modelModification = IResource.NULL_STAMP;
long lastGenerated = IResource.NULL_STAMP;
try {
for (IResource umlResources : modelProject.getFolder(new Path("model")).members()) {
if (umlResources.getName().endsWith(".uml")) {
if (umlResources.getLocalTimeStamp() > modelModification) {
modelModification = umlResources.getLocalTimeStamp();
}
}
}
if (project.getName().endsWith(".doc")) {
for (IResource pdfResources : project.getFolder(new Path("dita/classes/generated")).members()) {
if (pdfResources.getName().endsWith(".dita")) {
if (pdfResources.getLocalTimeStamp() > lastGenerated) {
lastGenerated = pdfResources.getLocalTimeStamp();
}
}
}
} else {
for (IResource ecoreUMLResources : project.getFolder(new Path("model")).members()) {
if (ecoreUMLResources.getName().endsWith("_Ecore.uml")) {
if (ecoreUMLResources.getLocalTimeStamp() > lastGenerated) {
lastGenerated = ecoreUMLResources.getLocalTimeStamp();
}
}
}
}
} catch (CoreException e) {
}
return modelModification > lastGenerated;
}
public static void createGenModel(IProject project, IProgressMonitor monitor) {
EPackage.Registry.INSTANCE.put(GenModelPackage.eNS_URI, GenModelPackage.eINSTANCE);
ResourceSet resourceSet = new ResourceSetImpl();
URI umlEcoreModelURI = CDAUIUtil.getUMLEcoreModel(project);
org.eclipse.uml2.uml.Package pe = (org.eclipse.uml2.uml.Package) EcoreUtil.getObjectByType(
resourceSet.getResource(umlEcoreModelURI, true).getContents(), UMLPackage.eINSTANCE.getPackage());
String modelName = pe.getName();
IPath filePath = new Path(String.format("model/%s.genmodel", modelName));
IFile file = CDAUIUtil.getBundleRelativeFile(project, filePath);
IWorkspaceRoot myWorkspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
String genmodelPath = myWorkspaceRoot.getLocation().toOSString() + file.getFullPath().toOSString();
URI genmodelURI = URI.createFileURI(genmodelPath);
Resource genmodelResource = resourceSet.createResource(genmodelURI);
org.eclipse.uml2.codegen.ecore.genmodel.GenModel genmodel = org.eclipse.uml2.codegen.ecore.genmodel.GenModelFactory.eINSTANCE.createGenModel();
genmodel.setModelName(String.format("%s_Ecore", modelName));
genmodel.setModelDirectory(String.format("%s/src", project.getName()));
genmodel.setModelPluginClass(modelName.substring(0, 1).toUpperCase() + modelName.substring(1) + "Plugin");
genmodel.setModelPluginID(CDABASE + "." + modelName);
genmodel.setImporterID(ECOREIMPORTER);
genmodel.setInvariantPrefix(VALIDATEPREFIX);
genmodel.setCopyrightFields(false);
genmodel.setComplianceLevel(GenJDKLevel.JDK50_LITERAL);
genmodel.setRuntimeVersion(GenRuntimeVersion.EMF25);
genmodel.setTemplateDirectory(TEMPLATESDIR);
genmodel.setDynamicTemplates(true);
genmodel.getForeignModel().add(String.format("%s.uml", genmodel.getModelName()));
genmodel.setPluralizedGetters(true);
GenAnnotation ga = org.eclipse.emf.codegen.ecore.genmodel.GenModelFactory.eINSTANCE.createGenAnnotation();
ga.setSource(ANNOTATIONSOURCE);
ga.getDetails().put(org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__ECORE_TAGGED_VALUES, "PROCESS");
ga.getDetails().put(org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__UNION_PROPERTIES, "PROCESS");
ga.getDetails().put(org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__DUPLICATE_FEATURES, "PROCESS");
ga.getDetails().put(
org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__SUBSETTING_PROPERTIES, "PROCESS");
ga.getDetails().put(org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__COMMENTS, "PROCESS");
ga.getDetails().put(
org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__DUPLICATE_FEATURE_INHERITANCE, "PROCESS");
ga.getDetails().put(
org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__DUPLICATE_OPERATIONS, "PROCESS");
ga.getDetails().put(
org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__INVARIANT_CONSTRAINTS, "PROCESS");
ga.getDetails().put(
org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__REDEFINING_PROPERTIES, "PROCESS");
ga.getDetails().put(org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__ANNOTATION_DETAILS, "PROCESS");
ga.getDetails().put(
org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__DUPLICATE_OPERATION_INHERITANCE, "PROCESS");
ga.getDetails().put(
org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__REDEFINING_OPERATIONS, "PROCESS");
ga.getDetails().put(org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__DERIVED_FEATURES, "IGNORE");
ga.getDetails().put(org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__OPERATION_BODIES, "PROCESS");
ga.getDetails().put(org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__CAMEL_CASE_NAMES, "IGNORE");
ga.getDetails().put(org.eclipse.uml2.uml.util.UMLUtil.UML2EcoreConverter.OPTION__SUPER_CLASS_ORDER, "PROCESS");
genmodel.getGenAnnotations().add(ga);
for (org.eclipse.emf.codegen.ecore.genmodel.GenPackage genPackage : getGenModel(project).values()) {
genmodel.getUsedGenPackages().add(genPackage);
}
GenPackage genPackage = GenModelFactory.eINSTANCE.createGenPackage();
genPackage.setDisposableProviderFactory(true);
genPackage.setBasePackage(CDABASE);
genPackage.setOperationsPackage(String.format("org.openhealthtools.mdht.uml.cda.%s.operations", modelName));
EPackage value = org.eclipse.emf.ecore.EcoreFactory.eINSTANCE.createEPackage();
value.setName(modelName);
value.setNsPrefix(modelName);
value.setNsURI(String.format("http:
IPath epackageFilePath = new Path(String.format("model/%s.ecore", modelName));
IFile epackage = CDAUIUtil.getBundleRelativeFile(project, epackageFilePath);
String epackagePath = myWorkspaceRoot.getLocation().toOSString() + epackage.getFullPath().toOSString();
URI epackageURI = URI.createFileURI(epackagePath);
Resource ecoreResource = resourceSet.createResource(epackageURI);
ecoreResource.getContents().add(value);
try {
ecoreResource.save(null);
} catch (IOException e1) {
}
genPackage.setEcorePackage(value);
genmodel.getGenPackages().add(genPackage);
genmodelResource.getContents().add(genmodel);
try {
ecoreResource.save(null);
genmodelResource.save(null);
} catch (IOException e) {
}
}
private static String getFileNameFromMap(String ditaMapPath) {
String fileName = null;
try {
FileInputStream ditaMapStream;
ditaMapStream = new FileInputStream(ditaMapPath);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
factory.setFeature("http://xml.org/sax/features/namespaces", false);
factory.setFeature("http://xml.org/sax/features/validation", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
DocumentBuilder builder;
Document doc = null;
XPathExpression expr = null;
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource(ditaMapStream)); // zipFile.getInputStream(pluginEntry)));
XPathFactory xFactory = XPathFactory.newInstance();
XPath xpath = xFactory.newXPath();
expr = xpath.compile("//bookmap/booktitle/mainbooktitle");
Node result = (Node) expr.evaluate(doc, XPathConstants.NODE);
if (result != null) {
fileName = result.getTextContent();
} else {
expr = xpath.compile("/bookmap");
result = (Node) expr.evaluate(doc, XPathConstants.NODE);
if (result != null) {
fileName = result.getAttributes().getNamedItem("id").getTextContent();
}
}
// If there is any issue parsing - we use the project name
} catch (FileNotFoundException e) {
} catch (ParserConfigurationException e) {
} catch (SAXException e) {
} catch (IOException e) {
} catch (XPathExpressionException e) {
}
return fileName;
}
private static HashMap<org.eclipse.emf.codegen.ecore.genmodel.GenPackage, org.eclipse.emf.codegen.ecore.genmodel.GenPackage> getGenModel(
IProject modelProject) {
HashMap<org.eclipse.emf.codegen.ecore.genmodel.GenPackage, org.eclipse.emf.codegen.ecore.genmodel.GenPackage> genPackages = new HashMap<org.eclipse.emf.codegen.ecore.genmodel.GenPackage, org.eclipse.emf.codegen.ecore.genmodel.GenPackage>();
IWorkspace workspace = ResourcesPlugin.getWorkspace();
ResourceSet resourceSet = new ResourceSetImpl();
IWorkspaceRoot root = workspace.getRoot();
for (IProject project : root.getProjects()) {
if (!modelProject.getName().equals(project.getName())) {
URI genmodelFile = CDAUIUtil.getGeneratorModel(project);
if (genmodelFile != null) {
GenModel sourceGenModel = (GenModel) EcoreUtil.getObjectByType(
resourceSet.getResource(genmodelFile, true).getContents(),
GenModelPackage.eINSTANCE.getGenModel());
if (sourceGenModel != null) {
for (org.eclipse.emf.codegen.ecore.genmodel.GenPackage usedGenPackage : sourceGenModel.getUsedGenPackages()) {
genPackages.put(usedGenPackage, usedGenPackage);
}
for (org.eclipse.emf.codegen.ecore.genmodel.GenPackage usedGenPackage : sourceGenModel.getGenPackages()) {
genPackages.put(usedGenPackage, usedGenPackage);
}
}
}
}
}
return genPackages;
}
public static void runGenerate(boolean cleanBuild, IProject project, IProgressMonitor monitor) {
if (project.getName().endsWith(".doc")) {
if (cleanBuild) {
try {
runPublishDita(project, monitor);
project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
} catch (IOException e) {
} catch (CoreException e) {
} catch (URISyntaxException e) {
}
}
} else {
UMLImporter umlImporter = new UMLImporter();
try {
org.eclipse.emf.common.util.Monitor umlImportMonitor = BasicMonitor.toMonitor(monitor);
if (CDAUIUtil.getGeneratorModelFile(project) == null) {
createGenModel(project, monitor);
}
umlImporter.setGenModelProjectLocation(project.getFullPath());
umlImporter.defineOriginalGenModelPath(CDAUIUtil.getGeneratorModelFile(project));
umlImporter.computeEPackages(umlImportMonitor);
for (EPackage ePackage : umlImporter.getEPackages()) {
EcoreUtil.resolveAll(ePackage);
}
umlImporter.prepareGenModelAndEPackages(umlImportMonitor);
umlImporter.saveGenModelAndEPackages(umlImportMonitor);
org.eclipse.emf.codegen.ecore.genmodel.GenModel genmodel = umlImporter.getGenModel();
genmodel.setUpdateClasspath(false);
genmodel.setCanGenerate(true);
Generator generator = new Generator();
generator.setInput(umlImporter.getGenModel());
genmodel.setCanGenerate(true);
generator.generate(genmodel, GenBaseGeneratorAdapter.MODEL_PROJECT_TYPE, umlImportMonitor);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void runPublishDita(IProject project, IProgressMonitor monitor) throws IOException, CoreException,
URISyntaxException {
IFolder ditaFolder = project.getFolder("dita");
IFile ditaMapFile = CDAUIUtil.getProjectFile(project, CDAUIUtil.DITA_PATH, "book.ditamap");
if (ditaMapFile == null) {
return;
}
StringBuffer jvmArguments = new StringBuffer();
for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
if (arg.startsWith("-X")) {
jvmArguments.append(arg);
jvmArguments.append(" ");
}
}
jvmArguments.append("-Dfile.encoding=UTF-8 ");
String[] segments = ditaMapFile.getName().split("\\.");
String ditaMapFileRoot = segments[0];
// Assume pdf target ,developer-pdf
String antTargets = "standards-pdf,developer-pdf";
if (ditaMapFile.getName().endsWith("-web.ditamap")) {
antTargets = "standards-eclipsehelp";
}
Bundle bundle = Platform.getBundle("org.openhealthtools.mdht.uml.cda.dita");
Path path = new Path("META-INF/MANIFEST.MF");
URL fileURL = FileLocator.find(bundle, path, null);
Path ditadirPath = new Path("DITA-OT");
URL ditadirURL = FileLocator.find(bundle, ditadirPath, null);
ditadirURL = FileLocator.toFileURL(ditadirURL);
InputStream in = fileURL.openStream();
Manifest ditaPluginManifest = new Manifest(in);
Attributes attributes = ditaPluginManifest.getMainAttributes();
String ditaClassPath = attributes.getValue("Bundle-ClassPath");
List<String> classpath = new ArrayList<String>();
for (String classPath : ditaClassPath.split(",")) {
if (".".equals(classPath)) {
URL url = FileLocator.find(bundle, new Path(""), null);
url = FileLocator.toFileURL(url);
IRuntimeClasspathEntry pluginEntry = JavaRuntime.newRuntimeContainerClasspathEntry(
new Path(url.getPath()), IRuntimeClasspathEntry.USER_CLASSES);
classpath.add(pluginEntry.getMemento());
} else {
URL url = FileLocator.find(bundle, new Path(classPath), null);
url = FileLocator.toFileURL(url);
IRuntimeClasspathEntry toolsEntry = JavaRuntime.newArchiveRuntimeClasspathEntry(new Path(url.getPath()));
toolsEntry.setClasspathProperty(IRuntimeClasspathEntry.USER_CLASSES);
classpath.add(toolsEntry.getMemento());
}
}
ContributedClasspathEntriesEntry ccee = new ContributedClasspathEntriesEntry();
AntHomeClasspathEntry ace = new AntHomeClasspathEntry();
classpath.add(ace.getMemento());
classpath.add(ccee.getMemento());
ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType type = launchManager.getLaunchConfigurationType(IAntLaunchConstants.ID_ANT_LAUNCH_CONFIGURATION_TYPE);
URL ditaPublishBuildFileURL = fileURL = FileLocator.find(bundle, new Path("dita-publish.xml"), null);
ditaPublishBuildFileURL = FileLocator.toFileURL(ditaPublishBuildFileURL);
String name = launchManager.generateLaunchConfigurationName("Publish CDA");
ILaunchConfigurationWorkingCopy workingCopy = type.newInstance(null, name);
workingCopy.setAttribute("org.eclipse.ui.externaltools.ATTR_LOCATION", ditaPublishBuildFileURL.getPath());
IVMInstall jre = JavaRuntime.getDefaultVMInstall();
workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_JRE_CONTAINER_PATH, jre.getName());
workingCopy.setAttribute(
IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
"-Djavax.xml.transform.TransformerFactory=net.sf.saxon.TransformerFactoryImpl");
Map<String, String> antProperties = new HashMap<String, String>();
antProperties.put("dita.dir", ditadirURL.toURI().getRawPath());
antProperties.put("ditaMapFile", ditaMapFile.getLocation().toOSString());
antProperties.put("outputLocation", project.getLocation().toOSString());
antProperties.put("pdf.output", Activator.getDefault().getStateLocation().append("pdf").toOSString());
antProperties.put("ditaMapFileRoot", ditaMapFileRoot);
String fileName = getFileNameFromMap(ditaMapFile.getLocation().toOSString());
if (fileName == null) {
fileName = project.getName();
}
antProperties.put("fileName", fileName);
antProperties.put("args.debug", "no");
antProperties.put("ditaFilePath", ditaFolder.getLocation().toOSString());
antProperties.put("tempFilePath", Activator.getDefault().getStateLocation().append("temp").toOSString());
antProperties.put("docProject", project.getLocation().toOSString());
String pdfFileLocation = ditaMapFile.getName();
pdfFileLocation = pdfFileLocation.replaceFirst(".ditamap", ".pdf");
antProperties.put("pdflocation", pdfFileLocation);
workingCopy.setAttribute("process_factory_id", "org.eclipse.ant.ui.remoteAntProcessFactory");
workingCopy.setAttribute(
IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
"org.eclipse.ant.internal.ui.antsupport.InternalAntRunner");
workingCopy.setAttribute(
org.eclipse.core.externaltools.internal.IExternalToolConstants.ATTR_WORKING_DIRECTORY,
project.getLocation().toOSString());
workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, jvmArguments.toString());
workingCopy.setAttribute(org.eclipse.ant.launching.IAntLaunchConstants.ATTR_ANT_TARGETS, antTargets);
workingCopy.setAttribute(IAntLaunchConstants.ATTR_ANT_PROPERTIES, antProperties);
workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, classpath);
workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, false);
workingCopy.setAttribute(IDebugUIConstants.ATTR_CONSOLE_PROCESS, false);
workingCopy.setAttribute(
IJavaLaunchConfigurationConstants.ATTR_CLASSPATH_PROVIDER, "org.eclipse.ant.ui.AntClasspathProvider");
workingCopy.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, false);
workingCopy.setAttribute(DebugPlugin.ATTR_CONSOLE_ENCODING, "UTF-8");
workingCopy.migrate();
workingCopy.launch(ILaunchManager.RUN_MODE, monitor, false, true);
}
public static void runTransformation(IProject project, IProgressMonitor monitor) {
try {
String antFileName = null;
if (project.getName().endsWith(".doc")) {
antFileName = "dita-transform.xml";
} else {
antFileName = "transform.xml";
}
ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
String launchMemento = String.format("%s.%s", project.getName(), antFileName);
try {
ILaunchConfiguration oldLaunchConfiguration = launchManager.getLaunchConfiguration(launchMemento);
if (oldLaunchConfiguration != null) {
oldLaunchConfiguration.delete();
}
} catch (CoreException ce) {
// Ignore exception, keep going
}
ArrayList<IAntClasspathEntry> classpathEntries = new ArrayList<IAntClasspathEntry>();
IAntClasspathEntry[] additionalClassPathEntries = AntCorePlugin.getPlugin().getPreferences().getAdditionalClasspathEntries();
if (additionalClassPathEntries != null) {
for (IAntClasspathEntry antClasspathEntry : additionalClassPathEntries) {
classpathEntries.add(antClasspathEntry);
}
}
final String BIN = "bin";
for (IProject wsProject : project.getWorkspace().getRoot().getProjects()) {
if (wsProject.isOpen() && !wsProject.getName().startsWith(".")) {
IFolder binFolder = wsProject.getFolder(BIN);
if (binFolder.exists()) {
String binFolderString = binFolder.getLocation().toOSString();
// check to see if the entry exists
boolean needToAdd = true;
for (IAntClasspathEntry antClasspathEntry : classpathEntries) {
if (antClasspathEntry.getEntryURL().toString().endsWith(binFolderString)) {
needToAdd = false;
break;
}
}
if (needToAdd) {
classpathEntries.add(new AntClasspathEntry(binFolderString));
}
}
}
}
AntCorePlugin.getPlugin().getPreferences().setAdditionalClasspathEntries(
classpathEntries.toArray(new IAntClasspathEntry[classpathEntries.size()]));
ILaunchConfigurationType type = launchManager.getLaunchConfigurationType(IAntLaunchConstants.ID_ANT_LAUNCH_CONFIGURATION_TYPE);
IFile transformxml = project.getFile(antFileName);
String name = launchManager.generateLaunchConfigurationName(launchMemento);
ILaunchConfigurationWorkingCopy workingCopy = type.newInstance(null, name);
workingCopy.setAttribute(
"org.eclipse.ui.externaltools.ATTR_LOCATION", transformxml.getLocation().toOSString());
workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, project.getName());
workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, true);
workingCopy.setAttribute(IDebugUIConstants.ATTR_CONSOLE_PROCESS, false);
workingCopy.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, false);
ILaunch launch = workingCopy.launch(ILaunchManager.RUN_MODE, monitor);
boolean terminated = false;
while (!terminated) {
for (IProcess process : launch.getProcesses()) {
terminated = process.isTerminated();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
terminated = true;
}
}
} catch (CoreException e) {
e.printStackTrace();
}
}
@Override
@SuppressWarnings("rawtypes")
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
String modelProjectName = null;
if (getProject().getName().endsWith(".doc")) {
modelProjectName = getProject().getName().replace(".doc", ".model");
} else {
modelProjectName = getProject().getName() + ".model";
}
IProject modelProject = root.getProject(modelProjectName);
IProject[] projects = new IProject[] { modelProject };
IResourceDelta modelProjectDelta = getDelta(modelProject);
CheckForModelChanged cfmc = new CheckForModelChanged();
if (modelProjectDelta != null) {
modelProjectDelta.accept(cfmc);
}
if (cfmc.hasModelChanged || checkBuildStatus(modelProject, getProject())) {
runTransformation(getProject(), monitor);
runGenerate(IncrementalProjectBuilder.FULL_BUILD == kind, getProject(), monitor);
}
return projects;
}
@Override
protected void clean(IProgressMonitor monitor) throws CoreException {
runTransformation(getProject(), monitor);
runGenerate(true, getProject(), monitor);
}
}
|
package com.io7m.jcanephora.tests.contracts;
import com.io7m.jequality.AlmostEqualDouble;
import com.io7m.jranges.RangeCheckException;
import com.io7m.jtensors.core.unparameterized.matrices.Matrix4x4D;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Projection matrix contract.
*/
// CHECKSTYLE_JAVADOC:OFF
public abstract class JCGLProjectionMatricesContract
{
private static final Logger LOG;
private static final AlmostEqualDouble.ContextRelative ALMOST_EQUAL_LARGE;
static {
LOG = LoggerFactory.getLogger(JCGLProjectionMatricesContract.class);
ALMOST_EQUAL_LARGE = new AlmostEqualDouble.ContextRelative();
ALMOST_EQUAL_LARGE.setMaxAbsoluteDifference(0.000001);
ALMOST_EQUAL_LARGE.setMaxRelativeDifference(0.000001);
}
public static void checkAlmostEquals(
final double x,
final double y)
{
if (!AlmostEqualDouble.almostEqual(ALMOST_EQUAL_LARGE, x, y)) {
throw new AssertionError(
String.format(
"Expected: <%f> Received: <%f>",
Double.valueOf(x),
Double.valueOf(y)));
}
}
protected abstract Matrix4x4D frustumProjectionRH(
final double x_min,
final double x_max,
final double y_min,
final double y_max,
final double z_near,
final double z_far);
protected abstract Matrix4x4D orthographicProjectionRH(
final double x_min,
final double x_max,
final double y_min,
final double y_max,
final double z_near,
final double z_far);
protected abstract Matrix4x4D perspectiveProjectionRH(
final double z_near,
final double z_far,
final double aspect,
final double horizontal_fov);
@Test(expected = RangeCheckException.class)
public final void testFrustumFarLessThanNear()
{
this.frustumProjectionRH(-1.0, 1.0, -1.0, 1.0, 1.0, -1.0);
}
@Test(expected = RangeCheckException.class)
public final void testFrustumNearFarSame()
{
this.frustumProjectionRH(-1.0, 1.0, -1.0, 1.0, 1.0, 1.0);
}
@Test(expected = RangeCheckException.class)
public final void testFrustumNearNegative()
{
this.frustumProjectionRH(-1.0, 1.0, -1.0, 1.0, -0.001, 100.0);
}
@Test
public final void testFrustumSimple()
{
final Matrix4x4D m =
this.frustumProjectionRH(
-1.0,
1.0,
-1.0,
1.0,
5.0,
100.0);
System.out.println(m);
checkAlmostEquals(5.0, m.rowColumn(0, 0));
checkAlmostEquals(0.0, m.rowColumn(0, 1));
checkAlmostEquals(0.0, m.rowColumn(0, 2));
checkAlmostEquals(0.0, m.rowColumn(0, 3));
checkAlmostEquals(0.0, m.rowColumn(1, 0));
checkAlmostEquals(5.0, m.rowColumn(1, 1));
checkAlmostEquals(0.0, m.rowColumn(1, 2));
checkAlmostEquals(0.0, m.rowColumn(1, 3));
checkAlmostEquals(0.0, m.rowColumn(2, 0));
checkAlmostEquals(0.0, m.rowColumn(2, 1));
checkAlmostEquals(-1.105263113975525, m.rowColumn(2, 2));
checkAlmostEquals(-10.526315689086914, m.rowColumn(2, 3));
checkAlmostEquals(0.0, m.rowColumn(3, 0));
checkAlmostEquals(0.0, m.rowColumn(3, 1));
checkAlmostEquals(-1.0, m.rowColumn(3, 2));
checkAlmostEquals(0.0, m.rowColumn(3, 3));
}
@Test
public final void testOrthographic()
{
final Matrix4x4D m =
this.orthographicProjectionRH(
0.0,
10.0,
0.0,
10.0,
1.0,
10.0);
checkAlmostEquals(0.2, m.rowColumn(0, 0));
checkAlmostEquals(0.0, m.rowColumn(0, 1));
checkAlmostEquals(0.0, m.rowColumn(0, 2));
checkAlmostEquals(-1.0, m.rowColumn(0, 3));
checkAlmostEquals(0.0, m.rowColumn(1, 0));
checkAlmostEquals(0.2, m.rowColumn(1, 1));
checkAlmostEquals(0.0, m.rowColumn(1, 2));
checkAlmostEquals(-1.0, m.rowColumn(1, 3));
checkAlmostEquals(0.0, m.rowColumn(2, 0));
checkAlmostEquals(0.0, m.rowColumn(2, 1));
checkAlmostEquals(-0.22222222, m.rowColumn(2, 2));
checkAlmostEquals(-1.2222222, m.rowColumn(2, 3));
checkAlmostEquals(0.0, m.rowColumn(3, 0));
checkAlmostEquals(0.0, m.rowColumn(3, 1));
checkAlmostEquals(0.0, m.rowColumn(3, 2));
checkAlmostEquals(1.0, m.rowColumn(3, 3));
}
@Test
public final void testPerspective()
{
final Matrix4x4D m =
this.perspectiveProjectionRH(
1.0,
1000.0,
1.0,
Math.toRadians(90.0));
System.out.println(m);
checkAlmostEquals(1.0, m.rowColumn(0, 0));
checkAlmostEquals(0.0, m.rowColumn(0, 1));
checkAlmostEquals(0.0, m.rowColumn(0, 2));
checkAlmostEquals(0.0, m.rowColumn(0, 3));
checkAlmostEquals(0.0, m.rowColumn(1, 0));
checkAlmostEquals(1.0, m.rowColumn(1, 1));
checkAlmostEquals(0.0, m.rowColumn(1, 2));
checkAlmostEquals(0.0, m.rowColumn(1, 3));
checkAlmostEquals(0.0, m.rowColumn(2, 0));
checkAlmostEquals(0.0, m.rowColumn(2, 1));
checkAlmostEquals(-1.002002000808716, m.rowColumn(2, 2));
checkAlmostEquals(-2.002002000808716, m.rowColumn(2, 3));
checkAlmostEquals(0.0, m.rowColumn(3, 0));
checkAlmostEquals(0.0, m.rowColumn(3, 1));
checkAlmostEquals(-1.0, m.rowColumn(3, 2));
checkAlmostEquals(0.0, m.rowColumn(3, 3));
}
@Test
public final void testPerspectiveInfinite()
{
final Matrix4x4D m =
this.perspectiveProjectionRH(
1.0,
Double.POSITIVE_INFINITY,
1.3,
Math.PI / 4.0);
System.out.println(m);
checkAlmostEquals(2.414213657379150, m.rowColumn(0, 0));
checkAlmostEquals(0.0, m.rowColumn(0, 1));
checkAlmostEquals(0.0, m.rowColumn(0, 2));
checkAlmostEquals(0.0, m.rowColumn(0, 3));
checkAlmostEquals(0.0, m.rowColumn(1, 0));
checkAlmostEquals(3.138477563858032, m.rowColumn(1, 1));
checkAlmostEquals(0.0, m.rowColumn(1, 2));
checkAlmostEquals(0.0, m.rowColumn(1, 3));
checkAlmostEquals(0.0, m.rowColumn(2, 0));
checkAlmostEquals(0.0, m.rowColumn(2, 1));
checkAlmostEquals(-1.0, m.rowColumn(2, 2));
checkAlmostEquals(-2.0, m.rowColumn(2, 3));
checkAlmostEquals(0.0, m.rowColumn(3, 0));
checkAlmostEquals(0.0, m.rowColumn(3, 1));
checkAlmostEquals(-1.0, m.rowColumn(3, 2));
checkAlmostEquals(0.0, m.rowColumn(3, 3));
}
}
|
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.9-03/31/2009 04:14 PM(snajper)-fcs
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2009.04.30 at 06:20:20 PM CEST
package org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs30.rs;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs30.query.AdhocQueryResponse;
import org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs30.rim.SlotListType;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RegistryResponseType", propOrder = {
"responseSlotList",
"registryErrorList"
})
@XmlSeeAlso({
AdhocQueryResponse.class
})
public class RegistryResponseType {
@XmlElement(name = "ResponseSlotList")
protected SlotListType responseSlotList;
@XmlElement(name = "RegistryErrorList")
protected RegistryErrorList registryErrorList;
@XmlAttribute(required = true)
protected String status;
@XmlAttribute
@XmlSchemaType(name = "anyURI")
protected String requestId;
/**
* Gets the value of the responseSlotList property.
*
* @return
* possible object is
* {@link SlotListType }
*
*/
public SlotListType getResponseSlotList() {
return responseSlotList;
}
/**
* Sets the value of the responseSlotList property.
*
* @param value
* allowed object is
* {@link SlotListType }
*
*/
public void setResponseSlotList(SlotListType value) {
this.responseSlotList = value;
}
/**
* Gets the value of the registryErrorList property.
*
* @return
* possible object is
* {@link RegistryErrorList }
*
*/
public RegistryErrorList getRegistryErrorList() {
return registryErrorList;
}
/**
* Sets the value of the registryErrorList property.
*
* @param value
* allowed object is
* {@link RegistryErrorList }
*
*/
public void setRegistryErrorList(RegistryErrorList value) {
this.registryErrorList = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStatus(String value) {
this.status = value;
}
/**
* Gets the value of the requestId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRequestId() {
return requestId;
}
/**
* Sets the value of the requestId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRequestId(String value) {
this.requestId = value;
}
}
|
package org.xins.common.servlet.container;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.JFrame;
/**
* HTTP Server used to invoke the XINS Servlet.
*
* @version $Revision$ $Date$
* @author <a href="mailto:anthony.goubard@orange-ftgroup.com">Anthony Goubard</a>
*/
public class HTTPServletStarter {
/**
* The default port number.
*/
public static final int DEFAULT_PORT_NUMBER = 8080;
/**
* Creates a new <code>HTTPServletStarter</code> for the specified WAR
* file, on the default port, as a daemon thread.
*
* <p>A listener is started on the port immediately.
*
* @param warFile
* the WAR file of the application to deploy, cannot be
* <code>null</code>.
*
* @throws ServletException
* if the servlet cannot be initialized.
*
* @throws IOException
* if the servlet container cannot be started.
*/
public HTTPServletStarter(File warFile)
throws Exception {
this(warFile, DEFAULT_PORT_NUMBER, true);
}
/**
* Creates a new <code>HTTPServletStarter</code> for the specified WAR
* file, on the specified port, as a daemon thread.
*
* <p>A listener is started on the port immediately.
*
* @param warFile
* the WAR file of the application to deploy, cannot be
* <code>null</code>.
*
* @param port
* the port to run the web server on.
*
* @throws ServletException
* if the servlet cannot be initialized.
*
* @throws IOException
* if the servlet container cannot be started.
*/
public HTTPServletStarter(File warFile, int port)
throws Exception {
this(warFile, port, true);
}
/**
* Creates a new <code>HTTPServletStarter</code> for the specified WAR
* file, on the specified port, optionally as a daemon thread.
*
* <p>A listener is started on the port immediately.
*
* @param warFile
* The war file of the application to deploy, cannot be <code>null</code>.
*
* @param port
* The port of the web server, cannot be <code>null</code>.
*
* @param deamon
* <code>true</code> if the thread listening to connection should be a
* deamon thread, <code>false</code> otherwise.
*
* @throws ServletException
* if the servlet cannot be initialized.
*
* @throws IOException
* if the servlet container cannot be started.
*/
public HTTPServletStarter(File warFile, int port, boolean deamon)
throws Exception {
this(warFile, port, deamon, ServletClassLoader.USE_WAR_EXTERNAL_LIB);
}
/**
* Creates a new <code>HTTPServletStarter</code> for the specified servlet
* class, on the specified port, optionally as a daemon thread.
*
* <p>A listener is started on the port immediately.
*
* @param servletClassName
* The name of the servlet to load, cannot be <code>null</code>.
*
* @param port
* The port of the web server, cannot be <code>null</code>.
*
* @param deamon
* <code>true</code> if the thread listening to connection should be a
* deamon thread, <code>false</code> otherwise.
*
* @param loaderMode
* the way the ClassLoader should locate and load the classes.
* See {@link ServletClassLoader].
*
* @throws ServletException
* if the servlet cannot be initialized.
*
* @throws IOException
* if the servlet container cannot be started.
*
* @since XINS 2.1.
*/
public HTTPServletStarter(File warFile, int port, boolean deamon, int loaderMode)
throws Exception {
// Create the servlet
ClassLoader loader = ServletClassLoader.getServletClassLoader(warFile, loaderMode);
Class[] constClasses = {File.class, Integer.TYPE, Boolean.TYPE};
Object[] constArgs = {warFile, new Integer(port), deamon ? Boolean.TRUE : Boolean.FALSE};
try {
Class delegate = loader.loadClass("org.xins.common.servlet.container.HTTPServletHandler");
Constructor constructor = delegate.getConstructor(constClasses);
constructor.newInstance(constArgs);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Creates a new <code>HTTPServletStarter</code> for the specified servlet
* class, on the specified port, optionally as a daemon thread.
*
* <p>A listener is started on the port immediately.
*
* @param servletClassName
* The name of the servlet to load, cannot be <code>null</code>.
*
* @param port
* The port of the web server, cannot be <code>null</code>.
*
* @param deamon
* <code>true</code> if the thread listening to connection should be a
* deamon thread, <code>false</code> otherwise.
*
* @throws ServletException
* if the servlet cannot be initialized.
*
* @throws IOException
* if the servlet container cannot be started.
*/
public HTTPServletStarter(String servletClassName, int port, boolean deamon)
throws Exception {
// Create the servlet
Class[] constClasses = {String.class, Integer.TYPE, Boolean.TYPE};
Object[] constArgs = {servletClassName, new Integer(port), Boolean.valueOf(deamon)};
try {
Class delegate = getClass().getClassLoader().loadClass("org.xins.common.servlet.container.HTTPServletHandler");
Constructor constructor = delegate.getConstructor(constClasses);
constructor.newInstance(constArgs);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Starts the Servlet container for the specific API.
*
* @param args
* The command line arguments, the first argument should be the location
* of the WAR file or the name of the class of the servlet to load,
* the optional second argument is the port number.
* If no port number is specified, 8080 is used as default.
*/
public static void main(String[] args) {
CommandLineArguments cmdArgs = new CommandLineArguments(args);
if (cmdArgs.getPort() == -1) {
try {
ClassLoader loader = ServletClassLoader.getServletClassLoader(cmdArgs.getWARFile(), cmdArgs.getLoaderMode());
loader.loadClass("org.xins.common.spec.SpecGUI").newInstance();
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
if (cmdArgs.showGUI()) {
JFrame apiFrame = new JFrame();
new ConsoleGUI(apiFrame, cmdArgs);
apiFrame.setVisible(true);
}
try {
// Starts the server and wait for connections
new HTTPServletStarter(cmdArgs.getWARFile(), cmdArgs.getPort(), false, cmdArgs.getLoaderMode());
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
}
}
|
package org.dellroad.stuff.pobj;
import java.util.Set;
import javax.validation.ConstraintViolation;
/**
* Runtime exception thrown during {@link PersistentObject} operations.
*/
@SuppressWarnings("serial")
public class PersistentObjectValidationException extends PersistentObjectException {
private final Set<ConstraintViolation<?>> violations;
public PersistentObjectValidationException(Set<ConstraintViolation<?>> violations) {
super(PersistentObjectValidationException.generateMessage(violations));
this.violations = violations;
}
/**
* Get the set of constraint violations.
*/
public Set<ConstraintViolation<?>> getViolations() {
return this.violations;
}
private static String generateMessage(Set<ConstraintViolation<?>> violations) {
if (violations == null)
throw new IllegalArgumentException("null violations");
StringBuilder buf = new StringBuilder("object failed to validate with " + violations.size() + " violation(s): ");
boolean first = true;
for (ConstraintViolation<?> violation : violations) {
if (first)
first = false;
else
buf.append("; ");
buf.append("[" + violation.getPropertyPath() + "]: " + violation.getMessage());
}
return buf.toString();
}
}
|
package org.deegree.metadata.iso.parsing;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.apache.axiom.om.OMElement;
import org.deegree.commons.xml.stax.XMLStreamUtils;
import org.deegree.metadata.MetadataRecord;
import org.deegree.metadata.MetadataRecordFactory;
import org.junit.Test;
public class RecordPropertyParserTest {
private final String metadataEmptyDateFile = "metadataEmptyDate.xml";
@Test
public void testRecordPropertyParserWithEmptyDate()
throws IOException, XMLStreamException {
RecordPropertyParser recordPropertyParser = new RecordPropertyParser( createOmElement( metadataEmptyDateFile ) );
recordPropertyParser.parse();
}
private OMElement createOmElement( String inputFile )
throws IOException, XMLStreamException {
MetadataRecord record = MetadataRecordFactory.create( createXmlStream( inputFile ) );
OMElement omElement = record.getAsOMElement();
return omElement;
}
private XMLStreamReader createXmlStream( String inputFile )
throws IOException, XMLStreamException {
InputStream inputStream = RecordPropertyParserTest.class.getResourceAsStream( inputFile );
XMLStreamReader xmlStream = XMLInputFactory.newInstance().createXMLStreamReader( inputStream );
XMLStreamUtils.skipStartDocument( xmlStream );
XMLStreamUtils.skipToRequiredElement( xmlStream, new QName( "http:
return xmlStream;
}
}
|
package org.helioviewer.jhv.renderable.components;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import org.helioviewer.jhv.base.astronomy.Position;
import org.helioviewer.jhv.base.astronomy.Sun;
import org.helioviewer.jhv.base.math.Mat4d;
import org.helioviewer.jhv.base.math.Quatd;
import org.helioviewer.jhv.camera.GL3DCamera;
import org.helioviewer.jhv.camera.GL3DViewport;
import org.helioviewer.jhv.gui.UIGlobals;
import org.helioviewer.jhv.layers.Layers;
import org.helioviewer.jhv.opengl.GLHelper;
import org.helioviewer.jhv.opengl.GLInfo;
import org.helioviewer.jhv.renderable.components.RenderableGridOptionsPanel.GridChoiceType;
import org.helioviewer.jhv.renderable.gui.AbstractRenderable;
import com.jogamp.common.nio.Buffers;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.util.awt.TextRenderer;
public class RenderableGrid extends AbstractRenderable {
private static final int SUBDIVISIONS = 120;
private float lonstepDegrees = 15f;
private float latstepDegrees = 20f;
private final Color firstColor = Color.RED;
private final Color secondColor = Color.GREEN;
private boolean showAxes = true;
private boolean showLabels = true;
private Font font;
private TextRenderer textRenderer;
// the height of the text in solar radii
private static final float textScale = 0.08f;
private final Component optionsPanel;
private static final String name = "Grid";
public RenderableGrid() {
optionsPanel = new RenderableGridOptionsPanel(this);
this.setVisible(true);
makeLatLabels();
makeLonLabels();
}
private float oldFontSize = -1;
private int positionBufferID;
private int colorBufferID;
private GridChoiceType gridChoice = GridChoiceType.OBSERVER;
@Override
public void render(GL2 gl, GL3DViewport vp) {
GL3DCamera activeCamera = vp.getCamera();
renderBlackCircle(gl, activeCamera.getRotation().transpose().m);
if (!isVisible[vp.getIndex()])
return;
if (showAxes)
drawAxes(gl);
// cameraWidth ever changes so slightly with distance to Sun; 4x pix/Rsun
int pixelsPerSolarRadius = (int) (2 * textScale * vp.getHeight() / activeCamera.getCameraWidth());
float fontSize = Math.max(10, Math.min(288, pixelsPerSolarRadius));
if (showLabels && (textRenderer == null || fontSize != oldFontSize)) {
oldFontSize = fontSize;
font = UIGlobals.UIFontRoboto.deriveFont(fontSize);
if (textRenderer != null) {
textRenderer.dispose();
}
boolean antiAlias = GLInfo.pixelScale[1] == 1 ? false : true;
textRenderer = new TextRenderer(font, antiAlias, antiAlias, null, true);
textRenderer.setUseVertexArrays(true);
// textRenderer.setSmoothing(false);
textRenderer.setColor(Color.WHITE);
}
Mat4d cameraMatrix;
switch (gridChoice) {
case OBSERVER:
cameraMatrix = activeCamera.getLocalRotation().toMatrix();
break;
case HCI:
//TBD
cameraMatrix = Mat4d.identity();
break;
default:
cameraMatrix = Mat4d.identity();
break;
}
double[] matrix = cameraMatrix.transpose().m;
gl.glPushMatrix();
gl.glMultMatrixd(matrix, 0);
{
if (showLabels)
drawText(gl);
drawCircles(gl, cameraMatrix);
}
gl.glPopMatrix();
drawEarthCircles(gl);
}
private void renderBlackCircle(GL2 gl, double[] matrix) {
gl.glPushMatrix();
gl.glMultMatrixd(matrix, 0);
{
gl.glColor3f(0, 0, 0);
GLHelper.drawCircle(gl, 0, 0, 0.95, 25);
}
gl.glPopMatrix();
}
private void drawAxes(GL2 gl) {
GLHelper.lineWidth(gl, 1);
gl.glBegin(GL2.GL_LINES);
{
gl.glColor4f(0, 0, 1, 1);
gl.glVertex3f(0, -1.2f, 0);
gl.glVertex3f(0, -1, 0);
gl.glColor4f(1, 0, 0, 1);
gl.glVertex3f(0, 1.2f, 0);
gl.glVertex3f(0, 1, 0);
}
gl.glEnd();
}
private void drawEarthCircles(GL2 gl) {
gl.glColor4f(1, 1, 0, 1);
gl.glEnableClientState(GL2.GL_VERTEX_ARRAY);
gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, positionBufferID);
gl.glVertexPointer(2, GL2.GL_FLOAT, 0, 0);
{
Position.Latitudinal p = Sun.getEarth(Layers.getLastUpdatedTimestamp().getTime());
{
gl.glPushMatrix();
Quatd longitudeRotation = new Quatd(0, p.lon + Math.PI / 2);
longitudeRotation.conjugate();
gl.glMultMatrixd(longitudeRotation.toMatrix().m, 0);
gl.glDrawArrays(GL2.GL_LINE_LOOP, 0, SUBDIVISIONS);
gl.glPopMatrix();
gl.glPushMatrix();
Quatd latitudeRotation = new Quatd(p.lat + Math.PI / 2, p.lon);
latitudeRotation.conjugate();
gl.glMultMatrixd(latitudeRotation.toMatrix().m, 0);
gl.glRotatef((float) (-p.lat), 0, 0, 1);
gl.glDrawArrays(GL2.GL_LINE_LOOP, 0, SUBDIVISIONS);
gl.glPopMatrix();
}
}
gl.glDisableClientState(GL2.GL_VERTEX_ARRAY);
gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, 0);
}
private void drawCircles(GL2 gl, Mat4d cameraMatrix) {
GLHelper.lineWidth(gl, 0.25);
gl.glEnableClientState(GL2.GL_VERTEX_ARRAY);
gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, positionBufferID);
gl.glVertexPointer(2, GL2.GL_FLOAT, 0, 0);
{
gl.glEnableClientState(GL2.GL_COLOR_ARRAY);
gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, colorBufferID);
gl.glColorPointer(3, GL2.GL_FLOAT, 0, 0);
gl.glRotatef(90, 0, 1, 0);
gl.glPushMatrix();
{
float rotation = 0;
while (rotation <= 180) {
gl.glDrawArrays(GL2.GL_LINE_STRIP, SUBDIVISIONS / 4, SUBDIVISIONS / 2 + 1);
gl.glRotatef(lonstepDegrees, 0, 1, 0);
rotation += lonstepDegrees;
}
}
gl.glPopMatrix();
gl.glPushMatrix();
{
float rotation = 0;
rotation -= lonstepDegrees;
gl.glRotatef(-lonstepDegrees, 0, 1, 0);
while (rotation >= -180) {
gl.glDrawArrays(GL2.GL_LINE_STRIP, SUBDIVISIONS / 4, SUBDIVISIONS / 2 + 1);
gl.glRotatef(-lonstepDegrees, 0, 1, 0);
rotation -= lonstepDegrees;
}
}
gl.glPopMatrix();
gl.glPushMatrix();
{
float rotation = 0;
gl.glRotatef(90, 1, 0, 0);
gl.glDrawArrays(GL2.GL_LINE_LOOP, 0, SUBDIVISIONS);
while (rotation < 90) {
gl.glPushMatrix();
{
gl.glTranslatef(0, 0, (float) Math.sin(Math.PI / 180. * rotation));
float scale = (float) Math.cos(Math.PI / 180. * rotation);
gl.glScalef(scale, scale, scale);
gl.glDrawArrays(GL2.GL_LINE_LOOP, 0, SUBDIVISIONS);
}
gl.glPopMatrix();
rotation += latstepDegrees;
}
rotation = latstepDegrees;
while (rotation < 90) {
gl.glPushMatrix();
{
gl.glTranslatef(0, 0, -(float) Math.sin(Math.PI / 180. * rotation));
float scale = (float) Math.cos(Math.PI / 180. * rotation);
gl.glScalef(scale, scale, scale);
gl.glDrawArrays(GL2.GL_LINE_LOOP, 0, SUBDIVISIONS);
}
gl.glPopMatrix();
rotation += latstepDegrees;
}
gl.glDrawArrays(GL2.GL_LINE_LOOP, 0, SUBDIVISIONS);
}
gl.glPopMatrix();
gl.glDisableClientState(GL2.GL_COLOR_ARRAY);
}
gl.glDisableClientState(GL2.GL_VERTEX_ARRAY);
gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, 0);
}
private static String formatStrip(double v) {
String txt = String.format("%.1f", v);
if (txt.endsWith("0")) {
txt = txt.substring(0, txt.length() - 2);
}
return txt;
}
private static class GridLabel {
protected String txt;
protected float x;
protected float y;
protected float theta;
protected GridLabel(String _txt, float _x, float _y, float _theta) {
txt = _txt;
x = _x;
y = _y;
theta = _theta;
}
}
private ArrayList<GridLabel> latLabels = new ArrayList<GridLabel>();
private ArrayList<GridLabel> lonLabels = new ArrayList<GridLabel>();
private void makeLatLabels() {
double size = Sun.Radius * 1.1;
// adjust for font size in horizontal and vertical direction (centering the text approximately)
float horizontalAdjustment = textScale / 2f;
float verticalAdjustment = textScale / 3f;
latLabels.clear();
for (double phi = 0; phi <= 90; phi += latstepDegrees) {
double angle = (90 - phi) * Math.PI / 180.;
String txt = formatStrip(phi);
latLabels.add(new GridLabel(txt, (float) (Math.sin(angle) * size), (float) (Math.cos(angle) * size - verticalAdjustment), 0));
if (phi != 90) {
latLabels.add(new GridLabel(txt, (float) (-Math.sin(angle) * size - horizontalAdjustment), (float) (Math.cos(angle) * size - verticalAdjustment), 0));
}
}
for (double phi = -latstepDegrees; phi >= -90; phi -= latstepDegrees) {
double angle = (90 - phi) * Math.PI / 180.;
String txt = formatStrip(phi);
latLabels.add(new GridLabel(txt, (float) (Math.sin(angle) * size), (float) (Math.cos(angle) * size - verticalAdjustment), 0));
if (phi != -90) {
latLabels.add(new GridLabel(txt, (float) (-Math.sin(angle) * size - horizontalAdjustment), (float) (Math.cos(angle) * size - verticalAdjustment), 0));
}
}
}
private void makeLonLabels() {
double size = Sun.Radius * 1.05;
lonLabels.clear();
for (double theta = 0; theta <= 180.; theta += lonstepDegrees) {
double angle = (90 - theta) * Math.PI / 180.;
String txt = formatStrip(theta);
lonLabels.add(new GridLabel(txt, (float) (Math.cos(angle) * size), (float) (Math.sin(angle) * size), (float) theta));
}
for (double theta = -lonstepDegrees; theta > -180.; theta -= lonstepDegrees) {
double angle = (90 - theta) * Math.PI / 180.;
String txt = formatStrip(theta);
lonLabels.add(new GridLabel(txt, (float) (Math.cos(angle) * size), (float) (Math.sin(angle) * size), (float) theta));
}
}
private void drawText(GL2 gl) {
// the scale factor has to be divided by the current font size
float textScaleFactor = textScale / font.getSize();
textRenderer.begin3DRendering();
for (int i = 0; i < latLabels.size(); ++i) {
GridLabel label = latLabels.get(i);
textRenderer.draw3D(label.txt, label.x, label.y, 0, textScaleFactor);
}
textRenderer.end3DRendering();
for (int i = 0; i < lonLabels.size(); ++i) {
gl.glPushMatrix();
{
GridLabel label = lonLabels.get(i);
gl.glTranslatef(label.x, 0, label.y);
gl.glRotatef(label.theta, 0, 1, 0);
textRenderer.begin3DRendering();
textRenderer.draw3D(label.txt, 0, 0, 0, textScaleFactor);
textRenderer.end3DRendering();
}
gl.glPopMatrix();
}
}
@Override
public void init(GL2 gl) {
FloatBuffer positionBuffer = FloatBuffer.allocate((SUBDIVISIONS + 1) * 2);
FloatBuffer colorBuffer = FloatBuffer.allocate((SUBDIVISIONS + 1) * 3);
for (int i = 0; i <= SUBDIVISIONS; i++) {
positionBuffer.put((float) Math.cos(2 * Math.PI * i / SUBDIVISIONS));
positionBuffer.put((float) Math.sin(2 * Math.PI * i / SUBDIVISIONS));
if (i % 2 == 0) {
colorBuffer.put(firstColor.getRed() / 255f);
colorBuffer.put(firstColor.getGreen() / 255f);
colorBuffer.put(firstColor.getBlue() / 255f);
} else {
colorBuffer.put(secondColor.getRed() / 255f);
colorBuffer.put(secondColor.getGreen() / 255f);
colorBuffer.put(secondColor.getBlue() / 255f);
}
}
positionBuffer.flip();
colorBuffer.flip();
int positionBufferSize = positionBuffer.capacity();
int colorBufferSize = colorBuffer.capacity();
positionBufferID = generate(gl);
colorBufferID = generate(gl);
gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, positionBufferID);
gl.glBufferData(GL2.GL_ARRAY_BUFFER, positionBufferSize * Buffers.SIZEOF_FLOAT, positionBuffer, GL2.GL_STATIC_DRAW);
gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, colorBufferID);
gl.glBufferData(GL2.GL_ARRAY_BUFFER, colorBufferSize * Buffers.SIZEOF_FLOAT, colorBuffer, GL2.GL_STATIC_DRAW);
}
private int generate(GL2 gl) {
int[] tmpId = new int[1];
gl.glGenBuffers(1, tmpId, 0);
return tmpId[0];
}
@Override
public void remove(GL2 gl) {
dispose(gl);
}
@Override
public Component getOptionsPanel() {
return optionsPanel;
}
@Override
public String getName() {
return name;
}
public double getLonstepDegrees() {
return lonstepDegrees;
}
public void setLonstepDegrees(double lonstepDegrees) {
this.lonstepDegrees = (float) lonstepDegrees;
makeLonLabels();
}
public double getLatstepDegrees() {
return latstepDegrees;
}
public void setLatstepDegrees(double latstepDegrees) {
this.latstepDegrees = (float) latstepDegrees;
makeLatLabels();
}
public void showLabels(boolean show) {
showLabels = show;
}
public void showAxes(boolean show) {
showAxes = show;
}
@Override
public String getTimeString() {
return null;
}
@Override
public boolean isDeletable() {
return false;
}
@Override
public void dispose(GL2 gl) {
if (textRenderer != null) {
textRenderer.dispose();
textRenderer = null;
}
gl.glDeleteBuffers(1, new int[] { positionBufferID }, 0);
gl.glDeleteBuffers(1, new int[] { colorBufferID }, 0);
oldFontSize = -1;
}
@Override
public void renderMiniview(GL2 gl, GL3DViewport vp) {
}
public void setCoordinates(GridChoiceType gridChoice) {
this.gridChoice = gridChoice;
}
}
|
package org.estatio.module.capex.dom.invoice.approval.triggers;
import java.util.List;
import javax.annotation.Nullable;
import javax.inject.Inject;
import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.ActionLayout;
import org.apache.isis.applib.annotation.Mixin;
import org.apache.isis.applib.annotation.SemanticsOf;
import org.apache.isis.applib.services.title.TitleService;
import org.estatio.module.capex.dom.invoice.IncomingInvoice;
import org.estatio.module.capex.dom.invoice.approval.IncomingInvoiceApprovalStateTransition;
import org.estatio.module.capex.dom.invoice.approval.IncomingInvoiceApprovalStateTransitionType;
import org.estatio.module.capex.dom.payment.PaymentBatch;
import org.estatio.module.capex.dom.payment.PaymentLine;
import org.estatio.module.capex.dom.payment.PaymentLineRepository;
import org.estatio.module.capex.dom.payment.approval.PaymentBatchApprovalState;
import org.estatio.module.party.dom.Person;
/**
* This mixin cannot (easily) be inlined because it inherits functionality from its superclass, and in any case
* this follows a common pattern applicable for all domain objects that have an associated state transition machine.
*/
@Mixin(method = "act")
public class IncomingInvoice_reject extends IncomingInvoice_triggerAbstract {
private final IncomingInvoice incomingInvoice;
public IncomingInvoice_reject(IncomingInvoice incomingInvoice) {
super(incomingInvoice, IncomingInvoiceApprovalStateTransitionType.REJECT);
this.incomingInvoice = incomingInvoice;
}
public static class ActionDomainEvent
extends IncomingInvoice_triggerAbstract.ActionDomainEvent<IncomingInvoice_reject> {
}
@Action(
domainEvent = IncomingInvoice_next.ActionDomainEvent.class,
semantics = SemanticsOf.IDEMPOTENT
)
@ActionLayout(cssClassFa = "fa-thumbs-o-down", cssClass = "btn-warning")
public Object act(
final String role,
@Nullable final Person personToAssignNextTo,
final String reason) {
final List<PaymentLine> paymentLines =
paymentLineRepository.findByInvoice(incomingInvoice);
// because of the disableXxx guard, this should return either 0 or 1 lines.
for (PaymentLine paymentLine : paymentLines) {
final PaymentBatch paymentBatch = paymentLine.getBatch();
paymentBatch.removeLineFor(incomingInvoice);
}
final IncomingInvoiceApprovalStateTransition transition = trigger(personToAssignNextTo, reason, reason);
if (transition.getTask() != null)
transition.getTask().setToHighestPriority();
return objectToReturn();
}
protected Object objectToReturn() {
return getDomainObject();
}
public boolean hideAct() {
return cannotTransition();
}
public String disableAct() {
final List<PaymentLine> paymentLines =
paymentLineRepository.findByInvoice(incomingInvoice);
for (PaymentLine paymentLine : paymentLines) {
final PaymentBatch paymentBatch = paymentLine.getBatch();
final PaymentBatchApprovalState state = paymentBatch.getApprovalState();
if (state != PaymentBatchApprovalState.NEW && state != PaymentBatchApprovalState.DISCARDED) {
return String.format("Invoice is in batch %s", titleService.titleOf(paymentBatch));
}
}
return reasonGuardNotSatisified();
}
public String default0Act() {
return enumPartyRoleTypeName();
}
public Person default1Act() {
return defaultPersonToAssignNextTo();
}
public List<Person> choices1Act() {
return choicesPersonToAssignNextTo();
}
@Inject
PaymentLineRepository paymentLineRepository;
@Inject
TitleService titleService;
}
|
package io.quarkus.vertx.http.deployment.devmode.console;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.function.BiFunction;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
import org.yaml.snakeyaml.Yaml;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.quarkus.builder.Version;
import io.quarkus.devconsole.runtime.spi.FlashScopeUtil;
import io.quarkus.maven.dependency.GACTV;
import io.quarkus.qute.Engine;
import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateInstance;
import io.smallrye.common.classloader.ClassPathUtils;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpHeaders;
import io.vertx.ext.web.RoutingContext;
/**
* This is a Handler running in the Dev Vert.x instance (which is loaded by the Augmentation ClassLoader)
* and has access to build time stuff
*/
public class DevConsole implements Handler<RoutingContext> {
static final ThreadLocal<String> currentExtension = new ThreadLocal<>();
private static final Comparator<Map<String, Object>> EXTENSION_COMPARATOR = Comparator
.comparing(m -> ((String) m.get("name")));
final Engine engine;
final Map<String, Map<String, Object>> extensions = new HashMap<>();
final Map<String, Object> globalData = new HashMap<>();
final Config config = ConfigProvider.getConfig();
final String devRootAppend;
DevConsole(Engine engine, String httpRootPath, String frameworkRootPath) {
this.engine = engine;
// Both of these paths will end in slash
this.globalData.put("httpRootPath", httpRootPath);
this.globalData.put("frameworkRootPath", frameworkRootPath);
// This includes the dev segment, but does not include a trailing slash (for append)
this.devRootAppend = frameworkRootPath + "dev";
this.globalData.put("devRootAppend", devRootAppend);
this.globalData.put("quarkusVersion", Version.getVersion());
this.globalData.put("applicationName", config.getOptionalValue("quarkus.application.name", String.class).orElse(""));
this.globalData.put("applicationVersion",
config.getOptionalValue("quarkus.application.version", String.class).orElse(""));
}
private void initLazyState() {
if (extensions.isEmpty()) {
synchronized (extensions) {
if (extensions.isEmpty()) {
try {
final Yaml yaml = new Yaml();
ClassPathUtils.consumeAsPaths("/META-INF/quarkus-extension.yaml", p -> {
final String desc;
try (Scanner scanner = new Scanner(Files.newBufferedReader(p, StandardCharsets.UTF_8))) {
scanner.useDelimiter("\\A");
desc = scanner.hasNext() ? scanner.next() : null;
} catch (IOException e) {
throw new RuntimeException("Failed to read " + p, e);
}
if (desc == null) {
// should be an exception?
return;
}
final Map<String, Object> metadata = yaml.load(desc);
extensions.put(getExtensionNamespace(metadata), metadata);
});
this.globalData.put("configKeyMap", getConfigKeyMap());
} catch (IOException x) {
throw new RuntimeException(x);
}
}
}
}
}
@Override
public void handle(RoutingContext ctx) {
initLazyState();
// Redirect /q/dev to /q/dev/
if (ctx.normalizedPath().length() == devRootAppend.length()) {
ctx.response().setStatusCode(302);
ctx.response().headers().set(HttpHeaders.LOCATION, devRootAppend + "/");
ctx.response().end();
return;
}
String path = ctx.normalizedPath().substring(ctx.mountPoint().length() + 1);
if (path.isEmpty() || path.equals("/")) {
sendMainPage(ctx);
} else {
int nsIndex = path.indexOf("/");
if (nsIndex == -1) {
ctx.response().setStatusCode(404).end();
return;
}
String namespace = path.substring(0, nsIndex);
currentExtension.set(namespace);
Template devTemplate = engine.getTemplate(path);
if (devTemplate != null) {
String extName = getExtensionName(namespace);
ctx.response().setStatusCode(200).headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
TemplateInstance devTemplateInstance = devTemplate
.data("currentExtensionName", extName)
.data("flash", FlashScopeUtil.getFlash(ctx))
.data("currentRequest", ctx.request());
renderTemplate(ctx, devTemplateInstance);
} else {
ctx.next();
}
}
}
private Map<String, List<String>> getConfigKeyMap() {
Map<String, List<String>> ckm = new TreeMap<>();
Collection<Map<String, Object>> values = this.extensions.values();
for (Map<String, Object> extension : values) {
if (extension.containsKey("metadata")) {
Map<String, Object> metadata = (Map<String, Object>) extension.get("metadata");
if (metadata.containsKey("config")) {
List<String> configKeys = (List<String>) metadata.get("config");
String name = (String) extension.get("name");
ckm.put(name, configKeys);
}
}
}
return ckm;
}
private String getExtensionName(String namespace) {
Map<String, Object> map = extensions.get(namespace);
if (map == null)
return null;
return (String) map.get("name");
}
protected void renderTemplate(RoutingContext event, TemplateInstance template) {
// Add some global variables
for (Map.Entry<String, Object> global : globalData.entrySet()) {
template.data(global.getKey(), global.getValue());
}
template.renderAsync().handle(new BiFunction<String, Throwable, Object>() {
@Override
public Object apply(String s, Throwable throwable) {
if (throwable != null) {
event.fail(throwable);
} else {
event.response().end(s);
}
return null;
}
});
}
public void sendMainPage(RoutingContext event) {
Template devTemplate = engine.getTemplate("index");
List<Map<String, Object>> actionableExtensions = new ArrayList<>();
List<Map<String, Object>> nonActionableExtensions = new ArrayList<>();
for (Map<String, Object> loaded : this.extensions.values()) {
@SuppressWarnings("unchecked")
final Map<String, Object> metadata = (Map<String, Object>) loaded.get("metadata");
final String namespace = getExtensionNamespace(loaded);
currentExtension.set(namespace); // needed because the template of the extension is going to be read
Template simpleTemplate = engine.getTemplate(namespace + "/embedded.html");
boolean hasConsoleEntry = simpleTemplate != null;
boolean hasGuide = metadata.containsKey("guide");
boolean hasConfig = metadata.containsKey("config");
boolean isUnlisted = metadata.containsKey("unlisted")
&& (metadata.get("unlisted").equals(true) || metadata.get("unlisted").equals("true"));
loaded.put("hasConsoleEntry", hasConsoleEntry);
loaded.put("hasGuide", hasGuide);
if (!isUnlisted || hasConsoleEntry || hasGuide || hasConfig) {
if (hasConsoleEntry) {
Map<String, Object> data = new HashMap<>();
data.putAll(globalData);
data.put("urlbase", namespace);
String result = simpleTemplate.render(data);
loaded.put("_dev", result);
actionableExtensions.add(loaded);
} else {
nonActionableExtensions.add(loaded);
}
}
}
actionableExtensions.sort(EXTENSION_COMPARATOR);
nonActionableExtensions.sort(EXTENSION_COMPARATOR);
TemplateInstance instance = devTemplate.data("actionableExtensions", actionableExtensions)
.data("nonActionableExtensions", nonActionableExtensions).data("flash", FlashScopeUtil.getFlash(event));
renderTemplate(event, instance);
}
private static String getExtensionNamespace(Map<String, Object> metadata) {
final String groupId;
final String artifactId;
final String artifact = (String) metadata.get("artifact");
if (artifact == null) {
// trying quarkus 1.x format
groupId = (String) metadata.get("group-id");
artifactId = (String) metadata.get("artifact-id");
if (artifactId == null || groupId == null) {
throw new RuntimeException(
"Failed to locate 'artifact' or 'group-id' and 'artifact-id' among metadata keys " + metadata.keySet());
}
} else {
final GACTV coords = GACTV.fromString(artifact);
groupId = coords.getGroupId();
artifactId = coords.getArtifactId();
}
return groupId + "." + artifactId;
}
}
|
package org.ovirt.engine.ui.uicommonweb.models.hosts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.ovirt.engine.core.common.action.VdsOperationActionParameters.AuthenticationMethod;
import org.ovirt.engine.core.common.businessentities.ArchitectureType;
import org.ovirt.engine.core.common.businessentities.ExternalEntityBase;
import org.ovirt.engine.core.common.businessentities.FenceAgentOrder;
import org.ovirt.engine.core.common.businessentities.FenceStatusReturnValue;
import org.ovirt.engine.core.common.businessentities.Provider;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VdsProtocol;
import org.ovirt.engine.core.common.businessentities.VdsStatic;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.core.common.queries.GetNewVdsFenceStatusParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.ICommandTarget;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.ApplicationModeHelper;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.Model;
import org.ovirt.engine.ui.uicommonweb.models.SystemTreeItemModel;
import org.ovirt.engine.ui.uicommonweb.models.providers.HostNetworkProviderModel;
import org.ovirt.engine.ui.uicommonweb.validation.HostAddressValidation;
import org.ovirt.engine.ui.uicommonweb.validation.HostnameValidation;
import org.ovirt.engine.ui.uicommonweb.validation.IValidation;
import org.ovirt.engine.ui.uicommonweb.validation.IntegerValidation;
import org.ovirt.engine.ui.uicommonweb.validation.KeyValuePairValidation;
import org.ovirt.engine.ui.uicommonweb.validation.LengthValidation;
import org.ovirt.engine.ui.uicommonweb.validation.NotEmptyValidation;
import org.ovirt.engine.ui.uicommonweb.validation.SpecialAsciiI18NOrNoneValidation;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.Event;
import org.ovirt.engine.ui.uicompat.EventArgs;
import org.ovirt.engine.ui.uicompat.IEventListener;
import org.ovirt.engine.ui.uicompat.PropertyChangedEventArgs;
import org.ovirt.engine.ui.uicompat.UIConstants;
public abstract class HostModel extends Model
{
public static final int HostNameMaxLength = 255;
public static final String PmSecureKey = "secure"; //$NON-NLS-1$
public static final String PmPortKey = "port"; //$NON-NLS-1$
public static final String PmSlotKey = "slot"; //$NON-NLS-1$
public static final String BeginTestStage = "BeginTest"; //$NON-NLS-1$
public static final String EndTestStage = "EndTest"; //$NON-NLS-1$
public static final String RootUserName = "root"; //$NON-NLS-1$
private UICommand privateTestCommand;
UIConstants constants = ConstantsManager.getInstance().getConstants();
public UICommand getTestCommand()
{
return privateTestCommand;
}
private void setTestCommand(UICommand value)
{
privateTestCommand = value;
}
private UICommand privateUpdateHostsCommand;
public UICommand getUpdateHostsCommand()
{
return privateUpdateHostsCommand;
}
private void setUpdateHostsCommand(UICommand value)
{
privateUpdateHostsCommand = value;
}
public boolean getIsNew()
{
return getHostId() == null;
}
public boolean getIsProvisioning() { return getExternalDiscoveredHosts().getSelectedItem() != null; }
private Guid privateHostId;
public Guid getHostId()
{
return privateHostId;
}
public void setHostId(Guid value)
{
privateHostId = value;
}
private String privateOriginalName;
public String getOriginalName()
{
return privateOriginalName;
}
public void setOriginalName(String value)
{
privateOriginalName = value;
}
private EntityModel<String> privateName;
public EntityModel<String> getName()
{
return privateName;
}
private void setName(EntityModel<String> value)
{
privateName = value;
}
private EntityModel<String> privateUserName;
public EntityModel<String> getUserName()
{
return privateUserName;
}
private void setUserName(EntityModel<String> value)
{
privateUserName = value;
}
private EntityModel privatePkSection;
public EntityModel getPkSection()
{
return privatePkSection;
}
private void setPkSection(EntityModel value)
{
privatePkSection = value;
}
private EntityModel privateDiscoveredHostSection;
public EntityModel getDiscoveredHostSection() { return privateDiscoveredHostSection; }
private void setDiscoveredHostSection(EntityModel value)
{
privateDiscoveredHostSection = value;
}
private EntityModel privateProvisionedHostSection;
public EntityModel getProvisionedHostSection() { return privateProvisionedHostSection; }
private void setProvisionedHostSection(EntityModel value)
{
privateProvisionedHostSection = value;
}
private EntityModel privatePasswordSection;
public EntityModel getPasswordSection()
{
return privatePasswordSection;
}
private void setPasswordSection(EntityModel value)
{
privatePasswordSection = value;
}
private EntityModel<String> privateFetchSshFingerprint;
public EntityModel<String> getFetchSshFingerprint()
{
return privateFetchSshFingerprint;
}
private void setFetchSshFingerprint(EntityModel<String> value)
{
privateFetchSshFingerprint = value;
}
private EntityModel<Integer> privateAuthSshPort;
public EntityModel<Integer> getAuthSshPort()
{
return privateAuthSshPort;
}
private void setAuthSshPort(EntityModel<Integer> value)
{
privateAuthSshPort = value;
}
private EntityModel<String> privateUserPassword;
public EntityModel<String> getUserPassword()
{
return privateUserPassword;
}
private void setUserPassword(EntityModel<String> value)
{
privateUserPassword = value;
}
private EntityModel<String> privatePublicKey;
public EntityModel<String> getPublicKey()
{
return privatePublicKey;
}
private void setPublicKey(EntityModel<String> value)
{
privatePublicKey = value;
}
private EntityModel<String> privateProviderSearchFilterLabel;
public EntityModel<String> getProviderSearchFilterLabel()
{
return privateProviderSearchFilterLabel;
}
private void setProviderSearchFilterLabel(EntityModel<String> value)
{
privateProviderSearchFilterLabel = value;
}
private EntityModel<String> privateProviderSearchFilter;
public EntityModel<String> getProviderSearchFilter()
{
return privateProviderSearchFilter;
}
private void setProviderSearchFilter(EntityModel<String> value)
{
privateProviderSearchFilter = value;
}
private EntityModel<String> privateHost;
public EntityModel<String> getHost()
{
return privateHost;
}
private void setHost(EntityModel<String> value)
{
privateHost = value;
}
private EntityModel<String> privateManagementIp;
public EntityModel<String> getManagementIp()
{
return privateManagementIp;
}
private void setManagementIp(EntityModel<String> value)
{
privateManagementIp = value;
}
private ListModel<StoragePool> privateDataCenter;
public ListModel<StoragePool> getDataCenter()
{
return privateDataCenter;
}
private void setDataCenter(ListModel<StoragePool> value)
{
privateDataCenter = value;
}
private ListModel<VDSGroup> privateCluster;
public ListModel<VDSGroup> getCluster()
{
return privateCluster;
}
private void setCluster(ListModel<VDSGroup> value)
{
privateCluster = value;
}
private EntityModel<Integer> privatePort;
public EntityModel<Integer> getPort()
{
return privatePort;
}
private void setPort(EntityModel<Integer> value)
{
privatePort = value;
}
private AuthenticationMethod hostAuthenticationMethod;
public void setAuthenticationMethod(AuthenticationMethod value) {
hostAuthenticationMethod = value;
}
public AuthenticationMethod getAuthenticationMethod() {
return hostAuthenticationMethod;
}
private EntityModel<String> privateFetchResult;
public EntityModel<String> getFetchResult()
{
return privateFetchResult;
}
private void setFetchResult(EntityModel<String> value)
{
privateFetchResult = value;
}
private EntityModel<Boolean> privateOverrideIpTables;
public EntityModel<Boolean> getOverrideIpTables()
{
return privateOverrideIpTables;
}
private void setOverrideIpTables(EntityModel<Boolean> value)
{
privateOverrideIpTables = value;
}
private EntityModel<Boolean> privateProtocol;
public EntityModel<Boolean> getProtocol()
{
return privateProtocol;
}
private void setProtocol(EntityModel<Boolean> value)
{
privateProtocol = value;
}
private EntityModel<Boolean> privateIsPm;
public EntityModel<Boolean> getIsPm()
{
return privateIsPm;
}
private void setIsPm(EntityModel<Boolean> value)
{
privateIsPm = value;
}
private EntityModel<String> privatePmUserName;
public EntityModel<String> getPmUserName()
{
return privatePmUserName;
}
private void setPmUserName(EntityModel<String> value)
{
privatePmUserName = value;
}
private EntityModel<String> privatePmPassword;
public EntityModel<String> getPmPassword()
{
return privatePmPassword;
}
private void setPmPassword(EntityModel<String> value)
{
privatePmPassword = value;
}
private EntityModel<String> consoleAddress;
public void setConsoleAddress(EntityModel<String> consoleAddress) {
this.consoleAddress = consoleAddress;
}
public EntityModel<String> getConsoleAddress() {
return consoleAddress;
}
private EntityModel<Boolean> consoleAddressEnabled;
public EntityModel<Boolean> getConsoleAddressEnabled() {
return consoleAddressEnabled;
}
public void setConsoleAddressEnabled(EntityModel<Boolean> consoleAddressEnabled) {
this.consoleAddressEnabled = consoleAddressEnabled;
}
private ListModel<String> privatePmType;
public ListModel<String> getPmType()
{
return privatePmType;
}
private void setPmType(ListModel<String> value)
{
privatePmType = value;
}
private EntityModel<Boolean> privatePmSecure;
public EntityModel<Boolean> getPmSecure()
{
return privatePmSecure;
}
private void setPmSecure(EntityModel<Boolean> value)
{
privatePmSecure = value;
}
private EntityModel<String> privatePmPort;
public EntityModel<String> getPmPort()
{
return privatePmPort;
}
private void setPmPort(EntityModel<String> value)
{
privatePmPort = value;
}
private EntityModel<String> privatePmSlot;
public EntityModel<String> getPmSlot()
{
return privatePmSlot;
}
private void setPmSlot(EntityModel<String> value)
{
privatePmSlot = value;
}
private EntityModel<String> privatePmOptions;
public EntityModel<String> getPmOptions()
{
return privatePmOptions;
}
private void setPmOptions(EntityModel<String> value)
{
privatePmOptions = value;
}
private EntityModel<String> pmSecondaryIp;
public EntityModel<String> getPmSecondaryIp() {
return pmSecondaryIp;
}
private void setPmSecondaryIp(EntityModel<String> value) {
pmSecondaryIp = value;
}
private EntityModel<String> pmSecondaryPort;
public EntityModel<String> getPmSecondaryPort() {
return pmSecondaryPort;
}
private void setPmSecondaryPort(EntityModel<String> value) {
pmSecondaryPort = value;
}
private EntityModel<String> pmSecondaryUserName;
public EntityModel<String> getPmSecondaryUserName() {
return pmSecondaryUserName;
}
private void setPmSecondaryUserName(EntityModel<String> value) {
pmSecondaryUserName = value;
}
private EntityModel<String> pmSecondaryPassword;
public EntityModel<String> getPmSecondaryPassword() {
return pmSecondaryPassword;
}
private void setPmSecondaryPassword(EntityModel<String> value) {
pmSecondaryPassword = value;
}
private ListModel<String> pmSecondaryType;
public ListModel<String> getPmSecondaryType() {
return pmSecondaryType;
}
private void setPmSecondaryType(ListModel<String> value) {
pmSecondaryType = value;
}
private EntityModel<String> pmSecondaryOptions;
public EntityModel<String> getPmSecondaryOptions() {
return pmSecondaryOptions;
}
private void setPmSecondaryOptions(EntityModel<String> value) {
pmSecondaryOptions = value;
}
private EntityModel<Boolean> pmSecondarySecure;
public EntityModel<Boolean> getPmSecondarySecure() {
return pmSecondarySecure;
}
private void setPmSecondarySecure(EntityModel<Boolean> value) {
pmSecondarySecure = value;
}
private EntityModel<Boolean> pmKdumpDetection;
public EntityModel<Boolean> getPmKdumpDetection()
{
return pmKdumpDetection;
}
private void setPmKdumpDetection(EntityModel<Boolean> value)
{
pmKdumpDetection = value;
}
public HashMap<String, String> getPmSecondaryOptionsMap() {
// For secondary map determine (workarround) if it's was specified
// by checking secondary PM fields.
if (!isEntityModelEmpty(getPmSecondaryIp())
|| !isEntityModelEmpty(getPmSecondaryUserName())
|| !isEntityModelEmpty(getPmSecondaryPassword())) {
return getPmOptionsMapInternal(getPmSecondaryPort(), getPmSecondarySlot(), getPmSecondarySecure(), getPmSecondaryOptions());
}
return new HashMap<String, String>();
}
public void setPmSecondaryOptionsMap(Map<String, String> value) {
setPmOptionsMapInternal(value, getPmSecondaryPort(), getPmSecondarySlot(), getPmSecondarySecure(), getPmSecondaryOptions());
}
private EntityModel<String> pmSecondarySlot;
public EntityModel<String> getPmSecondarySlot() {
return pmSecondarySlot;
}
private void setPmSecondarySlot(EntityModel<String> value) {
pmSecondarySlot = value;
}
private EntityModel<Boolean> pmSecondaryConcurrent;
public EntityModel<Boolean> getPmSecondaryConcurrent() {
return pmSecondaryConcurrent;
}
private void setPmSecondaryConcurrent(EntityModel<Boolean> value) {
pmSecondaryConcurrent = value;
}
private ListModel<String> pmVariants;
public ListModel<String> getPmVariants() {
return pmVariants;
}
private void setPmVariants(ListModel<String> value) {
pmVariants = value;
}
private EntityModel<Boolean> disableAutomaticPowerManagement;
public EntityModel<Boolean> getDisableAutomaticPowerManagement() {
return disableAutomaticPowerManagement;
}
private void setDisableAutomaticPowerManagement(EntityModel<Boolean> value) {
disableAutomaticPowerManagement = value;
}
private boolean isGeneralTabValid;
public boolean getIsGeneralTabValid()
{
return isGeneralTabValid;
}
public void setIsGeneralTabValid(boolean value)
{
if (isGeneralTabValid != value)
{
isGeneralTabValid = value;
onPropertyChanged(new PropertyChangedEventArgs("IsGeneralTabValid")); //$NON-NLS-1$
}
}
private boolean isPowerManagementTabValid;
public boolean getIsPowerManagementTabValid()
{
return isPowerManagementTabValid;
}
public void setIsPowerManagementTabValid(boolean value)
{
if (isPowerManagementTabValid != value)
{
isPowerManagementTabValid = value;
onPropertyChanged(new PropertyChangedEventArgs("IsPowerManagementTabValid")); //$NON-NLS-1$
}
}
private boolean isPowerManagementTabSelected;
public boolean getIsPowerManagementTabSelected()
{
return isPowerManagementTabSelected;
}
public void setIsPowerManagementTabSelected(boolean value)
{
if (isPowerManagementTabSelected != value)
{
isPowerManagementTabSelected = value;
onPropertyChanged(new PropertyChangedEventArgs("IsPowerManagementTabSelected")); //$NON-NLS-1$
}
}
private boolean ciscoUcsPrimaryPmTypeSelected;
public boolean isCiscoUcsPrimaryPmTypeSelected() {
return ciscoUcsPrimaryPmTypeSelected;
}
public void setCiscoUcsPrimaryPmTypeSelected(boolean value) {
if (ciscoUcsPrimaryPmTypeSelected != value) {
ciscoUcsPrimaryPmTypeSelected = value;
onPropertyChanged(new PropertyChangedEventArgs("IsCiscoUcsPrimaryPmTypeSelected")); //$NON-NLS-1$
}
}
private boolean ciscoUcsSecondaryPmTypeSelected;
public boolean isCiscoUcsSecondaryPmTypeSelected() {
return ciscoUcsSecondaryPmTypeSelected;
}
public void setCiscoUcsSecondaryPmTypeSelected(boolean value) {
if (ciscoUcsSecondaryPmTypeSelected != value) {
ciscoUcsSecondaryPmTypeSelected = value;
onPropertyChanged(new PropertyChangedEventArgs("IsCiscoUcsSecondaryPmTypeSelected")); //$NON-NLS-1$
}
}
public HashMap<String, String> getPmOptionsMap() {
return getPmOptionsMapInternal(getPmPort(), getPmSlot(), getPmSecure(), getPmOptions());
}
public void setPmOptionsMap(Map<String, String> value) {
setPmOptionsMapInternal(value, getPmPort(), getPmSlot(), getPmSecure(), getPmOptions());
}
public String getPmProxyPreferences() {
// Return null if power management is not enabled.
if (!getIsPm().getEntity()) {
return null;
}
// Pack back proxy items to the comma delimited string.
StringBuilder builder = new StringBuilder();
if (getPmProxyPreferencesList().getItems() != null) {
List items = (List) getPmProxyPreferencesList().getItems();
for (Object item : items) {
builder.append(item);
if (items.indexOf(item) < items.size() - 1) {
builder.append(","); //$NON-NLS-1$
}
}
}
return builder.toString();
}
public void setPmProxyPreferences(String value) {
// Create list from the provided comma delimited string.
String[] array = value.split(","); //$NON-NLS-1$
List<String> list = new ArrayList<String>();
for (String item : array) {
list.add(item);
}
getPmProxyPreferencesList().setItems(list);
}
private ListModel<String> pmProxyPreferencesList;
public ListModel<String> getPmProxyPreferencesList() {
return pmProxyPreferencesList;
}
private void setPmProxyPreferencesList(ListModel<String> value) {
pmProxyPreferencesList = value;
}
private UICommand proxyUpCommand;
public UICommand getProxyUpCommand() {
return proxyUpCommand;
}
private void setProxyUpCommand(UICommand value) {
proxyUpCommand = value;
}
private UICommand proxyDownCommand;
public UICommand getProxyDownCommand() {
return proxyDownCommand;
}
private void setProxyDownCommand(UICommand value) {
proxyDownCommand = value;
}
private UICommand proxySSHFingerPrintCommand;
public UICommand getSSHFingerPrint() {
return proxySSHFingerPrintCommand;
}
public void setSSHFingerPrint(UICommand value) {
proxySSHFingerPrintCommand = value;
}
private Integer postponedSpmPriority;
public void setSpmPriorityValue(Integer value) {
if (spmInitialized) {
updateSpmPriority(value);
} else {
postponedSpmPriority = value;
}
}
public int getSpmPriorityValue() {
EntityModel<Integer> selectedItem = getSpmPriority().getSelectedItem();
if (selectedItem != null) {
return selectedItem.getEntity();
}
return 0;
}
private ListModel<EntityModel<Integer>> spmPriority;
public ListModel<EntityModel<Integer>> getSpmPriority() {
return spmPriority;
}
private void setSpmPriority(ListModel<EntityModel<Integer>> value) {
spmPriority = value;
}
private ListModel<VDS> privateExternalHostName;
public ListModel<VDS> getExternalHostName()
{
return privateExternalHostName;
}
protected void setExternalHostName(ListModel<VDS> value)
{
privateExternalHostName = value;
}
private ListModel<ExternalEntityBase> privateExternalDiscoveredHosts;
public ListModel<ExternalEntityBase> getExternalDiscoveredHosts() { return privateExternalDiscoveredHosts; }
protected void setExternalDiscoveredHosts(ListModel<ExternalEntityBase> value) { privateExternalDiscoveredHosts = value; }
private ListModel<ExternalEntityBase> privateExternalHostGroups;
public ListModel<ExternalEntityBase> getExternalHostGroups() { return privateExternalHostGroups; }
protected void setExternalHostGroups(ListModel<ExternalEntityBase> value) { privateExternalHostGroups = value; }
private ListModel<ExternalEntityBase> privateExternalComputeResource;
public ListModel<ExternalEntityBase> getExternalComputeResource() { return privateExternalComputeResource; }
protected void setExternalComputeResource(ListModel<ExternalEntityBase> value) { privateExternalComputeResource = value; }
private EntityModel<String> privateComment;
public EntityModel<String> getComment()
{
return privateComment;
}
protected void setComment(EntityModel<String> value)
{
privateComment = value;
}
private EntityModel<Boolean> externalHostProviderEnabled;
public EntityModel<Boolean> getExternalHostProviderEnabled() {
return externalHostProviderEnabled;
}
public void setExternalHostProviderEnabled(EntityModel<Boolean> externalHostProviderEnabled) {
this.externalHostProviderEnabled = externalHostProviderEnabled;
}
private ListModel<Provider> privateProviders;
public ListModel<Provider> getProviders()
{
return privateProviders;
}
protected void setProviders(ListModel<Provider> value)
{
privateProviders = value;
}
private HostNetworkProviderModel networkProviderModel;
public HostNetworkProviderModel getNetworkProviderModel() {
return networkProviderModel;
}
private void setNetworkProviderModel(HostNetworkProviderModel value) {
networkProviderModel = value;
}
private EntityModel<Boolean> isDiscorveredHosts;
public EntityModel<Boolean> getIsDiscorveredHosts()
{
return isDiscorveredHosts;
}
public void setDiscorveredHosts(EntityModel<Boolean> value)
{
isDiscorveredHosts = value;
}
public ListModel<Provider<org.ovirt.engine.core.common.businessentities.OpenstackNetworkProviderProperties>> getNetworkProviders() {
return getNetworkProviderModel().getNetworkProviders();
}
public EntityModel<String> getInterfaceMappings() {
return getNetworkProviderModel().getInterfaceMappings();
}
public HostModel()
{
setTestCommand(new UICommand("Test", new ICommandTarget() { //$NON-NLS-1$
@Override
public void executeCommand(UICommand command) {
test();
}
@Override
public void executeCommand(UICommand uiCommand, Object... parameters) {
test();
}
}));
setUpdateHostsCommand(new UICommand("", new ICommandTarget() { //$NON-NLS-1$
@Override
public void executeCommand(UICommand command) {
updateHosts();
}
@Override
public void executeCommand(UICommand uiCommand, Object... parameters) {
updateHosts();
}
}));
setProxyUpCommand(new UICommand("Up", new ICommandTarget() { //$NON-NLS-1$
@Override
public void executeCommand(UICommand command) {
proxyUp();
}
@Override
public void executeCommand(UICommand uiCommand, Object... parameters) {
proxyUp();
}
}));
setProxyDownCommand(new UICommand("Down", new ICommandTarget() { //$NON-NLS-1$
@Override
public void executeCommand(UICommand command) {
proxyDown();
}
@Override
public void executeCommand(UICommand uiCommand, Object... parameters) {
proxyDown();
}
}));
setSSHFingerPrint(new UICommand("fetch", new ICommandTarget() { //$NON-NLS-1$
@Override
public void executeCommand(UICommand command) {
fetchSSHFingerprint();
}
@Override
public void executeCommand(UICommand uiCommand, Object... parameters) {
fetchSSHFingerprint();
}
}));
setName(new EntityModel<String>());
setComment(new EntityModel<String>());
setHost(new EntityModel<String>());
setPkSection(new EntityModel());
setPasswordSection(new EntityModel());
setDiscoveredHostSection(new EntityModel());
setProvisionedHostSection(new EntityModel());
setAuthSshPort(new EntityModel<Integer>());
getAuthSshPort().setEntity(Integer.parseInt(constants.defaultHostSSHPort()));
setUserName(new EntityModel<String>());
getUserName().setEntity(RootUserName);
// TODO: remove setIsChangable when configured ssh username is enabled
getUserName().setIsChangable(false);
setFetchSshFingerprint(new EntityModel<String>());
getFetchSshFingerprint().setEntity(constants.empty());
setUserPassword(new EntityModel<String>());
getUserPassword().setEntity(constants.empty());
setPublicKey(new EntityModel<String>());
getPublicKey().setEntity(constants.empty());
setDataCenter(new ListModel<StoragePool>());
getDataCenter().getSelectedItemChangedEvent().addListener(this);
getDataCenter().setIsAvailable(ApplicationModeHelper.getUiMode() != ApplicationMode.GlusterOnly);
setCluster(new ListModel<VDSGroup>());
getCluster().getSelectedItemChangedEvent().addListener(this);
setPort(new EntityModel<Integer>());
setFetchResult(new EntityModel<String>());
setOverrideIpTables(new EntityModel<Boolean>());
getOverrideIpTables().setEntity(false);
setProtocol(new EntityModel());
getProtocol().setEntity(false);
IEventListener pmListener = new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender, EventArgs args) {
updatePmModels();
}
};
setExternalHostName(new ListModel<VDS>());
getExternalHostName().setIsAvailable(false);
setExternalHostProviderEnabled(new EntityModel<Boolean>());
getExternalHostProviderEnabled().setIsAvailable(false);
setProviders(new ListModel());
getProviders().setIsAvailable(false);
setProviderSearchFilter(new EntityModel<String>());
getProviderSearchFilter().setIsAvailable(false);
setProviderSearchFilterLabel(new EntityModel<String>());
getProviderSearchFilterLabel().setIsAvailable(false);
setExternalDiscoveredHosts(new ListModel());
setExternalHostGroups(new ListModel());
setExternalComputeResource(new ListModel());
getUpdateHostsCommand().setIsExecutionAllowed(false);
// Initialize primary PM fields.
setManagementIp(new EntityModel<String>());
setPmUserName(new EntityModel<String>());
setPmPassword(new EntityModel<String>());
setPmType(new ListModel<String>());
getPmType().getSelectedItemChangedEvent().addListener(pmListener);
setPmPort(new EntityModel<String>());
getPmPort().setIsAvailable(false);
setPmSlot(new EntityModel<String>());
getPmSlot().setIsAvailable(false);
setPmOptions(new EntityModel<String>());
setPmSecure(new EntityModel<Boolean>());
getPmSecure().setIsAvailable(false);
getPmSecure().setEntity(false);
// Initialize secondary PM fields.
setPmSecondaryIp(new EntityModel<String>());
setPmSecondaryUserName(new EntityModel<String>());
setPmSecondaryPassword(new EntityModel<String>());
setPmSecondaryType(new ListModel<String>());
getPmSecondaryType().getSelectedItemChangedEvent().addListener(pmListener);
setPmSecondaryPort(new EntityModel<String>());
getPmSecondaryPort().setIsAvailable(false);
setPmSecondarySlot(new EntityModel<String>());
getPmSecondarySlot().setIsAvailable(false);
setPmSecondaryOptions(new EntityModel<String>());
setPmSecondarySecure(new EntityModel<Boolean>());
getPmSecondarySecure().setIsAvailable(false);
getPmSecondarySecure().setEntity(false);
// Initialize other PM fields.
setPmSecondaryConcurrent(new EntityModel<Boolean>());
getPmSecondaryConcurrent().setEntity(false);
setDisableAutomaticPowerManagement(new EntityModel<Boolean>());
getDisableAutomaticPowerManagement().setEntity(false);
setPmKdumpDetection(new EntityModel<Boolean>());
getPmKdumpDetection().setEntity(true);
setPmVariants(new ListModel<String>());
List<String> pmVariants = new ArrayList<String>();
pmVariants.add(ConstantsManager.getInstance().getConstants().primaryPmVariant());
pmVariants.add(ConstantsManager.getInstance().getConstants().secondaryPmVariant());
getPmVariants().setItems(pmVariants);
getPmVariants().setSelectedItem(pmVariants.get(0));
setPmProxyPreferencesList(new ListModel<String>());
getPmProxyPreferencesList().getSelectedItemChangedEvent().addListener(new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender, EventArgs args) {
updatePmModels();
}
});
setConsoleAddress(new EntityModel<String>());
getConsoleAddress().setEntity(null);
setConsoleAddressEnabled(new EntityModel<Boolean>());
getConsoleAddressEnabled().setEntity(false);
getConsoleAddressEnabled().getEntityChangedEvent().addListener(this);
setIsPm(new EntityModel<Boolean>());
getIsPm().getEntityChangedEvent().addListener(pmListener);
getIsPm().setEntity(false);
setIsPowerManagementTabValid(true);
setIsGeneralTabValid(getIsPowerManagementTabValid());
setSpmPriority(new ListModel<EntityModel<Integer>>());
initSpmPriorities();
fetchPublicKey();
setNetworkProviderModel(new HostNetworkProviderModel());
setDiscorveredHosts(new EntityModel<Boolean>());
}
private void proxyUp() {
if (getPmProxyPreferencesList().getItems() == null) {
return;
}
List<String> list = new ArrayList<String>(getPmProxyPreferencesList().getItems());
String selectedItem = getPmProxyPreferencesList().getSelectedItem();
int selectedItemIndex = list.indexOf(selectedItem);
// Check whether the selected item is first in the list.
if (selectedItemIndex > 0) {
list.remove(selectedItemIndex);
list.add(selectedItemIndex - 1, selectedItem);
getPmProxyPreferencesList().setItems(list);
getPmProxyPreferencesList().setSelectedItem(selectedItem);
}
}
private void proxyDown() {
if (getPmProxyPreferencesList().getItems() == null) {
return;
}
List<String> list = new ArrayList<String>(getPmProxyPreferencesList().getItems());
String selectedItem = getPmProxyPreferencesList().getSelectedItem();
int selectedItemIndex = list.indexOf(selectedItem);
// Check whether the selected item is first in the list.
if (selectedItemIndex < list.size()) {
list.remove(selectedItemIndex);
list.add(selectedItemIndex + 1, selectedItem);
getPmProxyPreferencesList().setItems(list);
getPmProxyPreferencesList().setSelectedItem(selectedItem);
}
}
public void fetchPublicKey() {
AsyncQuery aQuery = new AsyncQuery();
aQuery.setModel(this);
aQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object result)
{
String pk = (String) result;
if (pk != null && pk.length() > 0)
{
getPublicKey().setEntity(pk);
}
}
};
AsyncDataProvider.getInstance().getHostPublicKey(aQuery);
}
private void fetchSSHFingerprint() {
// Cleaning up fields for initialization
getFetchSshFingerprint().setEntity(ConstantsManager.getInstance().getConstants().empty());
getFetchResult().setEntity(ConstantsManager.getInstance().getConstants().empty());
AsyncQuery aQuery = new AsyncQuery();
aQuery.setModel(this);
aQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object result)
{
String fingerprint = (String) result;
if (fingerprint != null && fingerprint.length() > 0)
{
getFetchSshFingerprint().setEntity(fingerprint);
getFetchResult().setEntity(ConstantsManager.getInstance().getConstants().successLoadingFingerprint());
}
else
{
getFetchResult().setEntity(ConstantsManager.getInstance().getConstants().errorLoadingFingerprint());
}
}
};
getHost().validateEntity(new IValidation[] {
new NotEmptyValidation(),
new LengthValidation(255),
new HostAddressValidation() });
if (!getHost().getIsValid()) {
getFetchResult().setEntity(ConstantsManager.getInstance().getConstants().fingerprintAddressError()
+ getHost().getInvalidityReasons().get(0));
}
else {
getFetchResult().setEntity(ConstantsManager.getInstance().getConstants().loadingFingerprint());
AsyncDataProvider.getInstance().getHostFingerprint(aQuery, getHost().getEntity());
}
}
boolean spmInitialized;
int maxSpmPriority;
int defaultSpmPriority;
private void initSpmPriorities() {
AsyncDataProvider.getInstance().getMaxSpmPriority(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
HostModel model = (HostModel) target;
model.maxSpmPriority = (Integer) returnValue;
initSpmPriorities1();
}
}));
}
private void initSpmPriorities1() {
AsyncDataProvider.getInstance().getDefaultSpmPriority(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
HostModel model = (HostModel) target;
model.defaultSpmPriority = (Integer) returnValue;
if (postponedSpmPriority != null) {
updateSpmPriority(postponedSpmPriority);
}
spmInitialized = true;
}
}));
}
private void updateSpmPriority(Integer value) {
List<EntityModel<Integer>> items = new ArrayList<EntityModel<Integer>>();
if (value == null) {
value = defaultSpmPriority;
}
int neverValue = -1;
EntityModel<Integer> neverItem = new EntityModel<Integer>(constants.neverTitle(), neverValue);
items.add(neverItem);
int lowValue = defaultSpmPriority / 2;
items.add(new EntityModel<Integer>(constants.lowTitle(), lowValue));
items.add(new EntityModel<Integer>(constants.normalTitle(), defaultSpmPriority));
int highValue = defaultSpmPriority + (maxSpmPriority - defaultSpmPriority) / 2;
items.add(new EntityModel<Integer>(constants.highTitle(), highValue));
// Determine whether to set custom SPM priority, and where.
EntityModel<Integer> selectedItem = null;
int[] values = new int[] { neverValue, lowValue, defaultSpmPriority, highValue, maxSpmPriority + 1 };
Integer prevValue = null;
for (int i = 0; i < values.length; i++) {
int currentValue = values[i];
if (value == currentValue) {
selectedItem = items.get(i);
break;
} else if (prevValue != null && value > prevValue && value < currentValue) {
EntityModel<Integer> customItem = new EntityModel<Integer>("Custom (" + value + ")", value);//$NON-NLS-1$ //$NON-NLS-2$
items.add(i, customItem);
selectedItem = customItem;
break;
}
prevValue = currentValue;
}
// Delete 'never' item if it's not selected.
if (selectedItem != neverItem) {
items.remove(neverItem);
}
getSpmPriority().setItems(items);
getSpmPriority().setSelectedItem(selectedItem);
}
@Override
public void eventRaised(Event ev, Object sender, EventArgs args)
{
super.eventRaised(ev, sender, args);
if (ev.matchesDefinition(ListModel.selectedItemChangedEventDefinition) && sender == getDataCenter())
{
dataCenter_SelectedItemChanged();
}
else if (ev.matchesDefinition(ListModel.selectedItemChangedEventDefinition) && sender == getCluster())
{
cluster_SelectedItemChanged();
} else if (sender == getConsoleAddressEnabled()) {
consoleAddressChanged();
}
}
private void consoleAddressChanged() {
boolean enabled = getConsoleAddressEnabled().getEntity();
getConsoleAddress().setIsChangable(enabled);
}
private void dataCenter_SelectedItemChanged()
{
StoragePool dataCenter = getDataCenter().getSelectedItem();
if (dataCenter != null)
{
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object result)
{
HostModel hostModel = (HostModel) model;
ArrayList<VDSGroup> clusters = (ArrayList<VDSGroup>) result;
StoragePool selectedDataCenter = getDataCenter().getSelectedItem();
// Update selected cluster only if the returned cluster list is indeed the selected datacenter's
// clusters
if (clusters.isEmpty()
|| clusters.size() > 0
&& clusters.get(0)
.getStoragePoolId()
.equals(selectedDataCenter.getId()))
{
if (hostModel.getIsNew()) {
updateClusterList(hostModel, clusters);
} else {
AsyncQuery architectureQuery = new AsyncQuery();
architectureQuery.setModel(new Object[] { hostModel, clusters });
architectureQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
Object[] objArray = (Object[]) model;
HostModel hostModel = (HostModel) objArray[0];
ArrayList<VDSGroup> clusters = (ArrayList<VDSGroup>) objArray[1];
ArchitectureType architecture = (ArchitectureType) returnValue;
ArrayList<VDSGroup> filteredClusters = new ArrayList<VDSGroup>();
for (VDSGroup cluster : clusters) {
if (architecture == ArchitectureType.undefined
|| cluster.getArchitecture() == ArchitectureType.undefined
|| cluster.getArchitecture() == architecture) {
filteredClusters.add(cluster);
}
}
updateClusterList(hostModel, filteredClusters);
}
};
AsyncDataProvider.getInstance().getHostArchitecture(architectureQuery, hostModel.getHostId());
}
}
}
};
AsyncDataProvider.getInstance().getClusterList(_asyncQuery, dataCenter.getId());
}
}
private void updateClusterList(HostModel hostModel, List<VDSGroup> clusters) {
VDSGroup oldCluster = hostModel.getCluster().getSelectedItem();
hostModel.getCluster().setItems(clusters);
if (oldCluster != null)
{
VDSGroup newSelectedItem =
Linq.firstOrDefault(clusters, new Linq.ClusterPredicate(oldCluster.getId()));
if (newSelectedItem != null)
{
hostModel.getCluster().setSelectedItem(newSelectedItem);
}
}
if (hostModel.getCluster().getSelectedItem() == null)
{
hostModel.getCluster().setSelectedItem(Linq.firstOrDefault(clusters));
}
}
private void cluster_SelectedItemChanged()
{
VDSGroup cluster = getCluster().getSelectedItem();
if (cluster != null)
{
AsyncDataProvider.getInstance().getPmTypeList(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
ArrayList<String> pmTypes = (ArrayList<String>) returnValue;
updatePmTypeList(pmTypes, getPmType());
updatePmTypeList(pmTypes, getPmSecondaryType());
}
}), cluster.getcompatibility_version());
}
}
private void updatePmTypeList(List<String> pmTypes, ListModel<String> model) {
String pmType = model.getSelectedItem();
model.setItems(pmTypes);
if (pmTypes.contains(pmType)) {
model.setSelectedItem(pmType);
}
}
private void setPmOptionsMapInternal(Map<String, String> value, EntityModel<String> port, EntityModel<String> slot, EntityModel<Boolean> secure, EntityModel<String> options) {
StringBuilder pmOptions = new StringBuilder();
for (Map.Entry<String, String> pair : value.entrySet()) {
String k = pair.getKey();
String v = pair.getValue();
if (PmPortKey.equals(k)) {
port.setEntity(StringHelper.isNullOrEmpty(value.get(k)) ? "" : value.get(k)); //$NON-NLS-1$
} else if (PmSlotKey.equals(k)) {
slot.setEntity(StringHelper.isNullOrEmpty(value.get(k)) ? "" : value.get(k)); //$NON-NLS-1$
} else if (PmSecureKey.equals(k)) {
secure.setEntity(Boolean.parseBoolean(value.get(k)));
} else {
// Compose custom string from unknown pm options.
if (StringHelper.isNullOrEmpty(v)) {
pmOptions.append(k).append(","); //$NON-NLS-1$
} else {
pmOptions.append(k).append("=").append(v).append(","); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
String pmOptionsValue = pmOptions.toString();
if (!StringHelper.isNullOrEmpty(pmOptionsValue)) {
options.setEntity(pmOptionsValue.substring(0, pmOptionsValue.length() - 1));
}
}
private HashMap<String, String> getPmOptionsMapInternal(EntityModel<String> port, EntityModel<String> slot, EntityModel<Boolean> secure, EntityModel<String> options) {
HashMap<String, String> dict = new HashMap<String, String>();
// Add well known pm options.
if (port.getIsAvailable() && port.getEntity() != null) {
dict.put(PmPortKey, port.getEntity());
}
if (slot.getIsAvailable() && slot.getEntity() != null) {
dict.put(PmSlotKey, slot.getEntity());
}
if (secure.getIsAvailable()) {
dict.put(PmSecureKey, secure.getEntity().toString());
}
// Add unknown pm options.
// Assume Validate method was called before this getter.
String pmOptions = options.getEntity();
if (!StringHelper.isNullOrEmpty(pmOptions)) {
for (String pair : pmOptions.split("[,]", -1)) //$NON-NLS-1$
{
String[] array = pair.split("[=]", -1); //$NON-NLS-1$
if (array.length == 2) {
dict.put(array[0], array[1]);
} else if (array.length == 1) {
dict.put(array[0], ""); //$NON-NLS-1$
}
}
}
return dict;
}
private void updatePmModels()
{
boolean isPm = getIsPm().getEntity();
final String ciscoUcsValue = "cisco_ucs"; //$NON-NLS-1$
// Update primary PM fields.
getManagementIp().setIsChangable(isPm);
getManagementIp().setIsValid(true);
getPmUserName().setIsChangable(isPm);
getPmUserName().setIsValid(true);
getPmPassword().setIsChangable(isPm);
getPmPassword().setIsValid(true);
getPmType().setIsChangable(isPm);
getPmType().setIsValid(true);
getPmPort().setIsChangable(isPm);
getPmPort().setIsValid(true);
getPmProxyPreferencesList().setIsChangable(getIsPm().getEntity());
String proxySelectedItem = getPmProxyPreferencesList().getSelectedItem();
getTestCommand().setIsExecutionAllowed(isPm);
getProxyUpCommand().setIsExecutionAllowed(isPm && proxySelectedItem != null);
getProxyDownCommand().setIsExecutionAllowed(isPm && proxySelectedItem != null);
getPmSlot().setIsChangable(isPm);
getPmOptions().setIsChangable(isPm);
getPmOptions().setIsValid(true);
getPmSecure().setIsChangable(isPm);
VDSGroup cluster = getCluster().getSelectedItem();
String version = AsyncDataProvider.getInstance().getDefaultConfigurationVersion();
if (cluster != null) {
version = cluster.getcompatibility_version().toString();
}
String pmType = getPmType().getSelectedItem();
if (!StringHelper.isNullOrEmpty(pmType)) {
AsyncDataProvider.getInstance().getPmOptions(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
List<String> pmOptions = (ArrayList<String>) returnValue;
if (pmOptions != null) {
getPmPort().setIsAvailable(pmOptions.contains(PmPortKey));
getPmSlot().setIsAvailable(pmOptions.contains(PmSlotKey));
getPmSecure().setIsAvailable(pmOptions.contains(PmSecureKey));
}
}
}), pmType, version);
setCiscoUcsPrimaryPmTypeSelected(pmType.equals(ciscoUcsValue));
} else {
getPmPort().setIsAvailable(false);
getPmSlot().setIsAvailable(false);
getPmSecure().setIsAvailable(false);
}
// Update secondary PM fields.
getPmSecondaryIp().setIsChangable(isPm);
getPmSecondaryIp().setIsValid(true);
getPmSecondaryUserName().setIsChangable(isPm);
getPmSecondaryUserName().setIsValid(true);
getPmSecondaryPassword().setIsChangable(isPm);
getPmSecondaryPassword().setIsValid(true);
getPmSecondaryType().setIsChangable(isPm);
getPmSecondaryType().setIsValid(true);
getPmSecondaryPort().setIsChangable(isPm);
getPmSecondaryPort().setIsValid(true);
getPmSecondarySlot().setIsChangable(isPm);
getPmSecondaryOptions().setIsChangable(isPm);
getPmSecondaryOptions().setIsValid(true);
getPmSecondarySecure().setIsChangable(isPm);
getDisableAutomaticPowerManagement().setIsValid(true);
getDisableAutomaticPowerManagement().setIsChangable(isPm);
String pmSecondaryType = getPmSecondaryType().getSelectedItem();
if (!StringHelper.isNullOrEmpty(pmSecondaryType)) {
AsyncDataProvider.getInstance().getPmOptions(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
List<String> pmOptions = (ArrayList<String>) returnValue;
if (pmOptions != null) {
getPmSecondaryPort().setIsAvailable(pmOptions.contains(PmPortKey));
getPmSecondarySlot().setIsAvailable(pmOptions.contains(PmSlotKey));
getPmSecondarySecure().setIsAvailable(pmOptions.contains(PmSecureKey));
}
}
}), pmSecondaryType, version);
setCiscoUcsSecondaryPmTypeSelected(pmSecondaryType.equals(ciscoUcsValue));
} else {
getPmSecondaryPort().setIsAvailable(false);
getPmSecondarySlot().setIsAvailable(false);
getPmSecondarySecure().setIsAvailable(false);
}
// Update other PM fields.
getPmVariants().setIsChangable(isPm);
getPmSecondaryConcurrent().setIsChangable(isPm);
getPmKdumpDetection().setIsChangable(isPm);
getTestCommand().setIsExecutionAllowed(isPm);
}
private boolean isPmPrimarySelected() {
List items = (List) getPmVariants().getItems();
String selectedItem = getPmVariants().getSelectedItem();
return items.indexOf(selectedItem) == 0;
}
// Validate user input.
public void test()
{
boolean isPrimary = isPmPrimarySelected();
getCluster().validateSelectedItem(new IValidation[] { new NotEmptyValidation() });
validatePmModels(isPrimary);
if (isPrimary && (!getManagementIp().getIsValid()
|| !getPmUserName().getIsValid()
|| !getPmPassword().getIsValid()
|| !getPmType().getIsValid()
|| !getPmPort().getIsValid()
|| !getPmOptions().getIsValid())) {
return;
}
if (!isPrimary && (!getPmSecondaryIp().getIsValid()
|| !getPmSecondaryUserName().getIsValid()
|| !getPmSecondaryPassword().getIsValid()
|| !getPmSecondaryType().getIsValid()
|| !getPmSecondaryPort().getIsValid()
|| !getPmSecondaryOptions().getIsValid())) {
return;
}
setMessage(ConstantsManager.getInstance().getConstants().testingInProgressItWillTakeFewSecondsPleaseWaitMsg());
getTestCommand().setIsExecutionAllowed(false);
VDSGroup cluster = getCluster().getSelectedItem();
GetNewVdsFenceStatusParameters param = new GetNewVdsFenceStatusParameters();
if (getHostId() != null)
{
param.setVdsId(getHostId());
}
param.setOrder(isPrimary ? FenceAgentOrder.Primary : FenceAgentOrder.Secondary);
param.setManagementIp(isPrimary ? getManagementIp().getEntity() : getPmSecondaryIp().getEntity());
param.setPmType(isPrimary ? getPmType().getSelectedItem() : getPmSecondaryType().getSelectedItem());
param.setUser(isPrimary ? getPmUserName().getEntity() : getPmSecondaryUserName().getEntity());
param.setPassword(isPrimary ? getPmPassword().getEntity() : getPmSecondaryPassword().getEntity());
param.setStoragePoolId(cluster.getStoragePoolId() != null ? cluster.getStoragePoolId() : Guid.Empty);
param.setFencingOptions(getPmOptionsMap());
Frontend.getInstance().runQuery(VdcQueryType.GetNewVdsFenceStatus, param, new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
VdcQueryReturnValue response = (VdcQueryReturnValue) returnValue;
if (response == null || !response.getSucceeded()) {
String message;
if (response != null && response.getReturnValue() != null) {
FenceStatusReturnValue fenceStatusReturnValue =
response.getReturnValue();
message = fenceStatusReturnValue.toString();
} else {
message = ConstantsManager.getInstance().getConstants().testFailedUnknownErrorMsg();
}
setMessage(message);
getTestCommand().setIsExecutionAllowed(true);
} else {
if (response.getReturnValue() != null) {
FenceStatusReturnValue fenceStatusReturnValue =
response.getReturnValue();
String message = fenceStatusReturnValue.toString();
setMessage(message);
getTestCommand().setIsExecutionAllowed(true);
}
}
}
}
, true));
}
private void validatePmModels(boolean primary)
{
EntityModel<String> ip = primary ? getManagementIp() : getPmSecondaryIp();
EntityModel<String> userName = primary ? getPmUserName() : getPmSecondaryUserName();
EntityModel<String> password = primary ? getPmPassword() : getPmSecondaryPassword();
ListModel<String> type = primary ? getPmType() : getPmSecondaryType();
EntityModel<String> port = primary ? getPmPort() : getPmSecondaryPort();
EntityModel<String> options = primary ? getPmOptions() : getPmSecondaryOptions();
ip.validateEntity(new IValidation[] {new NotEmptyValidation(), new HostAddressValidation()});
userName.validateEntity(new IValidation[] {new NotEmptyValidation()});
password.validateEntity(new IValidation[] {new NotEmptyValidation()});
type.validateSelectedItem(new IValidation[] {new NotEmptyValidation()});
port.validateEntity(new IValidation[] {new IntegerValidation(1, 65535)});
options.validateEntity(new IValidation[] {new KeyValuePairValidation(true)});
}
public boolean validate()
{
getName().validateEntity(new IValidation[] { new HostnameValidation() });
getComment().validateEntity(new IValidation[] { new SpecialAsciiI18NOrNoneValidation() });
getHost().validateEntity(new IValidation[] {
new NotEmptyValidation(),
new LengthValidation(255),
new HostAddressValidation() });
getAuthSshPort().validateEntity(new IValidation[] {new NotEmptyValidation(), new IntegerValidation(1, 65535)});
if (getConsoleAddressEnabled().getEntity()) {
getConsoleAddress().validateEntity(new IValidation[] {new NotEmptyValidation(), new HostAddressValidation()});
} else {
// the console address is ignored so can not be invalid
getConsoleAddress().setIsValid(true);
}
getDataCenter().validateSelectedItem(new IValidation[] { new NotEmptyValidation() });
getCluster().validateSelectedItem(new IValidation[] { new NotEmptyValidation() });
if (getIsPm().getEntity())
{
// If PM enabled primary fencing options must be specified, ensure that.
validatePmModels(true);
// Secondary fencing options aren't mandatory, only ensure there was set
// if one of the related fields was filled.
if (!isEntityModelEmpty(getPmSecondaryIp())
|| !isEntityModelEmpty(getPmSecondaryUserName())
|| !isEntityModelEmpty(getPmSecondaryPassword())
|| !isEntityModelEmpty(getPmSecondaryPort())
|| !isEntityModelEmpty(getPmSecondarySlot())
|| !isEntityModelEmpty(getPmSecondaryOptions())) {
getPmSecondaryIp().setIsValid(true);
getPmSecondaryUserName().setIsValid(true);
getPmSecondaryPassword().setIsValid(true);
getPmSecondaryPort().setIsValid(true);
getPmSecondarySlot().setIsValid(true);
getPmSecondaryOptions().setIsValid(true);
validatePmModels(false);
}
}
setIsGeneralTabValid(getName().getIsValid()
&& getComment().getIsValid()
&& getHost().getIsValid()
&& getAuthSshPort().getIsValid()
&& getCluster().getIsValid()
);
setIsPowerManagementTabValid(getManagementIp().getIsValid()
&& getPmUserName().getIsValid()
&& getPmPassword().getIsValid()
&& getPmType().getIsValid()
&& getPmPort().getIsValid()
&& getPmOptions().getIsValid()
&& getPmSecondaryIp().getIsValid()
&& getPmSecondaryUserName().getIsValid()
&& getPmSecondaryPassword().getIsValid()
&& getPmSecondaryType().getIsValid()
&& getPmSecondaryPort().getIsValid()
&& getPmSecondaryOptions().getIsValid());
getNetworkProviderModel().validate();
return getIsGeneralTabValid() && getIsPowerManagementTabValid() && getConsoleAddress().getIsValid()
&& getNetworkProviderModel().getIsValid();
}
private boolean isEntityModelEmpty(EntityModel<String> model) {
return !(model.getEntity() != null && !model.getEntity().equals(""));
}
public void updateModelFromVds(VDS vds,
ArrayList<StoragePool> dataCenters,
boolean isEditWithPMemphasis,
SystemTreeItemModel selectedSystemTreeItem)
{
setHostId(vds.getId());
getOverrideIpTables().setIsAvailable(showInstallationProperties());
getProtocol().setEntity(VdsProtocol.STOMP == vds.getProtocol());
setSpmPriorityValue(vds.getVdsSpmPriority());
setOriginalName(vds.getName());
getName().setEntity(vds.getName());
getComment().setEntity(vds.getComment());
getHost().setEntity(vds.getHostName());
getFetchSshFingerprint().setEntity(vds.getSshKeyFingerprint());
getUserName().setEntity(vds.getSshUsername());
getAuthSshPort().setEntity(vds.getSshPort());
setPort(vds);
boolean consoleAddressEnabled = vds.getConsoleAddress() != null;
getConsoleAddressEnabled().setEntity(consoleAddressEnabled);
getConsoleAddress().setEntity(vds.getConsoleAddress());
getConsoleAddress().setIsChangable(consoleAddressEnabled);
if (!showInstallationProperties()) {
getPkSection().setIsChangable(false);
getPkSection().setIsAvailable(false);
// Use public key when edit or approve host
setAuthenticationMethod(AuthenticationMethod.PublicKey);
}
setAllowChangeHost(vds);
// Set primary PM parameters.
getManagementIp().setEntity(vds.getManagementIp());
getPmUserName().setEntity(vds.getPmUser());
getPmPassword().setEntity(vds.getPmPassword());
getPmType().setSelectedItem(vds.getPmType());
setPmOptionsMap(VdsStatic.pmOptionsStringToMap(vds.getPmOptions()));
// Set secondary PM parameters.
getPmSecondaryIp().setEntity(vds.getPmSecondaryIp());
getPmSecondaryUserName().setEntity(vds.getPmSecondaryUser());
getPmSecondaryPassword().setEntity(vds.getPmSecondaryPassword());
getPmSecondaryType().setSelectedItem(vds.getPmSecondaryType());
setPmSecondaryOptionsMap(vds.getPmSecondaryOptionsMap());
// Set other PM parameters.
if (isEditWithPMemphasis) {
setIsPowerManagementTabSelected(true);
getIsPm().setEntity(true);
getIsPm().setIsChangable(false);
} else {
getIsPm().setEntity(vds.getpm_enabled());
}
getPmSecondaryConcurrent().setEntity(vds.isPmSecondaryConcurrent());
getDisableAutomaticPowerManagement().setEntity(vds.isDisablePowerManagementPolicy());
getPmKdumpDetection().setEntity(vds.isPmKdumpDetection());
updateModelDataCenterFromVds(dataCenters, vds);
ArrayList<VDSGroup> clusters;
if (getCluster().getItems() == null)
{
VDSGroup tempVar = new VDSGroup();
tempVar.setName(vds.getVdsGroupName());
tempVar.setId(vds.getVdsGroupId());
tempVar.setcompatibility_version(vds.getVdsGroupCompatibilityVersion());
getCluster()
.setItems(new ArrayList<VDSGroup>(Arrays.asList(new VDSGroup[] { tempVar })));
}
clusters = (ArrayList<VDSGroup>) getCluster().getItems();
updateModelClusterFromVds(clusters, vds);
if (getCluster().getSelectedItem() == null)
{
getCluster().setSelectedItem(Linq.firstOrDefault(clusters));
}
if (vds.getStatus() != VDSStatus.Maintenance &&
vds.getStatus() != VDSStatus.PendingApproval &&
vds.getStatus() != VDSStatus.InstallingOS) {
setAllowChangeHostPlacementPropertiesWhenNotInMaintenance();
}
else if (selectedSystemTreeItem != null)
{
final UIConstants constants = ConstantsManager.getInstance().getConstants();
switch (selectedSystemTreeItem.getType())
{
case Host:
getName().setIsChangable(false);
getName().setChangeProhibitionReason(constants.cannotEditNameInTreeContext());
break;
case Hosts:
case Cluster:
case Cluster_Gluster:
getCluster().setIsChangable(false);
getCluster().setChangeProhibitionReason(constants.cannotChangeClusterInTreeContext());
getDataCenter().setIsChangable(false);
break;
case DataCenter:
StoragePool selectDataCenter = (StoragePool) selectedSystemTreeItem.getEntity();
getDataCenter()
.setItems(new ArrayList<StoragePool>(Arrays.asList(new StoragePool[] { selectDataCenter })));
getDataCenter().setSelectedItem(selectDataCenter);
getDataCenter().setIsChangable(false);
break;
default:
break;
}
}
}
public void cleanHostParametersFields() {
getName().setEntity(constants.empty());
getComment().setEntity(constants.empty());
getAuthSshPort().setEntity(Integer.parseInt(constants.defaultHostSSHPort()));
getHost().setEntity(constants.empty());
getUserPassword().setEntity(constants.empty());
getFetchSshFingerprint().setEntity(constants.empty());
}
protected abstract boolean showInstallationProperties();
protected abstract boolean showTransportProperties();
public abstract boolean showExternalProviderPanel();
protected abstract void updateModelDataCenterFromVds(ArrayList<StoragePool> dataCenters, VDS vds);
protected abstract void updateModelClusterFromVds(ArrayList<VDSGroup> clusters, VDS vds);
protected abstract void setAllowChangeHost(VDS vds);
protected abstract void setAllowChangeHostPlacementPropertiesWhenNotInMaintenance();
public abstract void updateHosts();
protected abstract void setPort(VDS vds);
public abstract boolean showNetworkProviderTab();
}
|
/* WARNING: THIS FILE IS AUTO-GENERATED
DO NOT MODIFY THIS SOURCE
ALL CHANGES MUST BE MADE IN THE CATALOG GENERATOR */
package org.voltdb.catalog;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.commons.lang3.StringUtils;
import org.voltdb.VoltType;
import org.voltdb.catalog.CatalogChangeGroup.FieldChange;
import org.voltdb.catalog.CatalogChangeGroup.TypeChanges;
import org.voltdb.expressions.AbstractExpression;
import org.voltdb.utils.CatalogSizing;
import org.voltdb.utils.CatalogUtil;
public class CatalogDiffEngine {
/*/ //ELSE
//*/ //ENDIF
/**
* Instantiate a new diff. The resulting object can return the text
* of the difference and report whether the difference is allowed in a
* running system.
* @param prev Tip of the old catalog.
* @param next Tip of the new catalog.
*/
public CatalogDiffEngine(final Catalog prev, final Catalog next) {
m_supported = true;
// store the complete set of old and new indexes so some extra checking can be done with
// constraints and new/updated unique indexes
CatalogMap<Table> tables = prev.getClusters().get("cluster").getDatabases().get("database").getTables();
assert(tables != null);
for (Table t : tables) {
m_originalIndexesByTable.put(t.getTypeName(), t.getIndexes());
}
tables = next.getClusters().get("cluster").getDatabases().get("database").getTables();
assert(tables != null);
for (Table t : tables) {
m_newIndexesByTable.put(t.getTypeName(), t.getIndexes());
}
// make sure this map has an entry for each value
for (DiffClass dc : DiffClass.values()) {
m_changes.put(dc, new CatalogChangeGroup(dc));
}
diffRecursively(prev, next);
if (m_triggeredVerbosity || m_triggerForVerbosity.equals("final")) {
System.out.println("DEBUG VERBOSE diffRecursively Errors:" +
( m_supported ? " <none>" : "\n" + errors()));
System.out.println("DEBUG VERBOSE diffRecursively Commands: " + commands());
}
}
public String commands() {
return m_sb.toString();
}
public boolean supported() {
return m_supported;
}
/**
* @return true if table changes require the catalog change runs
* while no snapshot is running.
*/
public boolean requiresSnapshotIsolation() {
return m_requiresSnapshotIsolation;
}
public String[] tablesThatMustBeEmpty() {
// this lines up with reasonsWhyTablesMustBeEmpty because SortedMap/TreeMap has order
return m_tablesThatMustBeEmpty.keySet().toArray(new String[0]);
}
public String[] reasonsWhyTablesMustBeEmpty() {
// this lines up with tablesThatMustBeEmpty because SortedMap/TreeMap has order
return m_tablesThatMustBeEmpty.values().toArray(new String[0]);
}
public boolean worksWithElastic() {
return m_canOccurWithElasticRebalance;
}
public String errors() {
return m_errors.toString();
}
enum ChangeType {
ADDITION, DELETION
}
/**
* Check if a candidate unique index (for addition) covers an existing unique index.
* If a unique index exists on a subset of the columns, then the less specific index
* can be created without failing.
*/
private boolean indexCovers(Index newIndex, Index existingIndex) {
assert(newIndex.getParent().getTypeName().equals(existingIndex.getParent().getTypeName()));
// non-unique indexes don't help with this check
if (existingIndex.getUnique() == false) {
return false;
}
// expression indexes only help if they are on exactly the same expressions in the same order.
// OK -- that's obviously overspecifying the requirement, since expression order has nothing
// to do with it, and uniqueness of just a subset of the new index expressions would do, but
// that's hard to check for, so we punt on optimized dynamic update except for the critical
// case of grand-fathering in a surviving pre-existing index.
if (existingIndex.getExpressionsjson().length() > 0) {
if (existingIndex.getExpressionsjson().equals(newIndex.getExpressionsjson())) {
return true;
} else {
return false;
}
} else if (newIndex.getExpressionsjson().length() > 0) {
// A column index does not generally provide coverage for an expression index,
// though there are some special cases not being recognized, here,
// like expression indexes that list a mix of non-column expressions and unique columns.
return false;
}
// iterate over all of the existing columns
for (ColumnRef existingColRef : existingIndex.getColumns()) {
boolean foundMatch = false;
// see if the current column is also in the candidate index
// for now, assume the tables in question have the same schema
for (ColumnRef colRef : newIndex.getColumns()) {
String colName1 = colRef.getColumn().getName();
String colName2 = existingColRef.getColumn().getName();
if (colName1.equals(colName2)) {
foundMatch = true;
break;
}
}
// if this column isn't covered
if (!foundMatch) {
return false;
}
}
// There exists a unique index that contains a subset of the columns in the new index
return true;
}
/**
* Check if there is a unique index that exists in the old catalog
* that is covered by the new index. That would mean adding this index
* can't fail with a duplicate key.
*
* @param newIndex The new index to check.
* @return True if the index can be created without a chance of failing.
*/
private boolean checkNewUniqueIndex(Index newIndex) {
Table table = (Table) newIndex.getParent();
CatalogMap<Index> existingIndexes = m_originalIndexesByTable.get(table.getTypeName());
for (Index existingIndex : existingIndexes) {
if (indexCovers(newIndex, existingIndex)) {
return true;
}
}
return false;
}
/**
* @param oldType The old type of the column.
* @param oldSize The old size of the column.
* @param newType The new type of the column.
* @param newSize The new size of the column.
*
* @return True if the change from one column type to another is possible
* to do live without failing or truncating any data.
*/
private boolean checkIfColumnTypeChangeIsSupported(VoltType oldType, int oldSize,
VoltType newType, int newSize,
boolean oldInBytes, boolean newInBytes)
{
// increases in size are cool; shrinks not so much
if (oldType == newType) {
if (oldType == VoltType.STRING && oldInBytes == false && newInBytes == true) {
// varchar CHARACTER to varchar BYTES
return oldSize * 4 <= newSize;
}
return oldSize <= newSize;
}
// allow people to convert timestamps to longs
// (this is useful if they accidentally put millis instead of micros in there)
if ((oldType == VoltType.TIMESTAMP) && (newType == VoltType.BIGINT)) {
return true;
}
// allow integer size increase and allow promotion to DECIMAL
if (oldType == VoltType.BIGINT) {
if (newType == VoltType.DECIMAL) {
return true;
}
}
// also allow lossless conversion to double from ints < mantissa size
else if (oldType == VoltType.INTEGER) {
if ((newType == VoltType.DECIMAL) ||
(newType == VoltType.FLOAT) ||
newType == VoltType.BIGINT) {
return true;
}
}
else if (oldType == VoltType.SMALLINT) {
if ((newType == VoltType.DECIMAL) ||
(newType == VoltType.FLOAT) ||
(newType == VoltType.BIGINT) ||
(newType == VoltType.INTEGER)) {
return true;
}
}
else if (oldType == VoltType.TINYINT) {
if ((newType == VoltType.DECIMAL) ||
(newType == VoltType.FLOAT) ||
(newType == VoltType.BIGINT) ||
(newType == VoltType.INTEGER) ||
(newType == VoltType.SMALLINT)) {
return true;
}
}
return false;
}
/**
* @return null if the CatalogType can be dynamically added or removed
* from a running system. Return an error string if it can't be changed on
* a non-empty table. There will be a subsequent check for empty table
* feasability.
*/
private String checkAddDropWhitelist(final CatalogType suspect, final ChangeType changeType)
{
//Will catch several things that are actually just deployment changes, but don't care
//to be more specific at this point
m_canOccurWithElasticRebalance = false;
// should generate this from spec.txt
if (suspect instanceof User ||
suspect instanceof Group ||
suspect instanceof Procedure ||
suspect instanceof Connector ||
suspect instanceof SnapshotSchedule ||
// refs are safe to add drop if the thing they reference is
suspect instanceof ConstraintRef ||
suspect instanceof GroupRef ||
suspect instanceof UserRef ||
// The only meaty constraints (for now) are UNIQUE, PKEY and NOT NULL.
// The UNIQUE and PKEY constraints are supported as index definitions.
// NOT NULL is supported as a field on columns.
// So, in short, all of these constraints will pass or fail tests of other catalog differences
// Even if they did show up as Constraints in the catalog (for no apparent functional reason),
// flagging their changes here would be redundant.
suspect instanceof Constraint ||
// Support add/drop of the top level object.
suspect instanceof Table)
{
return null;
}
else if (suspect instanceof ColumnRef) {
if (suspect.getParent() instanceof Index) {
Index parent = (Index) suspect.getParent();
if (parent.getUnique() && (changeType == ChangeType.DELETION)) {
CatalogMap<Index> newIndexes= m_newIndexesByTable.get(parent.getParent().getTypeName());
Index newIndex = newIndexes.get(parent.getTypeName());
if (!checkNewUniqueIndex(newIndex)) {
return "May not dynamically remove columns from unique index: " +
parent.getTypeName();
}
}
}
// ColumnRef is not part of an index, index is not unique OR unique index is safe to create
return null;
}
else if (suspect instanceof Column) {
// Note: "return false;" vs. fall through, in any of these branches
// overrides the grandfathering-in of added/dropped Column-typed
// sub-components of Procedure, Connector, etc. as checked in the loop, below.
// Is this safe/correct?
if (m_inStrictMatViewDiffMode) {
return "May not dynamically add, drop, or rename materialized view columns.";
}
if (changeType == ChangeType.ADDITION) {
Column col = (Column) suspect;
if ((! col.getNullable()) && (col.getDefaultvalue() == null)) {
return "May not dynamically add non-nullable column without default value.";
}
}
// adding/dropping a column requires isolation from snapshots
m_requiresSnapshotIsolation = true;
return null;
}
// allow addition/deletion of indexes except for the addition
// of certain unique indexes that might fail if created
else if (suspect instanceof Index) {
Index index = (Index) suspect;
if (!index.m_unique) {
return null;
}
// it's cool to remove unique indexes
if (changeType == ChangeType.DELETION) {
return null;
}
// if adding a unique index, check if the columns in the new
// index cover an existing index
if (checkNewUniqueIndex(index)) {
return null;
}
// Note: return error vs. fall through, here
// overrides the grandfathering-in of (any? possible?) added/dropped Index-typed
// sub-components of Procedure, Connector, etc. as checked in the loop, below.
return "May not dynamically add unique indexes that don't cover existing unique indexes.\n";
}
else if (suspect instanceof MaterializedViewInfo && ! m_inStrictMatViewDiffMode) {
return null;
}
//TODO: This code is also pretty fishy
// -- See the "salmon of doubt" comment in checkModifyWhitelist
// Also allow add/drop of anything (that hasn't triggered an early return already)
// if it is found anywhere in these sub-trees.
for (CatalogType parent = suspect.m_parent; parent != null; parent = parent.m_parent) {
if (parent instanceof Procedure ||
parent instanceof Connector ||
parent instanceof ConstraintRef ||
parent instanceof Column) {
if (m_triggeredVerbosity) {
System.out.println("DEBUG VERBOSE diffRecursively " +
((changeType == ChangeType.ADDITION) ? "addition" : "deletion") +
" of schema object '" + suspect + "'" +
" rescued by context '" + parent + "'");
}
return null;
}
}
return "May not dynamically add/drop schema object: '" + suspect + "'\n";
}
/**
* @return null if the change is not possible under any circumstances.
* Return two strings if it is possible if the table is empty.
* String 1 is name of a table if the change could be made if the table of that name had no tuples.
* String 2 is the error message to show the user if that table isn't empty.
*/
private String[] checkAddDropIfTableIsEmptyWhitelist(final CatalogType suspect, final ChangeType changeType) {
String[] retval = new String[2];
// handle adding an index - presumably unique
if (suspect instanceof Index) {
Index idx = (Index) suspect;
assert(idx.getUnique());
retval[0] = idx.getParent().getTypeName();
retval[1] = String.format(
"Unable to add unique index %s because table %s is not empty.",
idx.getTypeName(), retval[0]);
return retval;
}
// handle changes to columns in an index - presumably drops and presumably unique
if ((suspect instanceof ColumnRef) && (suspect.getParent() instanceof Index)) {
Index idx = (Index) suspect.getParent();
assert(idx.getUnique());
assert(changeType == ChangeType.DELETION);
Table table = (Table) idx.getParent();
retval[0] = table.getTypeName();
retval[1] = String.format(
"Unable to remove column %s from unique index %s because table %s is not empty.",
suspect.getTypeName(), idx.getTypeName(), retval[0]);
return retval;
}
return null;
}
private boolean areTableColumnsMutable(Table table) {
//WARNING: There used to be a test here that the table's list of views was empty,
// but what it actually appeared to be testing was whether the table HAD views prior
// to any redefinition in the current catalog.
// This means that dropping mat views and changing the underlying columns in one "live"
// catalog change would not be an option -- they would have to be broken up into separate
// steps.
// Fortunately, for now, all the allowed "live column changes" seem to be supported without
// disrupting materialized views.
// In the future it MAY be required that column mutability gets re-checked after all of the
// mat view definitions (drops and adds) have been processed, in case certain kinds of
// underlying column change might cause special problems for certain specific cases of
// materialized view definition.
// no export tables
Database db = (Database) table.getParent();
for (Connector connector : db.getConnectors()) {
for (ConnectorTableInfo tinfo : connector.getTableinfo()) {
if (tinfo.getTable() == table) {
m_errors.append("May not change the columns of export table " +
table.getTypeName() + ".\n");
return false;
}
}
}
return true;
}
/**
* @return true if this change may be ignored
*/
protected boolean checkModifyIgnoreList(final CatalogType suspect,
final CatalogType prevType,
final String field)
{
if (suspect instanceof Deployment) {
// ignore host count differences as clusters may elastically expand,
// and yet require catalog changes
return "hostcount".equals(field);
}
return false;
}
/**
* @return true if this addition may be ignored
*/
protected boolean checkAddIgnoreList(final CatalogType suspect)
{
return false;
}
/**
* @return true if this delete may be ignored
*/
protected boolean checkDeleteIgnoreList(final CatalogType prevType,
final CatalogType newlyChildlessParent,
final String mapName,
final String name)
{
return false;
}
/**
* @return null if CatalogType can be dynamically modified
* in a running system. Otherwise return an error message that
* can be given if it turns out we really can't make the change.
* Return "" if the error has already been handled.
*/
private String checkModifyWhitelist(final CatalogType suspect,
final CatalogType prevType,
final String field)
{
// should generate this from spec.txt
if (suspect instanceof Systemsettings &&
(field.equals("elasticduration") || field.equals("elasticthroughput")
|| field.equals("querytimeout"))) {
return null;
} else {
m_canOccurWithElasticRebalance = false;
}
// Support any modification of these
if (suspect instanceof User ||
suspect instanceof Group ||
suspect instanceof Procedure ||
suspect instanceof SnapshotSchedule ||
suspect instanceof UserRef ||
suspect instanceof GroupRef ||
suspect instanceof ColumnRef) {
return null;
}
// Support modification of these specific fields
if (suspect instanceof Database && field.equals("schema"))
return null;
if (suspect instanceof Database && "securityprovider".equals(field))
return null;
if (suspect instanceof Cluster && field.equals("securityEnabled"))
return null;
if (suspect instanceof Cluster && field.equals("adminstartup"))
return null;
if (suspect instanceof Cluster && field.equals("heartbeatTimeout"))
return null;
if (suspect instanceof Constraint && field.equals("index"))
return null;
if (suspect instanceof Table) {
if (field.equals("signature") || field.equals("tuplelimit"))
return null;
}
// Avoid over-generalization when describing limitations that are dependent on particular
// cases of BEFORE and AFTER values by listing the offending values.
String restrictionQualifier = "";
// whitelist certain column changes
if (suspect instanceof Column) {
CatalogType parent = suspect.getParent();
// can change statements
if (parent instanceof Statement) {
return null;
}
// all table column changes require snapshot isolation for now
m_requiresSnapshotIsolation = true;
// now assume parent is a Table
Table parentTable = (Table) parent;
if ( ! areTableColumnsMutable(parentTable)) {
// Note: "return false;" vs. fall through, here
// overrides the grandfathering-in of modified fields of
// Column-typed sub-components of Procedure and ColumnRef.
// Is this safe/correct?
return ""; // error msg already appended
}
if (field.equals("index")) {
return null;
}
if (field.equals("defaultvalue")) {
return null;
}
if (field.equals("defaulttype")) {
return null;
}
if (field.equals("nullable")) {
Boolean nullable = (Boolean) suspect.getField(field);
assert(nullable != null);
if (nullable) return null;
restrictionQualifier = " from nullable to non-nullable";
}
else if (field.equals("type") || field.equals("size") || field.equals("inbytes")) {
int oldTypeInt = (Integer) prevType.getField("type");
int newTypeInt = (Integer) suspect.getField("type");
int oldSize = (Integer) prevType.getField("size");
int newSize = (Integer) suspect.getField("size");
VoltType oldType = VoltType.get((byte) oldTypeInt);
VoltType newType = VoltType.get((byte) newTypeInt);
boolean oldInBytes = false, newInBytes = false;
if (oldType == VoltType.STRING) {
oldInBytes = (Boolean) prevType.getField("inbytes");
}
if (newType == VoltType.STRING) {
newInBytes = (Boolean) suspect.getField("inbytes");
}
if (checkIfColumnTypeChangeIsSupported(oldType, oldSize, newType, newSize,
oldInBytes, newInBytes)) {
return null;
}
if (oldTypeInt == newTypeInt) {
if (oldType == VoltType.STRING && oldInBytes == false && newInBytes == true) {
restrictionQualifier = "narrowing from " + oldSize + "CHARACTERS to "
+ newSize * CatalogSizing.MAX_BYTES_PER_UTF8_CHARACTER + " BYTES";
} else {
restrictionQualifier = "narrowing from " + oldSize + " to " + newSize;
}
}
else {
restrictionQualifier = "from " + oldType.toSQLString() +
" to " + newType.toSQLString();
}
}
}
else if (suspect instanceof MaterializedViewInfo) {
if ( ! m_inStrictMatViewDiffMode) {
// Ignore differences to json fields that only reflect other underlying
// changes that are presumably checked and accepted/rejected separately.
if (field.equals("groupbyExpressionsJson") ||
field.equals("aggregationExpressionsJson")) {
if (AbstractExpression.areOverloadedJSONExpressionLists((String)prevType.getField(field),
(String)suspect.getField(field))) {
return null;
}
}
}
}
// Also allow any field changes (that haven't triggered an early return already)
// if they are found anywhere in these sub-trees.
//TODO: There's a "salmon of doubt" about all this upstream checking in the middle of a
// downward recursion.
// In effect, each sub-element of these certain parent object types has been forced to
// successfully "run the gnutella" of qualifiers above.
// Having survived, they are only now paternity tested
// -- which repeatedly revisits once per changed field, per (recursive) child,
// each of the parents that were seen on the way down --
// to possibly decide "nevermind, this change is grand-fathered in after all".
// A better general approach would be for the parent object types,
// as they are recursed into, to set one or more state mode flags on the CatalogDiffEngine.
// These would be somewhat like m_inStrictMatViewDiffMode
// -- but with a loosening rather than restricting effect on recursive tests.
// This would provide flexibility in the future for the grand-fathered elements
// to bypass as many or as few checks as desired.
for (CatalogType parent = suspect.m_parent; parent != null; parent = parent.m_parent) {
if (parent instanceof Procedure || parent instanceof ColumnRef) {
if (m_triggeredVerbosity) {
System.out.println("DEBUG VERBOSE diffRecursively field change to " +
"'" + field + "' of schema object '" + suspect + "'" +
restrictionQualifier +
" rescued by context '" + parent + "'");
}
return null;
}
}
return "May not dynamically modify field '" + field +
"' of schema object '" + suspect + "'" + restrictionQualifier;
}
/**
* @return null if the change is not possible under any circumstances.
* Return two strings if it is possible if the table is empty.
* String 1 is name of a table if the change could be made if the table of that name had no tuples.
* String 2 is the error message to show the user if that table isn't empty.
*/
public String[] checkModifyIfTableIsEmptyWhitelist(final CatalogType suspect,
final CatalogType prevType,
final String field)
{
// first is table name, second is error message
String[] retval = new String[2];
if (prevType instanceof Table) {
Table prevTable = (Table) prevType; // safe because of enclosing if-block
Database db = (Database) prevType.getParent();
// table name
retval[0] = suspect.getTypeName();
// for now, no changes to export tables
if (CatalogUtil.isTableExportOnly(db, prevTable)) {
return null;
}
// allowed changes to a table
if (field.equalsIgnoreCase("isreplicated")) {
// error message
retval[1] = String.format(
"Unable to change whether table %s is replicated because it is not empty.",
retval[0]);
return retval;
}
if (field.equalsIgnoreCase("partitioncolumn")) {
// error message
retval[1] = String.format(
"Unable to change the partition column of table %s because it is not empty.",
retval[0]);
return retval;
}
}
// handle narrowing columns
if (prevType instanceof Column) {
Table table = (Table) prevType.getParent();
Database db = (Database) table.getParent();
// for now, no changes to export tables
if (CatalogUtil.isTableExportOnly(db, table)) {
return null;
}
// capture the table name
retval[0] = table.getTypeName();
if (field.equalsIgnoreCase("type")) {
// error message
retval[1] = String.format(
"Unable to make a possibly-lossy type change to column %s in table %s because it is not empty.",
prevType.getTypeName(), retval[0]);
return retval;
}
if (field.equalsIgnoreCase("size")) {
// error message
retval[1] = String.format(
"Unable to narrow the width of column %s in table %s because it is not empty.",
prevType.getTypeName(), retval[0]);
return retval;
}
}
return null;
}
/**
* Add a modification
*/
private void writeModification(CatalogType newType, CatalogType prevType, String field)
{
// Don't write modifications if the field can be ignored
if (checkModifyIgnoreList(newType, prevType, field)) {
return;
}
// verify this is possible, write an error and mark return code false if so
String errorMessage = checkModifyWhitelist(newType, prevType, field);
// if it's not possible with non-empty tables, check for possible with empty tables
if (errorMessage != null) {
String[] response = checkModifyIfTableIsEmptyWhitelist(newType, prevType, field);
// handle all the error messages and state from the modify check
processModifyResponses(errorMessage, response);
}
// write the commands to make it so
// they will be ignored if the change is unsupported
newType.writeCommandForField(m_sb, field, true);
// record the field change for later generation of descriptive text
// though skip the schema field of database because it changes all the time
// and the diff will be caught elsewhere
// need a better way to generalize this
if ((newType instanceof Database) && field.equals("schema")) {
return;
}
CatalogChangeGroup cgrp = m_changes.get(DiffClass.get(newType));
cgrp.processChange(newType, prevType, field);
}
/**
* After we decide we can't modify, add or delete something on a full table,
* we do a check to see if we can do that on an empty table. The original error
* and any response from the empty table check is processed here. This code
* is basically in this method so it's not repeated 3 times for modify, add
* and delete. See where it's called for context.
*/
private void processModifyResponses(String errorMessage, String[] response) {
assert(errorMessage != null);
// if no tablename, then it's just not possible
if (response == null) {
m_supported = false;
m_errors.append(errorMessage);
}
// otherwise, it's possible if a specific table is empty
// collect the error message(s) and decide if it can be done inside @UAC
else {
assert(response.length == 2);
String tableName = response[0]; assert(tableName != null);
String nonEmptyErrorMessage = response[1]; assert(nonEmptyErrorMessage != null);
String existingErrorMessagesForNonEmptyTable = m_tablesThatMustBeEmpty.get(tableName);
if (nonEmptyErrorMessage.length() == 0) {
// the empty string presumes there is already an error for this table
assert(existingErrorMessagesForNonEmptyTable != null);
}
else {
if (existingErrorMessagesForNonEmptyTable != null) {
nonEmptyErrorMessage = nonEmptyErrorMessage + "\n" + existingErrorMessagesForNonEmptyTable;
}
// add indentation here so the formatting comes out right for the user #gianthack
m_tablesThatMustBeEmpty.put(tableName, " " + nonEmptyErrorMessage);
}
}
}
/**
* Add a deletion
*/
private void writeDeletion(CatalogType prevType, CatalogType newlyChildlessParent, String mapName, String name)
{
// Don't write deletions if the field can be ignored
if (checkDeleteIgnoreList(prevType, newlyChildlessParent, mapName, name)) {
return;
}
// verify this is possible, write an error and mark return code false if so
String errorMessage = checkAddDropWhitelist(prevType, ChangeType.DELETION);
// if it's not possible with non-empty tables, check for possible with empty tables
if (errorMessage != null) {
String[] response = checkAddDropIfTableIsEmptyWhitelist(prevType, ChangeType.DELETION);
// handle all the error messages and state from the modify check
processModifyResponses(errorMessage, response);
}
// write the commands to make it so
// they will be ignored if the change is unsupported
m_sb.append("delete ").append(prevType.getParent().getPath()).append(" ");
m_sb.append(mapName).append(" ").append(name).append("\n");
// add it to the set of deletions to later compute descriptive text
CatalogChangeGroup cgrp = m_changes.get(DiffClass.get(prevType));
cgrp.processDeletion(prevType, newlyChildlessParent);
}
/**
* Add an addition
*/
private void writeAddition(CatalogType newType) {
// Don't write additions if the field can be ignored
if (checkAddIgnoreList(newType)) {
return;
}
// verify this is possible, write an error and mark return code false if so
String errorMessage = checkAddDropWhitelist(newType, ChangeType.ADDITION);
// if it's not possible with non-empty tables, check for possible with empty tables
if (errorMessage != null) {
String[] response = checkAddDropIfTableIsEmptyWhitelist(newType, ChangeType.ADDITION);
// handle all the error messages and state from the modify check
processModifyResponses(errorMessage, response);
}
// write the commands to make it so
// they will be ignored if the change is unsupported
newType.writeCreationCommand(m_sb);
newType.writeFieldCommands(m_sb);
newType.writeChildCommands(m_sb);
// add it to the set of additions to later compute descriptive text
CatalogChangeGroup cgrp = m_changes.get(DiffClass.get(newType));
cgrp.processAddition(newType);
}
/**
* Pre-order walk of catalog generating add, delete and set commands
* that compose that full difference.
* @param prevType
* @param newType
*/
private void diffRecursively(CatalogType prevType, CatalogType newType)
{
assert(prevType != null) : "Null previous object found in catalog diff traversal.";
assert(newType != null) : "Null new object found in catalog diff traversal";
Object materializerValue = null;
// Consider shifting into the strict more required within materialized view definitions.
if (prevType instanceof Table) {
// Under normal circumstances, it's highly unpossible that another (nested?) table will
// appear in the details of a materialized view table. So, when it does (!?), be sure to
// complain -- and don't let it throw off the accounting of the strict diff mode.
// That is, don't set the local "materializerValue".
if (m_inStrictMatViewDiffMode) {
// Maybe this should log or append to m_errors?
System.out.println("ERROR: unexpected nesting of a Table in CatalogDiffEngine.");
} else {
materializerValue = prevType.getField("materializer");
if (materializerValue != null) {
// This table is a materialized view, so the changes to it and its children are
// strictly limited, e.g. no adding/dropping columns.
// In a future development, such changes may be allowed, but they may be implemented
// differently (get different catalog commands), such as through a wholesale drop/add
// of the entire view and materialized table definitions.
// The non-null local "materializerValue" is a reminder to pop out of this mode
// before returning from this level of the recursion.
m_inStrictMatViewDiffMode = true;
if (m_triggeredVerbosity) {
System.out.println("DEBUG VERBOSE diffRecursively entering strict mat view mode");
}
}
}
}
// diff local fields
for (String field : prevType.getFields()) {
// this field is (or was) set at runtime, so ignore it for diff purposes
if (field.equals("isUp"))
{
continue;
}
boolean verbosityTriggeredHere = false;
if (( ! m_triggeredVerbosity) && field.equals(m_triggerForVerbosity)) {
System.out.println("DEBUG VERBOSE diffRecursively verbosity (triggered by field '" + field + "' is ON");
verbosityTriggeredHere = true;
m_triggeredVerbosity = true;
}
// check if the types are different
// options are: both null => same
// one null and one not => different
// both not null => check Object.equals()
Object prevValue = prevType.getField(field);
Object newValue = newType.getField(field);
if ((prevValue == null) != (newValue == null)) {
if (m_triggeredVerbosity) {
if (prevValue == null) {
System.out.println("DEBUG VERBOSE diffRecursively found new '" + field + "' only.");
} else {
System.out.println("DEBUG VERBOSE diffRecursively found prev '" + field + "' only.");
}
}
writeModification(newType, prevType, field);
}
// if they're both not null (above/below ifs implies this)
else if (prevValue != null) {
// if comparing CatalogTypes (both must be same)
if (prevValue instanceof CatalogType) {
assert(newValue instanceof CatalogType);
String prevPath = ((CatalogType) prevValue).getPath();
String newPath = ((CatalogType) newValue).getPath();
if (prevPath.compareTo(newPath) != 0) {
if (m_triggeredVerbosity) {
int padWidth = StringUtils.indexOfDifference(prevPath, newPath);
String pad = StringUtils.repeat(" ", padWidth);
System.out.println("DEBUG VERBOSE diffRecursively found a path change to '" + field + "':");
System.out.println("DEBUG VERBOSE prevPath=" + prevPath);
System.out.println("DEBUG VERBOSE diff at->" + pad + "^ position:" + padWidth);
System.out.println("DEBUG VERBOSE newPath=" + newPath);
}
writeModification(newType, prevType, field);
}
}
// if scalar types
else {
if (prevValue.equals(newValue) == false) {
if (m_triggeredVerbosity) {
System.out.println("DEBUG VERBOSE diffRecursively found a scalar change to '" + field + "':");
System.out.println("DEBUG VERBOSE diffRecursively prev:" + prevValue);
System.out.println("DEBUG VERBOSE diffRecursively new :" + newValue);
}
writeModification(newType, prevType, field);
}
}
}
if (verbosityTriggeredHere) {
System.out.println("DEBUG VERBOSE diffRecursively verbosity is OFF");
m_triggeredVerbosity = false;
}
}
// recurse
for (String field : prevType.m_childCollections.keySet()) {
boolean verbosityTriggeredHere = false;
if (field.equals(m_triggerForVerbosity)) {
System.out.println("DEBUG VERBOSE diffRecursively verbosity ON");
m_triggeredVerbosity = true;
verbosityTriggeredHere = true;
}
CatalogMap<? extends CatalogType> prevMap = prevType.m_childCollections.get(field);
CatalogMap<? extends CatalogType> newMap = newType.m_childCollections.get(field);
getCommandsToDiff(field, prevMap, newMap);
if (verbosityTriggeredHere) {
System.out.println("DEBUG VERBOSE diffRecursively verbosity OFF");
m_triggeredVerbosity = false;
}
}
if (materializerValue != null) {
// Just getting back from recursing into a materialized view table,
// so drop the strictness required only in that context.
// It's safe to assume that the prior mode to which this must pop back is the non-strict
// mode because nesting of table definitions is unpossible AND we guarded against its
// potential side effects, above, anyway.
m_inStrictMatViewDiffMode = false;
}
}
/**
* Check if all the children in prevMap are present and identical in newMap.
* Then, check if anything is in newMap that isn't in prevMap.
* @param mapName
* @param prevMap
* @param newMap
*/
private void getCommandsToDiff(String mapName,
CatalogMap<? extends CatalogType> prevMap,
CatalogMap<? extends CatalogType> newMap)
{
assert(prevMap != null);
assert(newMap != null);
// in previous, not in new
for (CatalogType prevType : prevMap) {
String name = prevType.getTypeName();
CatalogType newType = newMap.get(name);
if (newType == null) {
writeDeletion(prevType, newMap.m_parent, mapName, name);
continue;
}
diffRecursively(prevType, newType);
}
// in new, not in previous
for (CatalogType newType : newMap) {
CatalogType prevType = prevMap.get(newType.getTypeName());
if (prevType != null) continue;
writeAddition(newType);
}
}
// Code below this point helps generate human-readable diffs, but
// should have no functional impact on anything else.
/**
* Enum used to break up the catalog tree into sub-roots based on CatalogType
* class. This is purely used for printing human readable summaries.
*/
enum DiffClass {
PROC (Procedure.class),
TABLE (Table.class),
USER (User.class),
GROUP (Group.class),
//CONNECTOR (Connector.class),
//SCHEDULE (SnapshotSchedule.class),
//CLUSTER (Cluster.class),
OTHER (Catalog.class); // catch all for even the commented stuff above
final Class<?> clz;
DiffClass(Class<?> clz) {
this.clz = clz;
}
static DiffClass get(CatalogType type) {
// this exits because eventually OTHER will catch everything
while (true) {
for (DiffClass dc : DiffClass.values()) {
if (type.getClass() == dc.clz) {
return dc;
}
}
type = type.getParent();
}
}
}
interface Filter {
public boolean include(CatalogType type);
}
interface Namer {
public String getName(CatalogType type);
}
private boolean basicMetaChangeDesc(StringBuilder sb, String heading, DiffClass dc, Filter filter, Namer namer) {
CatalogChangeGroup group = m_changes.get(dc);
// exit if nothing has changed
if ((group.groupChanges.size() == 0) && (group.groupAdditions.size() == 0) && (group.groupDeletions.size() == 0)) {
return false;
}
// default namer uses simplename
if (namer == null) {
namer = new Namer() {
@Override
public String getName(CatalogType type) {
return type.getClass().getSimpleName() + " " + type.getTypeName();
}
};
}
sb.append(heading).append("\n");
for (CatalogType type : group.groupDeletions) {
if ((filter != null) && !filter.include(type)) continue;
sb.append(String.format(" %s dropped.\n",
namer.getName(type)));
}
for (CatalogType type : group.groupAdditions) {
if ((filter != null) && !filter.include(type)) continue;
sb.append(String.format(" %s added.\n",
namer.getName(type)));
}
for (Entry<CatalogType, TypeChanges> entry : group.groupChanges.entrySet()) {
if ((filter != null) && !filter.include(entry.getKey())) continue;
sb.append(String.format(" %s has been modified.\n",
namer.getName(entry.getKey())));
}
sb.append("\n");
return true;
}
// track adds/drops/modifies in a secondary structure to make human readable descriptions
private final Map<DiffClass, CatalogChangeGroup> m_changes = new TreeMap<DiffClass, CatalogChangeGroup>();
/**
* Get a human readable list of changes between two catalogs.
*
* This currently handles just the basics, but much of the plumbing is
* in place to give a lot more detail, with a bit more work.
*/
public String getDescriptionOfChanges() {
StringBuilder sb = new StringBuilder();
sb.append("Catalog Difference Report\n");
sb.append("=========================\n");
if (supported()) {
sb.append(" This change can occur while the database is running.\n");
if (requiresSnapshotIsolation()) {
sb.append(" This change must occur when no snapshot is running.\n");
sb.append(" If a snapshot is in progress, the system will wait \n" +
" until the snapshot is complete to make the changes.\n");
}
}
else {
sb.append(" Making this change requires stopping and restarting the database.\n");
}
sb.append("\n");
boolean wroteChanges = false;
// DESCRIBE TABLE CHANGES
Namer tableNamer = new Namer() {
@Override
public String getName(CatalogType type) {
Table table = (Table) type;
// check if view
// note, this has to be pretty raw to avoid some smarts that wont work
// in this context. this may return an unresolved link which points nowhere,
// but that's good enough to know it's a view
if (table.m_fields.get("materializer") != null) {
return "View " + type.getTypeName();
}
// check if export table
// this probably doesn't work due to the same kinds of problesm we have
// when identifying views. Tables just need a field that says if they
// are export tables or not... ugh. FIXME
for (Connector c : ((Database) table.getParent()).getConnectors()) {
for (ConnectorTableInfo cti : c.getTableinfo()) {
if (cti.getTable() == table) {
return "Export Table " + type.getTypeName();
}
}
}
// just a regular table
return "Table " + type.getTypeName();
}
};
wroteChanges |= basicMetaChangeDesc(sb, "TABLE CHANGES:", DiffClass.TABLE, null, tableNamer);
// DESCRIBE PROCEDURE CHANGES
Filter crudProcFilter = new Filter() {
@Override
public boolean include(CatalogType type) {
if (type.getTypeName().endsWith(".select")) return false;
if (type.getTypeName().endsWith(".insert")) return false;
if (type.getTypeName().endsWith(".delete")) return false;
if (type.getTypeName().endsWith(".update")) return false;
return true;
}
};
wroteChanges |= basicMetaChangeDesc(sb, "PROCEDURE CHANGES:", DiffClass.PROC, crudProcFilter, null);
// DESCRIBE GROUP CHANGES
wroteChanges |= basicMetaChangeDesc(sb, "GROUP CHANGES:", DiffClass.GROUP, null, null);
// DESCRIBE OTHER CHANGES
CatalogChangeGroup group = m_changes.get(DiffClass.OTHER);
if (group.groupChanges.size() > 0) {
wroteChanges = true;
sb.append("OTHER CHANGES:\n");
assert(group.groupAdditions.size() == 0);
assert(group.groupDeletions.size() == 0);
for (TypeChanges metaChanges : group.groupChanges.values()) {
for (CatalogType type : metaChanges.typeAdditions) {
sb.append(String.format(" Catalog node %s of type %s has been added.\n",
type.getTypeName(), type.getClass().getSimpleName()));
}
for (CatalogType type : metaChanges.typeDeletions) {
sb.append(String.format(" Catalog node %s of type %s has been removed.\n",
type.getTypeName(), type.getClass().getSimpleName()));
}
for (FieldChange fc : metaChanges.childChanges.values()) {
sb.append(String.format(" Catalog node %s of type %s has modified metadata.\n",
fc.newType.getTypeName(), fc.newType.getClass().getSimpleName()));
}
}
}
if (!wroteChanges) {
sb.append(" No changes detected.\n");
}
// trim the last newline
sb.setLength(sb.length() - 1);
return sb.toString();
}
}
|
package uk.ac.ebi.quickgo.geneproduct.service.converter;
import uk.ac.ebi.quickgo.geneproduct.common.document.GeneProductDocument;
import uk.ac.ebi.quickgo.geneproduct.common.document.GeneProductType;
import uk.ac.ebi.quickgo.geneproduct.model.GeneProduct;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.IsEqual.equalTo;
public class GeneProductDocConverterTest {
public static final String ID = "A0A000";
private static final int TAX_ID = 789;
private static final String DATABASE = "UniProt";
private static final String SYMBOL = "G12345";
private static final String TAX_NAME = "Streptomyces ghanaensis";
private static final String TYPE = "protein";
private static final String NAME = "moeA5";
private static final String PARENT_ID = "QWERTY";
private static final String REF_PROTEOME = "P1234";
private static final List<String> DATABASE_SUBSETS = Arrays.asList("SUB1", "SUB2");
private static final List<String> SYNONYMS = Arrays.asList("Q1234", "R1234", "S1234");
private GeneProductDocConverter geneProductDocConverter;
private GeneProductDocument geneProductDocument;
@Before
public void setup() {
geneProductDocConverter = new GeneProductDocConverterImpl();
geneProductDocument = new GeneProductDocument();
//14 members
geneProductDocument.id = ID;
geneProductDocument.database = DATABASE;
geneProductDocument.databaseSubsets = DATABASE_SUBSETS;
geneProductDocument.isAnnotated = true;
geneProductDocument.synonyms = SYNONYMS;
geneProductDocument.isIsoform = true;
geneProductDocument.name = NAME;
geneProductDocument.referenceProteome = REF_PROTEOME;
geneProductDocument.isCompleteProteome = true;
geneProductDocument.parentId = PARENT_ID;
geneProductDocument.symbol = SYMBOL;
geneProductDocument.taxonId = TAX_ID;
geneProductDocument.taxonName = TAX_NAME;
geneProductDocument.type = TYPE;
}
@Test
public void convertOne() {
GeneProduct convertedGeneProduct = geneProductDocConverter.convert(geneProductDocument);
assertThat(convertedGeneProduct.id, is(equalTo(ID)));
assertThat(convertedGeneProduct.database, is(equalTo(DATABASE)));
assertThat(convertedGeneProduct.databaseSubset, containsInAnyOrder("SUB1", "SUB2"));
assertThat(convertedGeneProduct.synonyms, containsInAnyOrder("Q1234", "R1234", "S1234"));
assertThat(convertedGeneProduct.isIsoform, is(true));
assertThat(convertedGeneProduct.name, is(NAME));
assertThat(convertedGeneProduct.referenceProteome, is(REF_PROTEOME));
assertThat(convertedGeneProduct.isCompleteProteome, is(true));
assertThat(convertedGeneProduct.parentId, is(PARENT_ID));
assertThat(convertedGeneProduct.symbol, is(SYMBOL));
assertThat(convertedGeneProduct.taxonomy.id, is(TAX_ID));
assertThat(convertedGeneProduct.taxonomy.name, is(TAX_NAME));
assertThat(convertedGeneProduct.type, is(GeneProductType.PROTEIN));
assertThat(convertedGeneProduct.isAnnotated, is(true));
}
@Test
public void thereIsNoTaxId() {
geneProductDocument.taxonId = 0;
GeneProduct convertedGeneProduct = geneProductDocConverter.convert(geneProductDocument);
assertThat(convertedGeneProduct.taxonomy, is(nullValue()));
}
}
|
package com.topcat.npclib;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import net.minecraft.server.v1_7_R4.Entity;
import net.minecraft.server.v1_7_R4.PlayerInteractManager;
import net.minecraft.util.com.mojang.authlib.GameProfile;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftEntity;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.plugin.java.JavaPlugin;
import com.topcat.npclib.entity.HumanNPC;
import com.topcat.npclib.entity.NPC;
import com.topcat.npclib.nms.BServer;
import com.topcat.npclib.nms.BWorld;
import com.topcat.npclib.nms.NPCEntity;
import com.topcat.npclib.nms.NPCNetworkManager;
/**
*
* @author martin
*/
public class NPCManager {
private HashMap<UUID, NPC> npcs = new HashMap<UUID, NPC>();
private BServer server;
private Map<World, BWorld> bworlds = new HashMap<World, BWorld>();
private NPCNetworkManager npcNetworkManager;
public static JavaPlugin plugin;
public NPCManager(JavaPlugin plugin) {
server = BServer.getInstance();
try {
npcNetworkManager = new NPCNetworkManager(false);
} catch (IOException e) {
e.printStackTrace();
}
NPCManager.plugin = plugin;
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override
public void run() {
HashSet<UUID> toRemove = new HashSet<UUID>();
for (UUID i : npcs.keySet()) {
Entity j = npcs.get(i).getEntity();
j.C();
if (j.dead) {
toRemove.add(i);
}
}
for (UUID n : toRemove) {
npcs.remove(n);
}
}
}, 1L, 1L);
Bukkit.getServer().getPluginManager().registerEvents(new WL(), plugin);
}
public BWorld getBWorld(World world) {
BWorld bworld = bworlds.get(world);
if (bworld != null) {
return bworld;
}
bworld = new BWorld(world);
bworlds.put(world, bworld);
return bworld;
}
private class WL implements Listener {
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
for (NPC npc : npcs.values()) {
if (npc != null && event.getChunk() == npc.getBukkitEntity().getLocation().getBlock().getChunk()) {
BWorld world = getBWorld(event.getWorld());
if(world.getWorldServer().getEntity(npc.getEntity().getId()) != npc.getEntity()){ //ATTEMPT TO ERRADICATE ENTITY TRACKING ERROR (WORKS IN NORMAL BUKKIT)
world.getWorldServer().addEntity(npc.getEntity());
}
}
}
}
}
public GameProfile setGameProfile(String name){
UUID uuid = UUID.randomUUID();
uuid = new UUID(uuid.getMostSignificantBits() | 0x0000000000005000L, uuid.getLeastSignificantBits());
while(Bukkit.getServer().getPlayer(uuid) != null){
uuid = new UUID(uuid.getMostSignificantBits() | 0x0000000000005000L, uuid.getLeastSignificantBits());
}
return new GameProfile(uuid, name);
}
public NPC spawnHumanNPC(String name, Location l, UUID id) {
if (npcs.containsKey(id)) {
server.getLogger().log(Level.WARNING, "NPC with that id already exists, existing NPC returned");
return npcs.get(id);
} else {
if (name.length() > 16) { // Check and nag if name is too long, spawn NPC anyway with shortened name.
String tmp = name.substring(0, 16);
server.getLogger().log(Level.WARNING, "NPCs can't have names longer than 16 characters,");
server.getLogger().log(Level.WARNING, name + " has been shortened to " + tmp);
name = tmp;
}
BWorld world = getBWorld(l.getWorld());
NPCEntity npcEntity = new NPCEntity(this, world, setGameProfile(name), new PlayerInteractManager(world.getWorldServer()));
npcEntity.setPositionRotation(l.getX(), l.getY(), l.getZ(), l.getYaw(), l.getPitch());
world.getWorldServer().addEntity(npcEntity); //the right way
NPC npc = new HumanNPC(npcEntity);
npcs.put(id, npc);
return npc;
}
}
public void despawnById(UUID playerUUID) {
NPC npc = npcs.get(playerUUID);
if (npc != null) {
npcs.remove(playerUUID);
npc.removeFromWorld();
}
}
public void despawnHumanByName(String npcName) {
if (npcName.length() > 16) {
npcName = npcName.substring(0, 16); //Ensure you can still despawn
}
HashSet<UUID> toRemove = new HashSet<UUID>();
for (UUID n : npcs.keySet()) {
NPC npc = npcs.get(n);
if (npc instanceof HumanNPC) {
if (npc != null && ((HumanNPC) npc).getName().equals(npcName)) {
toRemove.add(n);
npc.removeFromWorld();
}
}
}
for (UUID n : toRemove) {
npcs.remove(n);
}
}
public NPC getNPC(UUID playerUUID) {
return npcs.get(playerUUID);
}
public boolean isNPC(org.bukkit.entity.Entity e) {
return ((CraftEntity) e).getHandle() instanceof NPCEntity;
}
public List<NPC> getNPCs() {
return new ArrayList<NPC>(npcs.values());
}
public UUID getNPCIdFromEntity(org.bukkit.entity.Entity e) {
if (e instanceof HumanEntity) {
for (UUID i : npcs.keySet()) {
if (npcs.get(i).getBukkitEntity().getEntityId() == ((HumanEntity) e).getEntityId()) {
return i;
}
}
}
return null;
}
public BServer getServer() {
return server;
}
public NPCNetworkManager getNPCNetworkManager() {
return npcNetworkManager;
}
}
|
package cc.mallet.topics;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.*;
import java.util.zip.*;
import java.io.*;
import java.text.NumberFormat;
import cc.mallet.types.*;
import cc.mallet.topics.TopicAssignment;
import cc.mallet.util.Randoms;
/**
* Simple parallel threaded implementation of LDA,
* following the UCI NIPS paper.
*
* @author David Mimno, Andrew McCallum
*/
public class ParallelTopicModel {
protected ArrayList<TopicAssignment> data; // the training instances and their topic assignments
protected Alphabet alphabet; // the alphabet for the input data
protected LabelAlphabet topicAlphabet; // the alphabet for the topics
protected int numTopics; // Number of topics to be fit
// These values are used to encode type/topic counts as
// count/topic pairs in a single int.
protected int topicMask;
protected int topicBits;
protected int numTypes;
protected double[] alpha; // Dirichlet(alpha,alpha,...) is the distribution over topics
protected double alphaSum;
protected double beta; // Prior on per-topic multinomial distribution over words
protected double betaSum;
public static final double DEFAULT_BETA = 0.01;
protected int[][] typeTopicCounts; // indexed by <feature index, topic index>
protected int[] tokensPerTopic; // indexed by <topic index>
// for dirichlet estimation
protected int[] docLengthCounts; // histogram of document sizes
protected int[][] topicDocCounts; // histogram of document/topic counts, indexed by <topic index, sequence position index>
public int numIterations = 1000;
public int burninPeriod = 200;
public int saveSampleInterval = 10;
public int optimizeInterval = 50;
public int showTopicsInterval = 50;
public int wordsPerTopic = 7;
protected int saveStateInterval = 0;
protected String stateFilename = null;
protected Randoms random;
protected NumberFormat formatter;
protected boolean printLogLikelihood = false;
int numThreads = 1;
public ParallelTopicModel (int numberOfTopics) {
this (numberOfTopics, numberOfTopics, DEFAULT_BETA);
}
public ParallelTopicModel (int numberOfTopics, double alphaSum, double beta) {
this (numberOfTopics, alphaSum, beta, new Randoms());
}
private static LabelAlphabet newLabelAlphabet (int numTopics) {
LabelAlphabet ret = new LabelAlphabet();
for (int i = 0; i < numTopics; i++)
ret.lookupIndex("topic"+i);
return ret;
}
public ParallelTopicModel (int numberOfTopics, double alphaSum, double beta, Randoms random) {
this (newLabelAlphabet (numberOfTopics), alphaSum, beta, random);
}
public ParallelTopicModel (LabelAlphabet topicAlphabet, double alphaSum, double beta, Randoms random)
{
this.data = new ArrayList<TopicAssignment>();
this.topicAlphabet = topicAlphabet;
this.numTopics = topicAlphabet.size();
if (Integer.bitCount(numTopics) == 1) {
// exact power of 2
topicMask = numTopics - 1;
topicBits = Integer.bitCount(topicMask);
}
else {
// otherwise add an extra bit
topicMask = Integer.highestOneBit(numTopics) * 2 - 1;
topicBits = Integer.bitCount(topicMask);
}
this.alphaSum = alphaSum;
this.alpha = new double[numTopics];
Arrays.fill(alpha, alphaSum / numTopics);
this.beta = beta;
this.random = random;
tokensPerTopic = new int[numTopics];
formatter = NumberFormat.getInstance();
formatter.setMaximumFractionDigits(5);
System.err.println("Coded LDA: " + numTopics + " topics, " + topicBits + " topic bits, " +
Integer.toBinaryString(topicMask) + " topic mask");
}
public Alphabet getAlphabet() { return alphabet; }
public LabelAlphabet getTopicAlphabet() { return topicAlphabet; }
public int getNumTopics() { return numTopics; }
public ArrayList<TopicAssignment> getData() { return data; }
public void setNumIterations (int numIterations) {
this.numIterations = numIterations;
}
public void setBurninPeriod (int burninPeriod) {
this.burninPeriod = burninPeriod;
}
public void setTopicDisplay(int interval, int n) {
this.showTopicsInterval = interval;
this.wordsPerTopic = n;
}
public void setRandomSeed(int seed) {
random = new Randoms(seed);
}
public void setOptimizeInterval(int interval) {
this.optimizeInterval = interval;
}
public void setNumThreads(int threads) {
this.numThreads = threads;
}
/** Define how often and where to save the state
*
* @param interval Save a copy of the state every <code>interval</code> iterations.
* @param filename Save the state to this file, with the iteration number as a suffix
*/
public void setSaveState(int interval, String filename) {
this.saveStateInterval = interval;
this.stateFilename = filename;
}
public void addInstances (InstanceList training) {
alphabet = training.getDataAlphabet();
numTypes = alphabet.size();
betaSum = beta * numTypes;
typeTopicCounts = new int[numTypes][];
// Get the total number of occurrences of each word type
int[] typeTotals = new int[numTypes];
int doc = 0;
for (Instance instance : training) {
doc++;
FeatureSequence tokens = (FeatureSequence) instance.getData();
for (int position = 0; position < tokens.getLength(); position++) {
int type = tokens.getIndexAtPosition(position);
typeTotals[ type ]++;
}
}
// Allocate enough space so that we never have to worry about
// overflows: either the number of topics or the number of times
// the type occurs.
for (int type = 0; type < numTypes; type++) {
typeTopicCounts[type] = new int[ Math.min(numTopics, typeTotals[type]) ];
}
doc = 0;
for (Instance instance : training) {
doc++;
FeatureSequence tokens = (FeatureSequence) instance.getData();
LabelSequence topicSequence =
new LabelSequence(topicAlphabet, new int[ tokens.size() ]);
int[] topics = topicSequence.getFeatures();
for (int position = 0; position < topics.length; position++) {
int topic = random.nextInt(numTopics);
topics[position] = topic;
}
TopicAssignment t = new TopicAssignment (instance, topicSequence);
data.add (t);
}
buildInitialTypeTopicCounts();
initializeHistograms();
}
public void buildInitialTypeTopicCounts () {
// Clear the topic totals
Arrays.fill(tokensPerTopic, 0);
// Clear the type/topic counts, only
// looking at the entries before the first 0 entry.
for (int type = 0; type < numTypes; type++) {
int[] topicCounts = typeTopicCounts[type];
int position = 0;
while (position < topicCounts.length &&
topicCounts[position] > 0) {
topicCounts[position] = 0;
position++;
}
}
for (TopicAssignment document : data) {
FeatureSequence tokens = (FeatureSequence) document.instance.getData();
FeatureSequence topicSequence = (FeatureSequence) document.topicSequence;
int[] topics = topicSequence.getFeatures();
for (int position = 0; position < tokens.size(); position++) {
int topic = topics[position];
tokensPerTopic[topic]++;
// The format for these arrays is
// the topic in the rightmost bits
// the count in the remaining (left) bits.
// Since the count is in the high bits, sorting (desc)
// by the numeric value of the int guarantees that
// higher counts will be before the lower counts.
int type = tokens.getIndexAtPosition(position);
int[] currentTypeTopicCounts = typeTopicCounts[ type ];
// Start by assuming that the array is either empty
// or is in sorted (descending) order.
// Here we are only adding counts, so if we find
// an existing location with the topic, we only need
// to ensure that it is not larger than its left neighbor.
int index = 0;
int currentTopic = currentTypeTopicCounts[index] & topicMask;
int currentValue;
while (currentTypeTopicCounts[index] > 0 && currentTopic != topic) {
index++;
if (index == currentTypeTopicCounts.length) {
System.out.println("overflow on type " + type);
}
currentTopic = currentTypeTopicCounts[index] & topicMask;
}
currentValue = currentTypeTopicCounts[index] >> topicBits;
if (currentValue == 0) {
// new value is 1, so we don't have to worry about sorting
// (except by topic suffix, which doesn't matter)
currentTypeTopicCounts[index] =
(1 << topicBits) + topic;
}
else {
currentTypeTopicCounts[index] =
((currentValue + 1) << topicBits) + topic;
// Now ensure that the array is still sorted by
// bubbling this value up.
while (index > 0 &&
currentTypeTopicCounts[index] > currentTypeTopicCounts[index - 1]) {
int temp = currentTypeTopicCounts[index];
currentTypeTopicCounts[index] = currentTypeTopicCounts[index - 1];
currentTypeTopicCounts[index - 1] = temp;
index
}
}
}
}
}
public void sumTypeTopicCounts (WorkerRunnable[] runnables) {
// Clear the topic totals
Arrays.fill(tokensPerTopic, 0);
// Clear the type/topic counts, only
// looking at the entries before the first 0 entry.
for (int type = 0; type < numTypes; type++) {
int[] targetCounts = typeTopicCounts[type];
int position = 0;
while (position < targetCounts.length &&
targetCounts[position] > 0) {
targetCounts[position] = 0;
position++;
}
}
for (int thread = 0; thread < numThreads; thread++) {
// Handle the total-tokens-per-topic array
int[] sourceTotals = runnables[thread].getTokensPerTopic();
for (int topic = 0; topic < numTopics; topic++) {
tokensPerTopic[topic] += sourceTotals[topic];
}
// Now handle the individual type topic counts
int[][] sourceTypeTopicCounts =
runnables[thread].getTypeTopicCounts();
for (int type = 0; type < numTypes; type++) {
// Here the source is the individual thread counts,
// and the target is the global counts.
int[] sourceCounts = sourceTypeTopicCounts[type];
int[] targetCounts = typeTopicCounts[type];
int sourceIndex = 0;
while (sourceIndex < sourceCounts.length &&
sourceCounts[sourceIndex] > 0) {
int topic = sourceCounts[sourceIndex] & topicMask;
int count = sourceCounts[sourceIndex] >> topicBits;
int targetIndex = 0;
int currentTopic = targetCounts[targetIndex] & topicMask;
int currentCount;
while (targetCounts[targetIndex] > 0 && currentTopic != topic) {
targetIndex++;
if (targetIndex == targetCounts.length) {
System.out.println("overflow in merging on type " + type);
}
currentTopic = targetCounts[targetIndex] & topicMask;
}
currentCount = targetCounts[targetIndex] >> topicBits;
targetCounts[targetIndex] =
((currentCount + count) << topicBits) + topic;
// Now ensure that the array is still sorted by
// bubbling this value up.
while (targetIndex > 0 &&
targetCounts[targetIndex] > targetCounts[targetIndex - 1]) {
int temp = targetCounts[targetIndex];
targetCounts[targetIndex] = targetCounts[targetIndex - 1];
targetCounts[targetIndex - 1] = temp;
targetIndex
}
sourceIndex++;
}
}
}
}
/**
* Gather statistics on the size of documents
* and create histograms for use in Dirichlet hyperparameter
* optimization.
*/
private void initializeHistograms() {
int maxTokens = 0;
int totalTokens = 0;
int seqLen;
for (int doc = 0; doc < data.size(); doc++) {
FeatureSequence fs = (FeatureSequence) data.get(doc).instance.getData();
seqLen = fs.getLength();
if (seqLen > maxTokens)
maxTokens = seqLen;
totalTokens += seqLen;
}
System.err.println("max tokens: " + maxTokens);
System.err.println("total tokens: " + totalTokens);
docLengthCounts = new int[maxTokens + 1];
topicDocCounts = new int[numTopics][maxTokens + 1];
}
public void optimizeAlpha(WorkerRunnable[] runnables) {
// First clear the sufficient statistic histograms
Arrays.fill(docLengthCounts, 0);
for (int topic = 0; topic < topicDocCounts.length; topic++) {
Arrays.fill(topicDocCounts[topic], 0);
}
for (int thread = 0; thread < numThreads; thread++) {
int[] sourceLengthCounts = runnables[thread].getDocLengthCounts();
int[][] sourceTopicCounts = runnables[thread].getTopicDocCounts();
for (int count=0; count < sourceLengthCounts.length; count++) {
if (sourceLengthCounts[count] > 0) {
docLengthCounts[count] += sourceLengthCounts[count];
sourceLengthCounts[count] = 0;
}
}
for (int topic=0; topic < numTopics; topic++) {
for (int count=0; count < sourceTopicCounts[topic].length; count++) {
if (sourceTopicCounts[topic][count] > 0) {
topicDocCounts[topic][count] += sourceTopicCounts[topic][count];
sourceTopicCounts[topic][count] = 0;
}
}
}
}
alphaSum = Dirichlet.learnParameters(alpha, topicDocCounts, docLengthCounts);
}
public void estimate () throws IOException {
long startTime = System.currentTimeMillis();
WorkerRunnable[] runnables = new WorkerRunnable[numThreads];
int docsPerThread = data.size() / numThreads;
int offset = 0;
for (int thread = 0; thread < numThreads; thread++) {
int[] runnableTotals = new int[numTopics];
System.arraycopy(tokensPerTopic, 0, runnableTotals, 0, numTopics);
int[][] runnableCounts = new int[numTypes][];
for (int type = 0; type < numTypes; type++) {
int[] counts = new int[typeTopicCounts[type].length];
System.arraycopy(typeTopicCounts[type], 0, counts, 0, counts.length);
runnableCounts[type] = counts;
}
// some docs may be missing at the end due to integer division
if (thread == numThreads - 1) {
docsPerThread = data.size() - offset;
}
runnables[thread] = new WorkerRunnable(numTopics,
alpha, alphaSum, beta,
new Randoms(), data,
runnableCounts, runnableTotals,
offset, docsPerThread);
runnables[thread].initializeAlphaStatistics(docLengthCounts.length);
offset += docsPerThread;
}
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
for (int iteration = 1; iteration <= numIterations; iteration++) {
long iterationStart = System.currentTimeMillis();
if (showTopicsInterval != 0 && iteration != 0 && iteration % showTopicsInterval == 0) {
System.out.println();
printTopWords (System.out, wordsPerTopic, false);
}
if (saveStateInterval != 0 && iteration % saveStateInterval == 0) {
this.printState(new File(stateFilename + '.' + iteration));
}
// Submit runnables to thread pool
for (int thread = 0; thread < numThreads; thread++) {
if (iteration > burninPeriod && optimizeInterval != 0 &&
iteration % saveSampleInterval == 0) {
runnables[thread].collectAlphaStatistics();
}
executor.submit(runnables[thread]);
//runnables[thread].run();
}
// I'm getting some problems that look like
// a thread hasn't started yet when it is first
// polled, so it appears to be finished.
// This only occurs in very short corpora.
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
boolean finished = false;
while (! finished) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
finished = true;
// Are all the threads done?
for (int thread = 0; thread < numThreads; thread++) {
//System.out.println("thread " + thread + " done? " + runnables[thread].isFinished);
finished = finished && runnables[thread].isFinished;
}
}
if (iteration > burninPeriod && optimizeInterval != 0 &&
iteration % optimizeInterval == 0) {
optimizeAlpha(runnables);
System.out.print("[O " + (System.currentTimeMillis() - iterationStart) + "] ");
}
System.out.print("[" + (System.currentTimeMillis() - iterationStart) + "] ");
sumTypeTopicCounts(runnables);
System.out.print("[" + (System.currentTimeMillis() - iterationStart) + "] ");
for (int thread = 0; thread < numThreads; thread++) {
int[] runnableTotals = runnables[thread].getTokensPerTopic();
System.arraycopy(tokensPerTopic, 0, runnableTotals, 0, numTopics);
int[][] runnableCounts = runnables[thread].getTypeTopicCounts();
for (int type = 0; type < numTypes; type++) {
int[] targetCounts = runnableCounts[type];
int[] sourceCounts = typeTopicCounts[type];
int index = 0;
while (index < sourceCounts.length) {
if (sourceCounts[index] != 0) {
targetCounts[index] = sourceCounts[index];
}
else if (targetCounts[index] != 0) {
targetCounts[index] = 0;
}
else {
break;
}
index++;
}
//System.arraycopy(typeTopicCounts[type], 0, counts, 0, counts.length);
}
}
long elapsedMillis = System.currentTimeMillis() - iterationStart;
if (elapsedMillis < 1000) {
System.out.print(elapsedMillis + "ms ");
}
else {
System.out.print((elapsedMillis/1000) + "s ");
}
if (iteration % 10 == 0) {
System.out.println ("<" + iteration + "> ");
if (printLogLikelihood) System.out.println (modelLogLikelihood());
}
System.out.flush();
}
executor.shutdownNow();
long seconds = Math.round((System.currentTimeMillis() - startTime)/1000.0);
long minutes = seconds / 60; seconds %= 60;
long hours = minutes / 60; minutes %= 60;
long days = hours / 24; hours %= 24;
System.out.print ("\nTotal time: ");
if (days != 0) { System.out.print(days); System.out.print(" days "); }
if (hours != 0) { System.out.print(hours); System.out.print(" hours "); }
if (minutes != 0) { System.out.print(minutes); System.out.print(" minutes "); }
System.out.print(seconds); System.out.println(" seconds");
}
public void printTopWords (File file, int numWords, boolean useNewLines) throws IOException {
PrintStream out = new PrintStream (file);
printTopWords(out, numWords, useNewLines);
out.close();
}
public void printTopWords (PrintStream out, int numWords, boolean usingNewLines) {
FeatureCounter[] wordCountsPerTopic = new FeatureCounter[numTopics];
for (int topic = 0; topic < numTopics; topic++) {
wordCountsPerTopic[topic] = new FeatureCounter(alphabet);
}
for (int type = 0; type < numTypes; type++) {
int[] topicCounts = typeTopicCounts[type];
int index = 0;
while (index < topicCounts.length &&
topicCounts[index] > 0) {
int topic = topicCounts[index] & topicMask;
int count = topicCounts[index] >> topicBits;
wordCountsPerTopic[topic].increment(type, count);
index++;
}
}
for (int topic = 0; topic < numTopics; topic++) {
RankedFeatureVector rfv = wordCountsPerTopic[topic].toRankedFeatureVector();
if (usingNewLines) {
out.println ("Topic " + topic);
int max = rfv.numLocations(); if (max > numWords) max = numWords;
for (int ri = 0; ri < max; ri++) {
int type = rfv.getIndexAtRank(ri);
out.println (alphabet.lookupObject(type).toString()+"\t"+(int)rfv.getValueAtRank(ri));
}
} else {
out.print (topic + "\t" + formatter.format(alpha[topic]) + "\t");
for (int ri = 0; ri < numWords; ri++)
out.print (alphabet.lookupObject(rfv.getIndexAtRank(ri)).toString()+" ");
out.print ("\n");
}
}
}
public void printDocumentTopics (File f) throws IOException {
printDocumentTopics (new PrintWriter (new FileWriter (f) ) );
}
public void printDocumentTopics (PrintWriter pw) {
printDocumentTopics (pw, 0.0, -1);
}
/**
* @param pw A print writer
* @param threshold Only print topics with proportion greater than this number
* @param max Print no more than this many topics
*/
public void printDocumentTopics (PrintWriter pw, double threshold, int max) {
pw.print ("#doc source topic proportion ...\n");
int docLen;
int[] topicCounts = new int[ numTopics ];
IDSorter[] sortedTopics = new IDSorter[ numTopics ];
for (int topic = 0; topic < numTopics; topic++) {
// Initialize the sorters with dummy values
sortedTopics[topic] = new IDSorter(topic, topic);
}
if (max < 0 || max > numTopics) {
max = numTopics;
}
for (int di = 0; di < data.size(); di++) {
LabelSequence topicSequence = (LabelSequence) data.get(di).topicSequence;
int[] currentDocTopics = topicSequence.getFeatures();
pw.print (di); pw.print (' ');
if (data.get(di).instance.getSource() != null) {
pw.print (data.get(di).instance.getSource());
}
else {
pw.print ("null-source");
}
pw.print (' ');
docLen = currentDocTopics.length;
// Count up the tokens
for (int token=0; token < docLen; token++) {
topicCounts[ currentDocTopics[token] ]++;
}
// And normalize
for (int topic = 0; topic < numTopics; topic++) {
sortedTopics[topic].set(topic, (float) topicCounts[topic] / docLen);
}
Arrays.sort(sortedTopics);
for (int i = 0; i < max; i++) {
if (sortedTopics[i].getWeight() < threshold) { break; }
pw.print (sortedTopics[i].getID() + " " +
sortedTopics[i].getWeight() + " ");
}
pw.print (" \n");
Arrays.fill(topicCounts, 0);
}
}
public void printState (File f) throws IOException {
PrintStream out =
new PrintStream(new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(f))));
printState(out);
out.close();
}
public void printState (PrintStream out) {
out.println ("#doc source pos typeindex type topic");
out.print("#alpha : ");
for (int topic = 0; topic < numTopics; topic++) {
out.print(alpha[topic] + " ");
}
out.println();
for (int di = 0; di < data.size(); di++) {
FeatureSequence tokenSequence = (FeatureSequence) data.get(di).instance.getData();
LabelSequence topicSequence = (LabelSequence) data.get(di).topicSequence;
String source = "NA";
if (data.get(di).instance.getSource() != null) {
source = data.get(di).instance.getSource().toString();
}
for (int pi = 0; pi < topicSequence.getLength(); pi++) {
int type = tokenSequence.getIndexAtPosition(pi);
int topic = topicSequence.getIndexAtPosition(pi);
out.print(di); out.print(' ');
out.print(source); out.print(' ');
out.print(pi); out.print(' ');
out.print(type); out.print(' ');
out.print(alphabet.lookupObject(type)); out.print(' ');
out.print(topic); out.println();
}
}
}
public double modelLogLikelihood() {
double logLikelihood = 0.0;
int nonZeroTopics;
// The likelihood of the model is a combination of a
// Dirichlet-multinomial for the words in each topic
// and a Dirichlet-multinomial for the topics in each
// document.
// The likelihood function of a dirichlet multinomial is
// Gamma( sum_i alpha_i ) prod_i Gamma( alpha_i + N_i )
// prod_i Gamma( alpha_i ) Gamma( sum_i (alpha_i + N_i) )
// So the log likelihood is
// logGamma ( sum_i alpha_i ) - logGamma ( sum_i (alpha_i + N_i) ) +
// sum_i [ logGamma( alpha_i + N_i) - logGamma( alpha_i ) ]
// Do the documents first
int[] topicCounts = new int[numTopics];
double[] topicLogGammas = new double[numTopics];
int[] docTopics;
for (int topic=0; topic < numTopics; topic++) {
topicLogGammas[ topic ] = Dirichlet.logGammaStirling( alpha[topic] );
}
for (int doc=0; doc < data.size(); doc++) {
LabelSequence topicSequence = (LabelSequence) data.get(doc).topicSequence;
docTopics = topicSequence.getFeatures();
for (int token=0; token < docTopics.length; token++) {
topicCounts[ docTopics[token] ]++;
}
for (int topic=0; topic < numTopics; topic++) {
if (topicCounts[topic] > 0) {
logLikelihood += (Dirichlet.logGammaStirling(alpha[topic] + topicCounts[topic]) -
topicLogGammas[ topic ]);
}
}
// subtract the (count + parameter) sum term
logLikelihood -= Dirichlet.logGammaStirling(alphaSum + docTopics.length);
Arrays.fill(topicCounts, 0);
}
// add the parameter sum term
logLikelihood += data.size() * Dirichlet.logGammaStirling(alphaSum);
// And the topics
// Count the number of type-topic pairs
int nonZeroTypeTopics = 0;
for (int type=0; type < numTypes; type++) {
// reuse this array as a pointer
topicCounts = typeTopicCounts[type];
int index = 0;
while (index < topicCounts.length &&
topicCounts[index] > 0) {
int topic = topicCounts[index] & topicMask;
int count = topicCounts[index] >> topicBits;
nonZeroTypeTopics++;
logLikelihood += Dirichlet.logGammaStirling(beta + count);
if (Double.isNaN(logLikelihood)) {
System.out.println(count);
System.exit(1);
}
index++;
}
}
for (int topic=0; topic < numTopics; topic++) {
logLikelihood -=
Dirichlet.logGammaStirling( (beta * numTopics) +
tokensPerTopic[ topic ] );
if (Double.isNaN(logLikelihood)) {
System.out.println("after topic " + topic + " " + tokensPerTopic[ topic ]);
System.exit(1);
}
}
logLikelihood +=
(Dirichlet.logGammaStirling(beta * numTopics)) -
(Dirichlet.logGammaStirling(beta) * nonZeroTypeTopics);
if (Double.isNaN(logLikelihood)) {
System.out.println("at the end");
System.exit(1);
}
return logLikelihood;
}
public static void main (String[] args) {
try {
InstanceList training = InstanceList.load (new File(args[0]));
int numTopics = args.length > 1 ? Integer.parseInt(args[1]) : 200;
ParallelTopicModel lda = new ParallelTopicModel (numTopics, 50.0, 0.01);
lda.printLogLikelihood = true;
lda.setTopicDisplay(50, 7);
lda.addInstances(training);
lda.setNumThreads(Integer.parseInt(args[2]));
lda.estimate();
System.out.println("printing state");
lda.printState(new File("state.gz"));
System.out.println("finished printing");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.rho.rubyext;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.media.Player;
import rhomobile.RhodesApplication;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.PopupScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import com.rho.RhoClassFactory;
import com.rho.RhoEmptyLogger;
import com.rho.RhoLogger;
import com.rho.RhodesApp;
import com.rho.file.SimpleFile;
import com.xruby.runtime.builtin.*;
import com.xruby.runtime.lang.*;
public class Alert
{
private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
new RhoLogger("Alert");
public static final RubyID titleID = RubyID.intern("title");
public static final RubyID messageID = RubyID.intern("message");
public static final RubyID iconID = RubyID.intern("icon");
public static final RubyID callbackID = RubyID.intern("callback");
public static final RubyID buttonsID = RubyID.intern("buttons");
public static final RubyID buttonidID = RubyID.intern("id");
public static final RubyID alertTypeID = RubyID.intern("alert");
public static final RubyID questionTypeID = RubyID.intern("question");
public static final RubyID infoTypeID = RubyID.intern("info");
public static void showPopup(final String message)
{
Application.getApplication().invokeLater(new Runnable() {
public void run() {
Application.getApplication().requestForeground();
Dialog.alert(message);
}
});
}
private static String getHashStringValue(RubyHash hash, RubyID id)
{
RubyValue val = hash.get(id.toSymbol());
return val != null && val != RubyConstant.QNIL ? val.toStr() : "";
}
private static class AlertDialog extends PopupScreen {
private static AlertDialog current = null;
private HorizontalFieldManager hfm;
private String callback = null;
public AlertDialog(String title, String msg, String icon, String c) {
super(new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR));
callback = c;
Manager mgr = new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR);
add(mgr);
if (title != null) {
LabelField tf = new LabelField(title, Field.FIELD_HCENTER);
mgr.add(tf);
}
HorizontalFieldManager lfm = new HorizontalFieldManager();
mgr.add(lfm);
Bitmap bmp = null;
if (icon != null) {
if (icon.equalsIgnoreCase(alertTypeID.toString()))
bmp = Bitmap.getPredefinedBitmap(Bitmap.EXCLAMATION);
else if (icon.equalsIgnoreCase(questionTypeID.toString()))
bmp = Bitmap.getPredefinedBitmap(Bitmap.QUESTION);
else if (icon.equalsIgnoreCase(infoTypeID.toString()))
bmp = Bitmap.getPredefinedBitmap(Bitmap.INFORMATION);
// TODO: load bitmap from file
}
if (bmp != null) {
BitmapField bf = new BitmapField(bmp, Field.FIELD_LEFT | Field.FIELD_VCENTER);
lfm.add(bf);
}
LabelField lf = new LabelField(msg, Field.FIELD_HCENTER | Field.FIELD_VCENTER);
lfm.add(lf);
hfm = new HorizontalFieldManager();
mgr.add(hfm);
}
private class Callback implements FieldChangeListener {
private String id;
private String text;
public Callback(String i, String t) {
id = i;
text = t;
}
public void fieldChanged(Field field, int context) {
try {
RhodesApp.getInstance().callPopupCallback(callback, id, text);
} catch (Exception e) {
LOG.ERROR("show_popup callback failed.", e);
}
hide();
}
};
public void addButton(String id, String text) {
ButtonField bf = new ButtonField(text);
bf.setChangeListener(new Callback(id, text));
hfm.add(bf);
}
public void show() {
RhodesApplication app = (RhodesApplication)Application.getApplication();
app.requestForeground();
app.pushScreen(this);
current = this;
}
public void hide() {
RhodesApplication app = (RhodesApplication)Application.getApplication();
app.popScreen(this);
current = null;
}
private static void hidePopup() {
Application.getApplication().invokeLater(new Runnable() {
public void run() {
if (current == null)
return;
current.hide();
current = null;
}
});
}
};
private static class PopupHandler implements Runnable
{
//String m_strMessage = "";
//String m_strCallback = "";
//Vector m_vecButtons = new Vector();
//Vector m_vecIDs = new Vector();
//private static final int atAlert = 1;
//private static final int atQuestion = 2;
//private static final int atInfo = 3;
//int m_nType = 0;
private AlertDialog dialog;
PopupHandler(RubyHash hash)
{
String title = getHashStringValue(hash, titleID );
String msg = getHashStringValue(hash, messageID );
String icon = getHashStringValue(hash, iconID );
String callback = getHashStringValue(hash, callbackID );
dialog = new AlertDialog(title, msg, icon, callback);
RubyValue valButtons = hash.get(buttonsID.toSymbol());
if ( valButtons != null && valButtons instanceof RubyArray )
{
RubyArray arButtons = (RubyArray)valButtons;
for ( int i = 0; i < arButtons.size(); i++ )
{
RubyValue valButton = arButtons.get(i);
if ( valButton != null && valButton instanceof RubyString )
{
String text = valButton.toStr();
dialog.addButton(text, text);
}else if ( valButton != null && valButton instanceof RubyHash )
{
String strLabel = getHashStringValue((RubyHash)valButton, titleID );
if ( strLabel.length() > 0 )
{
String strID = getHashStringValue((RubyHash)valButton, buttonidID );
if ( strID.length() > 0 )
dialog.addButton(strID, strLabel);
else
dialog.addButton(strLabel, strLabel);
}
}
}
}
/*
RubyValue valIcon = hash.get(iconID.toSymbol());
if ( valIcon instanceof RubySymbol )
{
if ( valIcon == alertTypeID.toSymbol() )
m_nType = atAlert;
else if( valIcon == questionTypeID.toSymbol() )
m_nType = atQuestion;
else if( valIcon == infoTypeID.toSymbol() )
m_nType = atInfo;
}else
{
if (m_vecButtons.size() > 0 )
m_nType = atQuestion;
else
m_nType = atInfo;
}
*/
}
public void run() {
dialog.show();
/*
Application.getApplication().requestForeground();
switch( m_nType )
{
case atAlert:
Dialog.alert(m_strMessage);
break;
case atQuestion:
Object[] btns = new Object[m_vecButtons.size()];
m_vecButtons.copyInto(btns);
int nRes = Dialog.ask(m_strMessage,btns,0);
try
{
RhodesApp.getInstance().callPopupCallback(m_strCallback, (String)m_vecIDs.elementAt(nRes),
(String)m_vecButtons.elementAt(nRes));
}catch(Exception exc)
{
LOG.ERROR("show_popup callback failed.", exc);
}
break;
case atInfo:
Dialog.inform(m_strMessage);
break;
}
*/
}
}
public static void vibrate(final String duration)
{
Application.getApplication().invokeLater(new Runnable() {
public void run() {
int dt = 2500;
try {
dt = Integer.parseInt(duration);
} catch (NumberFormatException e) {
}
if (dt > 25500) dt = 25500;
if (dt > 0) {
net.rim.device.api.system.Alert.startVibrate(dt);
}
}
});
}
private static final String[][] filetypes = { {"mp3", "audio/mpeg"}, {"wav","audio/x-wav"} };
private static String getTypeFromExt(String file_name) {
int pt = file_name.lastIndexOf('.');
if (pt<0) {
return filetypes[0][1];
}
String ext = file_name.substring(pt+1);
for (int cnt = filetypes.length - 1; cnt >= 0; --cnt) {
if(filetypes[cnt][0].equals(ext)) {
return filetypes[cnt][1];
}
}
return null;
}
public static void play_file(final String file_name, final String media_type)
{
Application.getApplication().invokeLater(new Runnable()
{
public void run() {
String type = media_type == null ? getTypeFromExt(file_name) : media_type;
if (type != null) {
LOG.INFO("File type: " + type);
} else {
LOG.ERROR("Error - can't play unknown file type");
return;
}
String types[] =
javax.microedition.media.Manager.getSupportedContentTypes(null);
for (int cnt = types.length - 1; cnt >= 0; --cnt) {
if (type.equals(types[cnt])) {
LOG.INFO( "Playing file " + file_name + " of type: " + types[cnt]);
SimpleFile file = null;
try {
//retrieve the file
Class clazz = Class.forName("rhomobile.RhodesApplication");
file = RhoClassFactory.createFile();
String strClassName = file_name;
if ( !strClassName.startsWith("/apps") )
strClassName = "/apps" + file_name;
InputStream is = file.getResourceAsStream(clazz.getClass(), strClassName);
//create an instance of the player from the InputStream
Player player = javax.microedition.media.Manager.createPlayer(is,type);
player.realize();
player.prefetch();
//start the player
player.start();
} catch (Exception ex) {
LOG.ERROR("Error playing " + file_name + " :" + ex.getMessage());
} finally {
try{
if ( file != null )
file.close();
}catch(Exception exc){}
}
return;
}
}
LOG.ERROR("Error - media type " + type + " isn't supported.");
}
});
}
public static void initMethods(RubyClass klass) {
klass.getSingletonClass().defineMethod("show_popup", new RubyOneArgMethod()
{
protected RubyValue run(RubyValue receiver, RubyValue arg0, RubyBlock block)
{
try {
if ( arg0 instanceof RubyString )
{
String message = arg0.toString();
Alert.showPopup(message);
}else if ( arg0 instanceof RubyHash)
{
PopupHandler handler = new PopupHandler((RubyHash)arg0);
Application.getApplication().invokeLater(handler);
}
else
throw new RubyException(RubyRuntime.ArgumentErrorClass, "in Alert.show_popup: wrong argument type.Should be String or Hash");
return RubyConstant.QNIL;
} catch(Exception e) {
LOG.ERROR("show_popup failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("hide_popup", new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try {
AlertDialog.hidePopup();
return RubyConstant.QNIL;
}
catch (Exception e) {
LOG.ERROR("hide_popup failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("vibrate", new RubyVarArgMethod() {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block)
{
if ( args != null && args.size() > 1 )
throw new RubyException(RubyRuntime.ArgumentErrorClass,
"in Alert.vibrate: wrong number of arguments ( " + args.size() + " for " + 1 + " )");
try {
String duration = "2500";
if ((args != null) && (args.size() > 0))
duration = args.get(0).toString();
Alert.vibrate(duration);
return RubyConstant.QNIL;
} catch(Exception e) {
LOG.ERROR("vibrate failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("play_file", new RubyVarArgMethod() {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block)
{
if ( args.size() < 1 || args.size() > 2 )
throw new RubyException(RubyRuntime.ArgumentErrorClass,
"in Alert.play_file: wrong number of arguments ( " + args.size() + " for " + 2 + " )");
try {
String file_name = args.get(0).toString();
String media_type = null;
if ((args.size() > 1) && (args.get(1) != RubyConstant.QNIL))
media_type = args.get(1).toString();
Alert.play_file(file_name,media_type);
return RubyConstant.QNIL;
} catch(Exception e) {
LOG.ERROR("play_file failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
}
}
|
package chameleon.core.type;
import chameleon.core.declaration.SimpleNameSignature;
import chameleon.core.element.Element;
import chameleon.core.type.generics.FormalTypeParameter;
import chameleon.core.validation.Valid;
import chameleon.core.validation.VerificationResult;
import chameleon.exception.ChameleonProgrammerException;
/**
* This class represents types created as a result of looking up (resolving) a generic parameter, which itself is
* not a type.
*
* @author Marko van Dooren
*/
public class ConstructedType extends TypeIndirection {
public ConstructedType(SimpleNameSignature sig, Type aliasedType, FormalTypeParameter param) {
super(sig, aliasedType);
if(param == null) {
throw new ChameleonProgrammerException("The formal type parameter corresponding to a constructed type cannot be null.");
}
_param = param;
}
@Override
public boolean uniSameAs(Element type) {
return type == this ||
((type instanceof ConstructedType) && (((ConstructedType)type).parameter().equals(parameter())));
}
@Override
public String getFullyQualifiedName() {
return signature().name();
}
public FormalTypeParameter parameter() {
return _param;
}
private final FormalTypeParameter _param;
@Override
public ConstructedType clone() {
return new ConstructedType(signature().clone(), aliasedType(), parameter());
}
@Override
public VerificationResult verifySelf() {
return Valid.create();
}
}
|
package com.gmail.trentech.wirelessred.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.effect.particle.ParticleEffect;
import org.spongepowered.api.effect.particle.ParticleTypes;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.util.Direction;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import com.gmail.trentech.wirelessred.Main;
import com.gmail.trentech.wirelessred.data.receiver.Receiver;
import com.gmail.trentech.wirelessred.data.transmitter.Transmitter;
import com.gmail.trentech.wirelessred.data.transmitter.TransmitterData;
public class TransmitterHelper {
public static boolean toggleTransmitter(TransmitterData transmitterData, Location<World> location) {
boolean b = isPowered(location);
toggleTransmitter(transmitterData, location, b);
return b;
}
public static void toggleTransmitter(TransmitterData transmitterData, Location<World> location, boolean enable) {
Transmitter transmitter = transmitterData.transmitter().get();
transmitter.setEnabled(enable);
for (Location<World> receiverLocation : transmitterData.transmitter().get().getReceivers()) {
Optional<Receiver> optionalReceiver = Receiver.get(receiverLocation);
if (!optionalReceiver.isPresent()) {
transmitter.removeReceiver(receiverLocation);
continue;
}
Receiver receiver = optionalReceiver.get();
if (!isInRange(transmitter, location, receiverLocation)) {
continue;
}
receiver.setEnabled(enable);
receiver.updateEnabled(receiverLocation);
receiverLocation.offer(Keys.POWERED, enable);
}
List<Text> lines = new ArrayList<>();
if (enable) {
lines.add(Text.of(TextColors.DARK_BLUE, "[Transmitter]"));
lines.add(Text.of(TextColors.GREEN, "====="));
lines.add(Text.of(TextColors.GREEN, "==="));
lines.add(Text.of(TextColors.GREEN, "="));
enableParticles(location);
} else {
lines.add(Text.of(TextColors.DARK_BLUE, "[Transmitter]"));
lines.add(Text.EMPTY);
lines.add(Text.EMPTY);
lines.add(Text.of(TextColors.RED, "="));
disableParticles(location);
}
location.offer(Keys.SIGN_LINES, lines);
location.offer(transmitterData);
}
private static boolean isPowered(Location<World> location) {
List<Direction> directions = new ArrayList<>();
directions.add(Direction.NORTH);
directions.add(Direction.SOUTH);
directions.add(Direction.EAST);
directions.add(Direction.WEST);
for (Direction direction : directions) {
Location<World> relative = location.getRelative(direction);
if (relative.get(Keys.POWERED).isPresent() && relative.get(Keys.POWERED).get()) {
return true;
}
if (relative.get(Keys.POWER).isPresent() && (relative.get(Keys.POWER).get() >= 1)) {
return true;
}
}
return false;
}
public static boolean isInRange(Transmitter transmitter, Location<World> transmitterLocation, Location<World> receiverLocation) {
if ((receiverLocation.getExtent() != transmitterLocation.getExtent()) && !transmitter.isMultiWorld()) {
return false;
}
if (receiverLocation.getPosition().distance(transmitterLocation.getPosition()) > transmitter.getRange()) {
return false;
}
return true;
}
public static void enableParticles(Location<World> location) {
ThreadLocalRandom random = ThreadLocalRandom.current();
String name = location.getExtent().getName() + ":" + location.getBlockX() + ":" + location.getBlockY() + ":" + location.getBlockZ();
if (!Sponge.getScheduler().getTasksByName(name).isEmpty()) {
return;
}
ParticleEffect particle = ParticleEffect.builder().type(ParticleTypes.REDSTONE).build();
Sponge.getScheduler().createTaskBuilder().interval(400, TimeUnit.MILLISECONDS).name(name).execute(t -> {
if (random.nextDouble() > .8) {
location.getExtent().spawnParticles(particle, location.getPosition().add(random.nextDouble(), random.nextDouble(), random.nextDouble()));
} // .add(.5, .8, .5));
if (random.nextDouble() > .8) {
location.getExtent().spawnParticles(particle, location.getPosition().add(random.nextDouble(), random.nextDouble(), random.nextDouble()));
} // .add(.5, .8, .5));
if (random.nextDouble() > .8) {
location.getExtent().spawnParticles(particle, location.getPosition().add(random.nextDouble(), random.nextDouble(), random.nextDouble()));
} // .add(.5, .8, .5));
}).submit(Main.getPlugin());
}
public static void disableParticles(Location<World> location) {
String name = location.getExtent().getName() + ":" + location.getBlockX() + ":" + location.getBlockY() + ":" + location.getBlockZ();
for (Task task : Sponge.getScheduler().getScheduledTasks()) {
if (task.getName().equals(name)) {
task.cancel();
}
}
}
}
|
package com.googlesource.gerrit.plugins.cookbook.karma;
import com.google.gerrit.extensions.api.GerritApi;
import com.google.gerrit.extensions.common.*;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.List;
import java.util.Map;
@Singleton
public class Changes {
private final GerritApi gerritApi;
@Inject
public Changes(GerritApi gerritApi) {
this.gerritApi = gerritApi;
}
public List<ChangeInfo> getAllChangesForUser(String userName) throws RestApiException {
com.google.gerrit.extensions.api.changes.Changes.QueryRequest queryRequest =
gerritApi.changes().query("owner:" + userName);
return queryRequest.get();
}
public long ageInDays(ChangeInfo change) {
long createdMillis = change.created.getTime();
long updatedMillis = change.updated.getTime();
long millisInDay = (24*60*60*1000);
return (createdMillis - updatedMillis)/millisInDay;
}
public int totalLinesChanged(ChangeInfo change) {
return change.insertions + change.deletions;
}
public int averageNumberOfLinesForUser(String userName) throws RestApiException {
List<ChangeInfo> userChanges = getAllChangesForUser(userName);
return averageNumberOfLines(userChanges);
}
public int averageNumberOfLines(List<ChangeInfo> changes) {
int nTotalLines = 0;
int nChanges = changes.size();
for (ChangeInfo change : changes) {
nTotalLines += totalLinesChanged(change);
}
if (nChanges == 0) {
return 0;
}
return nTotalLines / nChanges;
}
public int averageNumberOfRevisions(List<ChangeInfo> changes) throws RestApiException {
int nChanges = changes.size();
int nRevisions = 0;
for (ChangeInfo change : changes) {
// revision info may not be fetched - explicit fetch required - no idea why...
ChangeInfo fetchedChange = gerritApi.changes().id(change._number).get();
Map<String, RevisionInfo> revisions = fetchedChange.revisions;
if (revisions == null) {
continue;
}
nRevisions += revisions.size();
}
return (int) Math.floor(((double)nRevisions)/((double)nChanges));
}
public boolean isApproved(ChangeInfo change) throws RestApiException {
Map<String, LabelInfo> labels = change.labels;
if (labels == null) {
// explicitly fetch if no labels found
change = gerritApi.changes().id(change._number).get();
}
LabelInfo codeReview = labels.get("Code-Review");
if (codeReview == null) {
// code not reviewed yet
return false;
}
AccountInfo approverAccountInfo = codeReview.approved;
return approverAccountInfo != null;
}
public boolean isRejected(ChangeInfo change) throws RestApiException {
Map<String, LabelInfo> labels = change.labels;
if (labels == null) {
// explicitly fetch if no labels found
change = gerritApi.changes().id(change._number).get();
}
LabelInfo codeReview = labels.get("Code-Review");
if (codeReview == null) {
// code not reviewed yet
return false;
}
AccountInfo rejectorAccountInfo = codeReview.rejected;
return rejectorAccountInfo != null;
}
/**
* Picks up the code review {@link LabelInfo}, picks the earliest review and computes the days between this and
* the time the patch set was created
*
* No, this is not perfect... its a very rough ballpark
*/
public long daysToReview(ChangeInfo change) throws RestApiException {
Map<String, LabelInfo> labels = change.labels;
if (labels == null) {
// explicitly fetch if no labels found
change = gerritApi.changes().id(change._number).get();
}
LabelInfo codeReview = labels.get("Code-Review");
if (codeReview == null) {
return -1;
}
// could be several - pick the earliest
long earliestReviewTimeInMillis = Long.MAX_VALUE;
for (ApprovalInfo approvalInfo : codeReview.all) {
if (approvalInfo.date.getTime() < earliestReviewTimeInMillis) {
earliestReviewTimeInMillis = approvalInfo.date.getTime();
}
}
long createdTimeInMillis = change.created.getTime();
long millisInDay = (24*60*60*1000);
return (earliestReviewTimeInMillis - createdTimeInMillis)/millisInDay;
}
}
|
package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.domain.dto.MenuDTO;
import com.imcode.imcms.domain.dto.MenuItemDTO;
import com.imcode.imcms.domain.service.AbstractVersionedContentService;
import com.imcode.imcms.domain.service.CommonContentService;
import com.imcode.imcms.domain.service.DocumentMenuService;
import com.imcode.imcms.domain.service.IdDeleterMenuService;
import com.imcode.imcms.domain.service.LanguageService;
import com.imcode.imcms.domain.service.VersionService;
import com.imcode.imcms.model.CommonContent;
import com.imcode.imcms.model.Language;
import com.imcode.imcms.persistence.entity.Menu;
import com.imcode.imcms.persistence.entity.MenuItem;
import com.imcode.imcms.persistence.entity.Version;
import com.imcode.imcms.persistence.repository.MenuRepository;
import com.imcode.imcms.sorted.TypeSort;
import imcode.server.Imcms;
import imcode.server.user.UserDomainObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import static com.imcode.imcms.persistence.entity.Meta.DisabledLanguageShowMode.SHOW_IN_DEFAULT_LANGUAGE;
@Service
@Transactional
public class DefaultMenuService extends AbstractVersionedContentService<Menu, MenuRepository>
implements IdDeleterMenuService {
private final VersionService versionService;
private final DocumentMenuService documentMenuService;
private final Function<List<MenuItemDTO>, Set<MenuItem>> menuItemDtoListToMenuItemList;
private final BiFunction<Menu, Language, MenuDTO> menuSaver;
private final UnaryOperator<MenuItem> toMenuItemsWithoutId;
private final LanguageService languageService;
private final BiFunction<MenuItem, Language, MenuItemDTO> menuItemToDTO;
private final BiFunction<MenuItem, Language, MenuItemDTO> menuItemToMenuItemDtoWithLang;
private final CommonContentService commonContentService;
DefaultMenuService(MenuRepository menuRepository,
VersionService versionService,
DocumentMenuService documentMenuService,
BiFunction<MenuItem, Language, MenuItemDTO> menuItemToDTO,
Function<List<MenuItemDTO>, Set<MenuItem>> menuItemDtoListToMenuItemList,
LanguageService languageService,
BiFunction<Menu, Language, MenuDTO> menuToMenuDTO,
UnaryOperator<MenuItem> toMenuItemsWithoutId,
BiFunction<MenuItem, Language, MenuItemDTO> menuItemToMenuItemDtoWithLang,
CommonContentService commonContentService) {
super(menuRepository);
this.versionService = versionService;
this.documentMenuService = documentMenuService;
this.menuItemToMenuItemDtoWithLang = menuItemToMenuItemDtoWithLang;
this.menuItemDtoListToMenuItemList = menuItemDtoListToMenuItemList;
this.menuItemToDTO = menuItemToDTO;
this.languageService = languageService;
this.toMenuItemsWithoutId = toMenuItemsWithoutId;
this.commonContentService = commonContentService;
this.menuSaver = (menu, language) -> menuToMenuDTO.apply(menuRepository.save(menu), language);
}
@Override
public List<MenuItemDTO> getMenuItems(int docId, int menuIndex, String language, boolean nested, String typeSort) {
List<MenuItemDTO> menuItemsOf = getMenuItemsOf(menuIndex, docId, MenuItemsStatus.ALL, language, false);
if (!nested) {
pullAndAddAllMenuItems(menuItemsOf);
}
if (typeSort == null) {
if (nested) {
typeSort = String.valueOf(TypeSort.TREE_SORT);
} else {
typeSort = String.valueOf(TypeSort.MANUAL);
}
}
return getSortingMenuItemsByTypeSort(typeSort, menuItemsOf);
}
private void pullAndAddAllMenuItems(List<MenuItemDTO> menuItems) {
final List<MenuItemDTO> childrenMenuItems = new ArrayList<>();
for (MenuItemDTO menuItemDTO : menuItems) {
childrenMenuItems.addAll(getAllNestedMenuItems(menuItemDTO));
}
menuItems.addAll(childrenMenuItems);
}
private List<MenuItemDTO> getSortingMenuItemsByTypeSort(String typeSort, List<MenuItemDTO> menuItems) {
switch (TypeSort.valueOf(typeSort.toUpperCase())) {
case TREE_SORT:
return menuItems;
case MANUAL:
return getAndSetUpEmptyChildrenMenuItems(menuItems);
case ALPHABETICAL_ASC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getTitle))
.collect(Collectors.toList());
case ALPHABETICAL_DESC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getTitle).reversed())
.collect(Collectors.toList());
default:
return Collections.EMPTY_LIST;
}
}
@Override
public List<MenuItemDTO> getVisibleMenuItems(int docId, int menuIndex, String language, boolean nested) {
List<MenuItemDTO> menuItemsOf = getMenuItemsOf(menuIndex, docId, MenuItemsStatus.ALL, language, true);
if (!nested) {
pullAndAddAllMenuItems(menuItemsOf);
}
return !nested ? getAndSetUpEmptyChildrenMenuItems(menuItemsOf) : menuItemsOf;
}
@Override
public List<MenuItemDTO> getPublicMenuItems(int docId, int menuIndex, String language, boolean nested) {
List<MenuItemDTO> menuItemsOf = getMenuItemsOf(menuIndex, docId, MenuItemsStatus.PUBLIC, language, true);
if (!nested) {
pullAndAddAllMenuItems(menuItemsOf);
}
return !nested ? getAndSetUpEmptyChildrenMenuItems(menuItemsOf) : menuItemsOf;
}
@Override
public MenuDTO saveFrom(MenuDTO menuDTO) {
final Integer docId = menuDTO.getDocId();
final Menu menu = Optional.ofNullable(getMenu(menuDTO.getMenuIndex(), docId))
.orElseGet(() -> createMenu(menuDTO));
menu.setNested(menuDTO.isNested());
menu.setMenuItems(menuItemDtoListToMenuItemList.apply(menuDTO.getMenuItems()));
final MenuDTO savedMenu = menuSaver.apply(menu, languageService.findByCode(Imcms.getUser().getLanguage()));
super.updateWorkingVersion(docId);
return savedMenu;
}
@Override
@Transactional
public void deleteByVersion(Version version) {
repository.deleteByVersion(version);
}
@Override
@Transactional
public void deleteByDocId(Integer docIdToDelete) {
repository.deleteByDocId(docIdToDelete);
}
@Override
public Menu removeId(Menu jpa, Version newVersion) {
final Menu menu = new Menu();
menu.setId(null);
menu.setNo(jpa.getNo());
menu.setVersion(newVersion);
final Set<MenuItem> newMenuItems = jpa.getMenuItems()
.stream()
.map(toMenuItemsWithoutId)
.collect(Collectors.toCollection(LinkedHashSet::new));
menu.setMenuItems(newMenuItems);
return menu;
}
private Menu getMenu(int menuNo, int docId) {
final Version workingVersion = versionService.getDocumentWorkingVersion(docId);
return repository.findByNoAndVersionAndFetchMenuItemsEagerly(menuNo, workingVersion);
}
private Menu createMenu(MenuDTO menuDTO) {
final Version workingVersion = versionService.getDocumentWorkingVersion(menuDTO.getDocId());
return createMenu(menuDTO, workingVersion);
}
private Menu createMenu(MenuDTO menuDTO, Version version) {
final Menu menu = new Menu();
menu.setNo(menuDTO.getMenuIndex());
menu.setVersion(version);
return menu;
}
@Override
public List<Menu> getAll() {
return repository.findAll();
}
private List<MenuItemDTO> getMenuItemsOf(
int menuIndex, int docId, MenuItemsStatus status, String langCode, boolean isVisible
) {
final Function<Integer, Version> versionReceiver = MenuItemsStatus.ALL.equals(status)
? versionService::getDocumentWorkingVersion
: versionService::getLatestVersion;
final Version version = versionService.getVersion(docId, versionReceiver);
final Language language = languageService.findByCode(langCode);
final Menu menu = repository.findByNoAndVersionAndFetchMenuItemsEagerly(menuIndex, version);
final UserDomainObject user = Imcms.getUser();
final Function<MenuItem, MenuItemDTO> menuItemFunction = isVisible
? menuItem -> menuItemToMenuItemDtoWithLang.apply(menuItem, language)
: menuItem -> menuItemToDTO.apply(menuItem, language);
return Optional.ofNullable(menu)
.map(Menu::getMenuItems)
.orElseGet(LinkedHashSet::new)
.stream()
.map(menuItemFunction)
.filter(Objects::nonNull)
.filter(menuItemDTO -> (status == MenuItemsStatus.ALL || isPublicMenuItem(menuItemDTO)))
.filter(menuItemDTO -> documentMenuService.hasUserAccessToDoc(menuItemDTO.getDocumentId(), user))
.filter(isMenuItemAccessibleForLang(language, versionReceiver))
.peek(menuItemDTO -> {
if (status == MenuItemsStatus.ALL) return;
final List<MenuItemDTO> children = menuItemDTO.getChildren()
.stream()
.filter(this::isPublicMenuItem)
.collect(Collectors.toList());
menuItemDTO.setChildren(children);
})
.collect(Collectors.toList());
}
private Predicate<MenuItemDTO> isMenuItemAccessibleForLang(Language language, Function<Integer, Version> versionReceiver) {
return menuItemDTO -> {
final int versionNo = versionService.getVersion(menuItemDTO.getDocumentId(), versionReceiver).getNo();
final List<CommonContent> menuItemDocContent = commonContentService.getOrCreateCommonContents(menuItemDTO.getDocumentId(), versionNo);
final List<Language> enabledLanguages = menuItemDocContent.stream()
.filter(item -> item.getLanguage().isEnabled())
.map(CommonContent::getLanguage)
.collect(Collectors.toList());
final boolean isLanguageEnabled = enabledLanguages.contains(language);
final boolean isCurrentLangDefault = language.getCode().equals(Imcms.getServices().getLanguageMapper().getDefaultLanguage());
final boolean isAllowedToShowWithDefaultLanguage = documentMenuService.getDisabledLanguageShowMode(menuItemDTO.getDocumentId()).equals(SHOW_IN_DEFAULT_LANGUAGE);
return isLanguageEnabled || (!isCurrentLangDefault && isAllowedToShowWithDefaultLanguage);
};
}
private boolean isPublicMenuItem(MenuItemDTO menuItemDTO) {
return documentMenuService.isPublicMenuItem(menuItemDTO.getDocumentId());
}
private List<MenuItemDTO> getAllNestedMenuItems(MenuItemDTO menuItemDTO) {
List<MenuItemDTO> nestedMenuItems = new ArrayList<>();
for (MenuItemDTO menuItem : menuItemDTO.getChildren()) {
if (!menuItem.getChildren().isEmpty()) {
nestedMenuItems.add(menuItem);
nestedMenuItems.addAll(getAllNestedMenuItems(menuItem));
} else {
nestedMenuItems.add(menuItem);
}
}
return nestedMenuItems;
}
private List<MenuItemDTO> getAndSetUpEmptyChildrenMenuItems(List<MenuItemDTO> menuItemDTOs) {
return menuItemDTOs.stream()
.peek(menuItem -> {
if (!menuItem.getChildren().isEmpty()) {
menuItem.setChildren(Collections.emptyList());
}
})
.collect(Collectors.toList());
}
}
|
package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.domain.dto.PhoneDTO;
import com.imcode.imcms.domain.dto.UserDTO;
import com.imcode.imcms.domain.dto.UserFormData;
import com.imcode.imcms.domain.exception.UserNotExistsException;
import com.imcode.imcms.domain.service.PhoneService;
import com.imcode.imcms.domain.service.RoleService;
import com.imcode.imcms.domain.service.UserAdminRolesService;
import com.imcode.imcms.domain.service.UserRolesService;
import com.imcode.imcms.domain.service.UserService;
import com.imcode.imcms.model.Phone;
import com.imcode.imcms.model.PhoneType;
import com.imcode.imcms.model.PhoneTypes;
import com.imcode.imcms.model.Role;
import com.imcode.imcms.model.Roles;
import com.imcode.imcms.persistence.entity.User;
import com.imcode.imcms.persistence.repository.UserRepository;
import imcode.server.LanguageMapper;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
class DefaultUserService implements UserService {
private final static Logger log = Logger.getLogger(DefaultUserService.class.getName());
private final UserRepository userRepository;
private final RoleService roleService;
private final PhoneService phoneService;
private final UserRolesService userRolesService;
private final UserAdminRolesService userAdminRolesService;
@PersistenceContext
private EntityManager entityManager;
DefaultUserService(UserRepository userRepository,
RoleService roleService,
PhoneService phoneService,
UserRolesService userRolesService,
UserAdminRolesService userAdminRolesService) {
this.userRepository = userRepository;
this.roleService = roleService;
this.phoneService = phoneService;
this.userRolesService = userRolesService;
this.userAdminRolesService = userAdminRolesService;
}
@Override
public User getUser(int id) {
return Optional.ofNullable(userRepository.findById(id))
.orElseThrow(() -> new UserNotExistsException(id));
}
@Override
public User getUser(String login) {
return Optional.ofNullable(userRepository.findByLogin(login))
.orElseThrow(() -> new UserNotExistsException(login));
}
@Override
public List<UserDTO> getAdminUsers() {
return toDTO(userRepository.findUsersWithRoleIds(Roles.USER_ADMIN.getId(), Roles.SUPER_ADMIN.getId()));
}
@Override
public List<UserDTO> getAllActiveUsers() {
return toDTO(userRepository.findByActiveIsTrue());
}
@Override
public List<UserDTO> getUsersByEmail(String email) {
return toDTO(userRepository.findByEmail(email));
}
@Override
public void createUser(UserFormData userData) {
final User user = saveUser(userData);
updateUserPhones(userData, user);
updateUserRoles(userData, user);
updateUserAdminRoles(userData, user);
}
private void updateUserAdminRoles(UserFormData userData, User user) {
final List<Role> administrateRoles = collectRoles(userData.getUserAdminRoleIds());
userAdminRolesService.updateUserAdminRoles(administrateRoles, user);
}
private void updateUserRoles(UserFormData userData, User user) {
final List<Role> userRoles = collectRoles(userData.getRoleIds());
userRolesService.updateUserRoles(userRoles, user);
}
void updateUserPhones(UserFormData userData, User user) {
final List<Phone> phoneNumbers = collectPhoneNumbers(userData, user);
phoneService.updateUserPhones(phoneNumbers, user.getId());
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
protected User saveUser(UserFormData userData) {
final User user = new User(userData);
user.setLanguageIso639_2(LanguageMapper.convert639_1to639_2(userData.getLangCode()));
return userRepository.save(user);
}
List<Role> collectRoles(int[] roleIdsInt) {
if (roleIdsInt == null || roleIdsInt.length == 0) return Collections.emptyList();
return Arrays.stream(roleIdsInt)
.mapToObj(roleService::getById)
.collect(Collectors.toList());
}
List<Phone> collectPhoneNumbers(UserFormData userData, User user) {
final String[] userPhoneNumbers = userData.getUserPhoneNumber();
final Integer[] userPhoneNumberTypes = userData.getUserPhoneNumberType();
if ((userPhoneNumbers == null)
|| (userPhoneNumberTypes == null)
|| (userPhoneNumbers.length <= 0)
|| (userPhoneNumberTypes.length <= 0)
|| (userPhoneNumbers.length != userPhoneNumberTypes.length))
{ // actually I don't know what to do if arrays have different length, however null and zero-length is fine
return Collections.emptyList();
}
List<Phone> numbers = new ArrayList<>();
for (int i = 0; i < userPhoneNumbers.length; i++) {
try {
final String userPhoneNumber = userPhoneNumbers[i];
final PhoneType numberType = PhoneTypes.getPhoneTypeById(userPhoneNumberTypes[i]);
numbers.add(new PhoneDTO(userPhoneNumber, user, numberType));
} catch (Exception e) {
log.error("Something wrong with phone numbers.", e);
}
}
return numbers;
}
private List<UserDTO> toDTO(Collection<User> users) {
return users.stream().map(UserDTO::new).collect(Collectors.toList());
}
// TODO: 13.10.17 Was moved. Rewrite to human code.
@Override
public List<User> findAll(boolean includeExternal, boolean includeInactive) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> c = cb.createQuery(User.class);
Root<User> user = c.from(User.class);
Predicate criteria = cb.conjunction();
if (!includeExternal) {
criteria = cb.and(criteria, cb.notEqual(user.get("external"), 2));
}
if (!includeInactive) {
criteria = cb.and(criteria, cb.isTrue(user.get("active")));
}
c.select(user).where(criteria);
return entityManager.createQuery(c).getResultList();
}
// TODO: 13.10.17 Was moved. Rewrite to human code.
@Override
public List<User> findByNamePrefix(String prefix, boolean includeInactive) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> c = cb.createQuery(User.class);
Root<User> user = c.from(User.class);
Predicate criteria = cb.notEqual(user.get("external"), 2);
if (!includeInactive) {
criteria = cb.and(criteria, cb.isTrue(user.get("active")));
}
criteria = cb.and(
criteria,
cb.or(
cb.like(user.get("login"), prefix),
cb.like(user.get("email"), prefix),
cb.like(user.get("firstName"), prefix),
cb.like(user.get("lastName"), prefix),
cb.like(user.get("title"), prefix),
cb.like(user.get("company"), prefix)
)
);
c.select(user).where(criteria).orderBy(cb.asc(user.get("lastName")), cb.asc(user.get("firstName")));
return entityManager.createQuery(c).getResultList();
}
}
|
package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.domain.dto.DocumentDTO;
import com.imcode.imcms.domain.dto.DocumentUrlDTO;
import com.imcode.imcms.domain.dto.UrlDocumentDTO;
import com.imcode.imcms.domain.factory.DocumentDtoFactory;
import com.imcode.imcms.domain.service.DocumentService;
import com.imcode.imcms.domain.service.DocumentUrlService;
import imcode.server.document.index.DocumentIndex;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
@Transactional
public class UrlDocumentService implements DocumentService<UrlDocumentDTO> {
private final DocumentService<DocumentDTO> defaultDocumentService;
private final DocumentDtoFactory documentDtoFactory;
private final DocumentUrlService documentUrlService;
public UrlDocumentService(DocumentService<DocumentDTO> documentService,
DocumentDtoFactory documentDtoFactory,
DocumentUrlService documentUrlService) {
this.defaultDocumentService = documentService;
this.documentDtoFactory = documentDtoFactory;
this.documentUrlService = documentUrlService;
}
@Override
public UrlDocumentDTO createEmpty() {
return documentDtoFactory.createEmptyUrlDocument();
}
@Override
public UrlDocumentDTO get(int docId) {
final UrlDocumentDTO urlDocumentDTO = new UrlDocumentDTO(defaultDocumentService.get(docId));
final DocumentUrlDTO documentUrlDTO = new DocumentUrlDTO(documentUrlService.getByDocId(docId));
urlDocumentDTO.setDocumentURL(documentUrlDTO);
return urlDocumentDTO;
}
@Override
public boolean publishDocument(int docId, int userId) {
return defaultDocumentService.publishDocument(docId, userId);
}
@Override
public SolrInputDocument index(int docId) {
final SolrInputDocument solrInputDocument = defaultDocumentService.index(docId);
final String url = get(docId).getDocumentURL().getUrl();
solrInputDocument.addField(DocumentIndex.FIELD_URL, url);
return solrInputDocument;
}
@Override
public void deleteByDocId(Integer docIdToDelete) {
defaultDocumentService.deleteByDocId(docIdToDelete);
}
@Override
public UrlDocumentDTO save(UrlDocumentDTO saveMe) {
final boolean isNew = (saveMe.getId() == null);
final Optional<DocumentUrlDTO> documentUrlDTO = Optional.ofNullable(saveMe.getDocumentURL());
final int savedDocId = defaultDocumentService.save(saveMe).getId();
if (isNew) {
documentUrlDTO.ifPresent(urlDTO -> urlDTO.setDocId(savedDocId));
}
documentUrlDTO.ifPresent(documentUrlService::save);
return saveMe;
}
}
|
package com.io7m.smfj.processing.main;
import com.io7m.jnull.NullCheck;
import com.io7m.jtensors.VectorI3L;
import com.io7m.smfj.parser.api.SMFParseError;
import com.io7m.smfj.processing.api.SMFFilterCommandContext;
import com.io7m.smfj.processing.api.SMFFilterCommandParsing;
import com.io7m.smfj.processing.api.SMFMemoryMesh;
import com.io7m.smfj.processing.api.SMFMemoryMeshFilterType;
import com.io7m.smfj.processing.api.SMFProcessingError;
import javaslang.collection.List;
import javaslang.collection.Vector;
import javaslang.control.Validation;
import java.nio.file.Path;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
/**
* A filter that optimizes and/or validates triangles.
*/
public final class SMFMemoryMeshFilterTrianglesOptimize implements
SMFMemoryMeshFilterType
{
/**
* The command name.
*/
public static final String NAME = "triangles-optimize";
private static final String SYNTAX =
"(<size> | '-') ('validate' | 'no-validate')";
private final SMFMemoryMeshFilterTrianglesOptimizeConfiguration config;
private SMFMemoryMeshFilterTrianglesOptimize(
final SMFMemoryMeshFilterTrianglesOptimizeConfiguration in_config)
{
this.config = NullCheck.notNull(in_config, "Config");
}
private static SMFProcessingError error(
final String format,
final Object... params)
{
return SMFProcessingError.of(
String.format(format, params), Optional.empty());
}
/**
* Create a new filter.
*
* @param in_config The configuration
*
* @return A new filter
*/
public static SMFMemoryMeshFilterType create(
final SMFMemoryMeshFilterTrianglesOptimizeConfiguration in_config)
{
return new SMFMemoryMeshFilterTrianglesOptimize(in_config);
}
private static SMFProcessingError nonexistentVertex(
final int triangle,
final long vertex)
{
return error(
"Triangle %d points to nonexistent vertex %d",
Integer.valueOf(triangle),
Long.valueOf(vertex));
}
/**
* Attempt to parse a command.
*
* @param file The file, if any
* @param line The line
* @param text The text
*
* @return A parsed command or a list of parse errors
*/
public static Validation<List<SMFParseError>, SMFMemoryMeshFilterType> parse(
final Optional<Path> file,
final int line,
final List<String> text)
{
NullCheck.notNull(file, "file");
NullCheck.notNull(text, "text");
if (text.length() == 2) {
try {
final int size;
final String size_text = text.get(0);
if (Objects.equals(size_text, "-")) {
size = 0;
} else {
size = Integer.parseInt(size_text);
}
final String validate = text.get(1);
final SMFMemoryMeshFilterTrianglesOptimizeConfiguration.Builder builder =
SMFMemoryMeshFilterTrianglesOptimizeConfiguration.builder();
if (size > 0) {
builder.setOptimize(size);
}
if (Objects.equals(validate, "validate")) {
builder.setValidate(true);
} else if (Objects.equals(validate, "no-validate")) {
builder.setValidate(false);
} else {
throw new IllegalArgumentException(
"Could not parse validation value: Must be 'validate' | 'no-validate'");
}
return Validation.valid(
create(builder.build()));
} catch (final IllegalArgumentException e) {
return SMFFilterCommandParsing.errorExpectedGotValidation(
file, line, makeSyntax(), text);
}
}
return SMFFilterCommandParsing.errorExpectedGotValidation(
file, line, makeSyntax(), text);
}
private static String makeSyntax()
{
return NAME + " " + SYNTAX;
}
@Override
public String name()
{
return NAME;
}
@Override
public String syntax()
{
return makeSyntax();
}
@Override
public Validation<List<SMFProcessingError>, SMFMemoryMesh> filter(
final SMFFilterCommandContext context,
final SMFMemoryMesh m)
{
NullCheck.notNull(context, "Context");
NullCheck.notNull(m, "Mesh");
List<SMFProcessingError> errors = List.empty();
final long vertices = m.header().vertexCount();
final Vector<VectorI3L> triangles = m.triangles();
final OptionalInt optimize_opt = this.config.optimize();
long max = 0L;
for (int index = 0; index < triangles.size(); ++index) {
final VectorI3L triangle = triangles.get(index);
final long v0 = triangle.getXL();
final long v1 = triangle.getYL();
final long v2 = triangle.getZL();
if (this.config.validate()) {
if (Long.compareUnsigned(v0, vertices) >= 0) {
errors = errors.append(nonexistentVertex(index, v0));
}
if (Long.compareUnsigned(v1, vertices) >= 0) {
errors = errors.append(nonexistentVertex(index, v1));
}
if (Long.compareUnsigned(v2, vertices) >= 0) {
errors = errors.append(nonexistentVertex(index, v2));
}
}
max = Math.max(max, v0);
max = Math.max(max, v1);
max = Math.max(max, v2);
}
final long triangle_size = optimize(m, optimize_opt, max);
if (errors.isEmpty()) {
return Validation.valid(
m.withHeader(m.header().withTriangleIndexSizeBits(triangle_size)));
}
return Validation.invalid(errors);
}
private static long optimize(
final SMFMemoryMesh m,
final OptionalInt optimize_opt,
final long max)
{
long triangle_size = m.header().triangleIndexSizeBits();
if (optimize_opt.isPresent()) {
if (max < (long) (StrictMath.pow(2.0, 64.0) - 1.0)) {
triangle_size = 64L;
}
if (max < (long) (StrictMath.pow(2.0, 32.0) - 1.0)) {
triangle_size = 32L;
}
if (max < (long) (StrictMath.pow(2.0, 16.0) - 1.0)) {
triangle_size = 16L;
}
if (max < (long) (StrictMath.pow(2.0, 8.0) - 1.0)) {
triangle_size = 8L;
}
final int smallest_allowed = optimize_opt.getAsInt();
triangle_size = Math.max(triangle_size, (long) smallest_allowed);
}
return triangle_size;
}
}
|
package com.indeed.proctor.webapp.tags;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.CharMatcher;
import com.google.common.base.Strings;
import com.indeed.proctor.common.EnvironmentVersion;
import com.indeed.proctor.common.Serializers;
import com.indeed.proctor.common.model.Allocation;
import com.indeed.proctor.common.model.Range;
import com.indeed.proctor.common.model.TestBucket;
import com.indeed.proctor.common.model.TestDefinition;
import com.indeed.proctor.store.Revision;
import com.indeed.proctor.webapp.controllers.ProctorController;
import com.indeed.proctor.webapp.db.Environment;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
/**
* @author parker
*/
public final class TestDefinitionFunctions {
private static final ObjectMapper objectMapper = Serializers.strict();
private TestDefinitionFunctions() { throw new UnsupportedOperationException("Static class"); }
public static TestBucket getTestBucketForRange(final TestDefinition definition, final Range range) {
for(TestBucket tb : definition.getBuckets()) {
if(tb.getValue() == range.getBucketValue()) {
return tb;
}
}
return null;
}
/**
*
* @param viewing
* @param history
* @param version
* @return
*/
public static boolean isCurrentVersionOnTrunk(final Environment viewing,
final Revision history,
final EnvironmentVersion version) {
if(version == null) { return false; }
switch (viewing) {
case QA:
case PRODUCTION:
// When viewing QA/TRUNK, look for (trunk r{Revision})
return isPromotedRevision(history, Environment.WORKING, version.getTrunkRevision()) ||
isCharmedRevision(history, version.getTrunkRevision());
case WORKING:
default:
return history.getRevision().equals(version.getTrunkRevision());
}
}
public static boolean isCurrentVersionOnQa(final Environment viewing,
final Revision history,
final EnvironmentVersion version) {
if(version == null) { return false; }
switch (viewing) {
case WORKING:
// trunk.revision gets set to qa.version during promotion
return history.getRevision().equals(version.getQaVersion());
case PRODUCTION:
// viewing production history:
// (qa r{qa.revision}) - this was a promotion from QA
// or (trunk r{qa.version}) - this was a promotion from trunk that is the same as the current version running on QA
return isPromotedRevision(history, Environment.QA, version.getQaRevision()) ||
isPromotedRevision(history, Environment.WORKING, version.getQaVersion()) ||
isCharmedRevision(history, version.getQaVersion());
case QA:
default:
return history.getRevision().equals(version.getQaRevision());
}
}
public static boolean isCurrentVersionOnProduction(final Environment viewing,
final Revision history,
final EnvironmentVersion version) {
if(version == null) { return false; }
switch (viewing) {
case WORKING:
// trunk.revision gets set to production.version during promotion
return history.getRevision().equals(version.getProductionVersion());
case QA:
// viewing qa history:
// (trunk r{qa.version}) - the same trunk revision was promoted to production, either by QA->PROD or TRUNK->PROD
return isPromotedRevision(history, Environment.WORKING, version.getProductionVersion()) ||
isCharmedRevision(history, version.getProductionVersion());
case PRODUCTION:
default:
return history.getRevision().equals(version.getProductionRevision());
}
}
/**
* Returns a flag whose value indicates if the history entry corresponds to the promoted version from the provided Branch+revision.
*
* When looking at the history of the trunk branch, because we track the trunk version as each test's 'Version' value (in the definition.json file),
* it's sufficient to compare the history.revision == definition.version.
*
* When looking at the history on the qa branch, the history.revision will never equal the definition.version because definition.version corresponds to a revision on trunk.
* When we promote from trunk -> QA, we format the commit message as "Promoting {testName} (trunk rXXX) to qa"
* If we look for (trunk rXXX) we should be able to identify the commit on QA that of the current definition.version.
*
* @param history
* @param source
* @param revision
* @return
*/
private static boolean isPromotedRevision(Revision history, Environment source, String revision) {
// Look for <branch> rXXXX in the commit message
final String needle = String.format("%s r%s", source.getName(), revision);
return history.getMessage().contains(needle);
}
private static boolean isCharmedRevision(Revision history, String revision) {
// Look for "merged rXXXX: in the commit message
final String needle = String.format("merged r%s:", revision);
return history.getMessage().startsWith(needle);
}
// Annoyingly there isn't a way to check map.contains via jsp, you cannot even access the keys Collection directly
public static boolean containsKey(Map m, Object key) {
return m.containsKey(key);
}
public static boolean containsAnyDev(final Collection<ProctorController.CompatibilityRow> rows) {
for (final ProctorController.CompatibilityRow row : rows) {
if (row.getDev().size() != 0) {
return true;
}
}
return false;
}
public static TestDefinition parseTestDefinition(final String testDefinition) throws IOException, JsonParseException, JsonMappingException {
final TestDefinition td = objectMapper.readValue(testDefinition, TestDefinition.class);
// Until (PROC-72) is resolved, all of the 'empty' rules should get saved as NULL rules.
if (CharMatcher.WHITESPACE.matchesAllOf(Strings.nullToEmpty(td.getRule()))) {
td.setRule(null);
}
for (final Allocation ac : td.getAllocations()) {
if (CharMatcher.WHITESPACE.matchesAllOf(Strings.nullToEmpty(ac.getRule()))) {
ac.setRule(null);
}
}
return td;
}
}
|
package com.izforge.izpack.installer.container.provider;
import com.izforge.izpack.api.data.AutomatedInstallData;
import com.izforge.izpack.api.data.DynamicInstallerRequirementValidator;
import com.izforge.izpack.api.data.DynamicVariable;
import com.izforge.izpack.api.data.Info;
import com.izforge.izpack.api.data.Info.TempDir;
import com.izforge.izpack.api.data.InstallerRequirement;
import com.izforge.izpack.api.data.LocaleDatabase;
import com.izforge.izpack.api.data.Pack;
import com.izforge.izpack.api.data.Panel;
import com.izforge.izpack.api.data.ResourceManager;
import com.izforge.izpack.api.data.ScriptParserConstant;
import com.izforge.izpack.api.data.Value;
import com.izforge.izpack.api.exception.InstallerException;
import com.izforge.izpack.api.substitutor.VariableSubstitutor;
import com.izforge.izpack.merge.resolve.ClassPathCrawler;
import com.izforge.izpack.util.IoHelper;
import com.izforge.izpack.util.OsConstraintHelper;
import com.izforge.izpack.util.OsVersion;
import com.izforge.izpack.util.TemporaryDirectory;
import org.picocontainer.injectors.Provider;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Abstract class sharing commons instanciation methods beetween installData
*/
public abstract class AbstractInstallDataProvider implements Provider
{
private static final Logger logger = Logger.getLogger(AbstractInstallDataProvider.class.getName());
/**
* The base name of the XML file that specifies the custom langpack. Searched is for the file
* with the name expanded by _ISO3.
*/
protected static final String LANG_FILE_NAME = "CustomLangPack.xml";
protected ResourceManager resourceManager;
protected VariableSubstitutor variableSubstitutor;
protected ClassPathCrawler classPathCrawler;
/**
* Loads the installation data. Also sets environment variables to <code>installdata</code>.
* All system properties are available as $SYSTEM_<variable> where <variable> is the actual
* name _BUT_ with all separators replaced by '_'. Properties with null values are never stored.
* Example: $SYSTEM_java_version or $SYSTEM_os_name
*
* @param installdata Where to store the installation data.
* @throws Exception Description of the Exception
*/
protected void loadInstallData(AutomatedInstallData installdata) throws IOException, ClassNotFoundException, InstallerException
{
// We load the variables
Properties variables = (Properties) readObject("vars");
// We load the Info data
Info info = (Info) readObject("info");
// We put the Info data as variables
installdata.setVariable(ScriptParserConstant.APP_NAME, info.getAppName());
if (info.getAppURL() != null)
{
installdata.setVariable(ScriptParserConstant.APP_URL, info.getAppURL());
}
installdata.setVariable(ScriptParserConstant.APP_VER, info.getAppVersion());
if (info.getUninstallerCondition() != null)
{
installdata.setVariable("UNINSTALLER_CONDITION", info.getUninstallerCondition());
}
installdata.setInfo(info);
// Set the installation path in a default manner
String dir = getDir();
String installPath = dir + info.getAppName();
if (info.getInstallationSubPath() != null)
{ // A subpath was defined, use it.
installPath = IoHelper.translatePath(dir + info.getInstallationSubPath(),
variableSubstitutor);
}
installdata.setDefaultInstallPath(installPath);
// Pre-set install path from a system property,
// for instance in unattended installations
installPath = System.getProperty(AutomatedInstallData.INSTALL_PATH);
if (installPath != null)
{
installdata.setInstallPath(installPath);
}
// We read the panels order data
List<Panel> panelsOrder = (List<Panel>) readObject("panelsOrder");
// We read the packs data
InputStream in = resourceManager.getInputStream("packs.info");
ObjectInputStream objIn = new ObjectInputStream(in);
int size = objIn.readInt();
List<Pack> availablePacks = new ArrayList<Pack>();
List<Pack> allPacks = new ArrayList<Pack>();
for (int i = 0; i < size; i++)
{
Pack pack = (Pack) objIn.readObject();
allPacks.add(pack);
if (OsConstraintHelper.oneMatchesCurrentSystem(pack.osConstraints))
{
availablePacks.add(pack);
}
}
objIn.close();
// We determine the hostname and IPAdress
String hostname;
String IPAddress;
try
{
InetAddress addr = InetAddress.getLocalHost();
// Get IP Address
IPAddress = addr.getHostAddress();
// Get hostname
hostname = addr.getHostName();
}
catch (Exception e)
{
hostname = "";
IPAddress = "";
}
installdata.setVariable("APPLICATIONS_DEFAULT_ROOT", dir);
dir += File.separator;
installdata.setVariable(ScriptParserConstant.JAVA_HOME, System.getProperty("java.home"));
installdata.setVariable(ScriptParserConstant.CLASS_PATH, System.getProperty("java.class.path"));
installdata.setVariable(ScriptParserConstant.USER_HOME, System.getProperty("user.home"));
installdata.setVariable(ScriptParserConstant.USER_NAME, System.getProperty("user.name"));
installdata.setVariable(ScriptParserConstant.IP_ADDRESS, IPAddress);
installdata.setVariable(ScriptParserConstant.HOST_NAME, hostname);
installdata.setVariable(ScriptParserConstant.FILE_SEPARATOR, File.separator);
Set<String> systemProperties = System.getProperties().stringPropertyNames();
for (String varName : systemProperties)
{
String varValue = System.getProperty(varName);
if (varValue != null)
{
varName = varName.replace('.', '_');
installdata.setVariable("SYSTEM_" + varName, varValue);
}
}
if (null != variables)
{
Set<String> vars = variables.stringPropertyNames();
for (String varName : vars)
{
installdata.setVariable(varName, variables.getProperty(varName));
}
}
installdata.setPanelsOrder(panelsOrder);
installdata.setAvailablePacks(availablePacks);
installdata.setAllPacks(allPacks);
// get list of preselected packs
for (Pack availablePack : availablePacks)
{
if (availablePack.preselected)
{
installdata.getSelectedPacks().add(availablePack);
}
}
// Create any temp directories
Set<TempDir> tempDirs = info.getTempDirs();
if (null != tempDirs && tempDirs.size() > 0)
{
for (TempDir tempDir : tempDirs)
{
TemporaryDirectory directory = new TemporaryDirectory(tempDir, installdata);
directory.create();
directory.cleanUp();
}
}
}
/**
* Add the contents of a custom langpack (if exist) to the previos loaded comman langpack. If
* not exist, trace an info and do nothing more.
*
* @param idata install data to be used
*/
protected void addCustomLangpack(AutomatedInstallData idata)
{
// We try to load and add a custom langpack.
try
{
idata.getLangpack().add(resourceManager.getInputStream(LANG_FILE_NAME));
}
catch (Throwable exception)
{
logger.warning("No custom langpack for " + idata.getLocaleISO3() + " available");
return;
}
logger.fine("Found custom langpack for " + idata.getLocaleISO3());
}
private String getDir()
{
// We determine the operating system and the initial installation path
String dir;
if (OsVersion.IS_WINDOWS)
{
dir = buildWindowsDefaultPath();
}
else if (OsVersion.IS_OSX)
{
dir = "/Applications/";
}
else
{
if (new File("/usr/local/").canWrite())
{
dir = "/usr/local/";
}
else
{
dir = System.getProperty("user.home") + File.separatorChar;
}
}
return dir;
}
/**
* Get the default path for Windows (i.e Program Files/...).
* Windows has a Setting for this in the environment and in the registry.
* Just try to use the setting in the environment. If it fails for whatever reason, we take the former solution (buildWindowsDefaultPathFromProps).
*
* @return The Windows default installation path for applications.
*/
private String buildWindowsDefaultPath()
{
try
{
//get value from environment...
String prgFilesPath = IoHelper.getenv("ProgramFiles");
if (prgFilesPath != null && prgFilesPath.length() > 0)
{
return prgFilesPath + File.separatorChar;
}
else
{
return buildWindowsDefaultPathFromProps();
}
}
catch (Exception x)
{
x.printStackTrace();
return buildWindowsDefaultPathFromProps();
}
}
/**
* just plain wrong in case the programfiles are not stored where the developer expects them.
* E.g. in custom installations of large companies or if used internationalized version of windows with a language pack.
*
* @return the program files path
*/
private String buildWindowsDefaultPathFromProps()
{
StringBuffer dpath = new StringBuffer("");
try
{
// We load the properties
Properties props = new Properties();
props.load(
resourceManager.getInputStream("/com/izforge/izpack/installer/win32-defaultpaths.properties"));
// We look for the drive mapping
String drive = System.getProperty("user.home");
if (drive.length() > 3)
{
drive = drive.substring(0, 3);
}
// Now we have it :-)
dpath.append(drive);
// Ensure that we have a trailing backslash (in case drive was
// something
// like "C:")
if (drive.length() == 2)
{
dpath.append("\\");
}
String language = Locale.getDefault().getLanguage();
String country = Locale.getDefault().getCountry();
String language_country = language + "_" + country;
// Try the most specific combination first
if (null != props.getProperty(language_country))
{
dpath.append(props.getProperty(language_country));
}
else if (null != props.getProperty(language))
{
dpath.append(props.getProperty(language));
}
else
{
dpath.append(props.getProperty(Locale.ENGLISH.getLanguage()));
}
}
catch (Exception err)
{
dpath = new StringBuffer("C:\\Program Files");
}
return dpath.toString();
}
/**
* Loads Dynamic Variables.
*
* @param automatedInstallData
*/
protected void loadDynamicVariables(AutomatedInstallData automatedInstallData)
{
try
{
InputStream in = resourceManager.getInputStream("dynvariables");
ObjectInputStream objIn = new ObjectInputStream(in);
Map<String, List<DynamicVariable>> dynamicvariables = (Map<String, List<DynamicVariable>>) objIn.readObject();
objIn.close();
// Initialize to prepare variable substition on several attributes
for (List<DynamicVariable> dynVarList : dynamicvariables.values())
{
for (DynamicVariable dynVar : dynVarList)
{
Value value = dynVar.getValue();
value.setInstallData(automatedInstallData);
}
}
automatedInstallData.setDynamicvariables(dynamicvariables);
}
catch (Exception e)
{
logger.log(Level.WARNING,
"Cannot find optional dynamic variables", e);
}
}
/**
* Loads dynamic conditions.
*
* @param automatedInstallData
*/
protected void loadDynamicConditions(AutomatedInstallData automatedInstallData)
{
try
{
InputStream in = resourceManager.getInputStream("dynconditions");
ObjectInputStream objIn = new ObjectInputStream(in);
automatedInstallData.setDynamicinstallerrequirements((List<DynamicInstallerRequirementValidator>) objIn.readObject());
objIn.close();
}
catch (Exception e)
{
logger.log(Level.WARNING,
"Cannot find optional dynamic conditions", e);
}
}
/**
* Load installer conditions
*
* @param automatedInstallData
* @throws Exception
*/
public void loadInstallerRequirements(AutomatedInstallData automatedInstallData) throws Exception
{
InputStream in = resourceManager.getInputStream("installerrequirements");
ObjectInputStream objIn = new ObjectInputStream(in);
automatedInstallData.setInstallerrequirements((List<InstallerRequirement>) objIn.readObject());
objIn.close();
}
/**
* Load a default locale in the installData
*
* @param automatedInstallData The installData to fill
* @throws Exception
*/
protected void loadDefaultLocale(AutomatedInstallData automatedInstallData) throws Exception
{
// Loads the suitable langpack
List<String> availableLangPacks = resourceManager.getAvailableLangPacks();
String selectedPack = availableLangPacks.get(0);
InputStream in = resourceManager.getInputStream("langpacks/" + selectedPack + ".xml");
automatedInstallData.setAndProcessLocal(selectedPack, new LocaleDatabase(in));
resourceManager.setLocale(selectedPack);
}
public Object readObject(String resourceId) throws IOException, ClassNotFoundException
{
InputStream inputStream = resourceManager.getInputStream(resourceId);
ObjectInputStream objIn = new ObjectInputStream(inputStream);
Object model = objIn.readObject();
objIn.close();
return model;
}
}
|
package com.sdl.selenium.web.utils.browsers;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class ChromeConfigReader extends AbstractBrowserConfigReader {
private static final Logger LOGGER = LoggerFactory.getLogger(ChromeConfigReader.class);
private static final String DEFAULT_CONFIG = "" +
"\n browser=chrome" +
"\n browser.driver.path=src\\\\test\\\\resources\\\\drivers\\\\chromedriver.exe" +
"\n browser.download.dir=src\\\\test\\\\resources\\\\download\\\\" +
"\n options.arguments=--lang=en --allow-running-insecure-content --enable-logging --v=1 --test-type" +
"\n options.experimental.profile.default_content_settings.multiple-automatic-downloads=1" +
"\n options.experimental.download.prompt_for_download=1";
public ChromeConfigReader() {
this(null);
}
public ChromeConfigReader(String resourcePath) {
super(resourcePath, DEFAULT_CONFIG);
}
@Override
public WebDriver createDriver() throws IOException {
String driverPath = getProperty("browser.driver.path");
if (!"".equals(driverPath)) {
System.setProperty("webdriver.chrome.driver", driverPath);
}
ChromeOptions options = new ChromeOptions();
setProfilePreferences(options);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
return new ChromeDriver(capabilities);
}
@Override
public boolean isSilentDownload() {
return !"".equals(getProperty("browser.download.dir"));
}
@Override
public String getDownloadPath() {
File file = new File(getProperty("browser.download.dir"));
return file.getAbsolutePath();
}
private void setProfilePreferences(ChromeOptions options) throws IOException {
Map<String, Object> prefs = new HashMap<String, Object>();
for (Map.Entry<Object, Object> entry : entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (key.startsWith("options.arguments")) {
options.addArguments(value);
} else if (key.startsWith("options.experimental.")) {
String preferenceKey = key.substring(21);
if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) {
prefs.put(preferenceKey, Boolean.valueOf(value));
} else {
try {
int intValue = Integer.parseInt(value);
prefs.put(preferenceKey, intValue);
} catch (NumberFormatException e) {
prefs.put(preferenceKey, value);
}
}
}
}
String property = getProperty("browser.download.dir");
File file = new File(property);
String downloadDir = file.getCanonicalPath();
if (!"".equals(downloadDir)) {
prefs.put("download.default_directory", downloadDir);
}
options.setExperimentalOption("prefs", prefs);
}
}
|
package crazypants.enderio.item.darksteel;
import java.util.List;
import java.util.Set;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemPickaxe;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.MinecraftForge;
import cofh.api.energy.IEnergyContainerItem;
import com.google.common.collect.Sets;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import crazypants.enderio.EnderIO;
import crazypants.enderio.EnderIOTab;
import crazypants.enderio.config.Config;
import crazypants.enderio.gui.IAdvancedTooltipProvider;
import crazypants.enderio.machine.power.PowerDisplayUtil;
import crazypants.enderio.teleport.IItemOfTravel;
import crazypants.enderio.teleport.TravelController;
import crazypants.enderio.teleport.TravelSource;
import crazypants.util.ItemUtil;
import crazypants.util.Lang;
public class ItemDarkSteelPickaxe extends ItemPickaxe implements IEnergyContainerItem, IAdvancedTooltipProvider, IDarkSteelItem, IItemOfTravel {
public static boolean isEquipped(EntityPlayer player) {
if(player == null) {
return false;
}
ItemStack equipped = player.getCurrentEquippedItem();
if(equipped == null) {
return false;
}
return equipped.getItem() == EnderIO.itemDarkSteelPickaxe;
}
public static boolean isEquippedAndPowered(EntityPlayer player, int requiredPower) {
if(!isEquipped(player)) {
return false;
}
return EnderIO.itemDarkSteelPickaxe.getEnergyStored(player.getCurrentEquippedItem()) >= requiredPower;
}
public static ItemDarkSteelPickaxe create() {
ItemDarkSteelPickaxe res = new ItemDarkSteelPickaxe();
res.init();
MinecraftForge.EVENT_BUS.register(res);
return res;
}
private long lastBlickTick = -1;
public ItemDarkSteelPickaxe() {
super(ItemDarkSteelSword.MATERIAL);
setCreativeTab(EnderIOTab.tabEnderIO);
String str = "darkSteel_pickaxe";
setUnlocalizedName(str);
setTextureName("enderIO:" + str);
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List par3List) {
ItemStack is = new ItemStack(this);
par3List.add(is);
is = new ItemStack(this);
EnergyUpgrade.EMPOWERED_FOUR.writeToItem(is);
EnergyUpgrade.setPowerFull(is);
TravelUpgrade.INSTANCE.writeToItem(is);
SpoonUpgrade.INSTANCE.writeToItem(is);
par3List.add(is);
}
@Override
public int getIngotsRequiredForFullRepair() {
return 3;
}
@Override
public boolean isDamaged(ItemStack stack) {
return false;
}
@Override
public boolean hitEntity(ItemStack par1ItemStack, EntityLivingBase par2EntityLivingBase, EntityLivingBase par3EntityLivingBase) {
applyDamage(par3EntityLivingBase, par1ItemStack, 2);
return true;
}
@Override
public boolean onBlockDestroyed(ItemStack item, World world, Block block, int x, int y, int z, EntityLivingBase entLiving) {
if(block.getBlockHardness(world, x, y, z) != 0.0D) {
if(useObsidianEffeciency(item, block)) {
extractEnergy(item, Config.darkSteelPickPowerUseObsidian, false);
}
applyDamage(entLiving, item, 1);
}
return true;
}
@Override
public boolean onItemUse(ItemStack item, EntityPlayer player, World world,
int x, int y, int z, int side, float par8, float par9, float par10) {
if (!isTravelUpgradeActive(player, item) && world.isRemote) {
return doRightClickItemPlace(player, world, x, y, z, side, par8,
par9, par10);
}
return false;
}
@SideOnly(Side.CLIENT)
static boolean doRightClickItemPlace(EntityPlayer player, World world,
int x, int y, int z, int side, float par8, float par9, float par10) {
int current = player.inventory.currentItem;
int slot = current == 0 && Config.slotZeroPlacesEight ? 8 : current + 1;
if (slot < 9
&& player.inventory.mainInventory[slot] != null
&& !(player.inventory.mainInventory[slot].getItem() instanceof IDarkSteelItem)) {
/*
* this will not work with buckets unless we don't switch back to
* the current item (the pick); there's probably some client <->
* server event thing going on with buckets, so our item-switch
* within the same tick would be a problem.
*/
player.inventory.currentItem = slot;
Minecraft mc = Minecraft.getMinecraft();
boolean result = mc.playerController.onPlayerRightClick(
mc.thePlayer, mc.theWorld,
player.inventory.mainInventory[slot],
mc.objectMouseOver.blockX, mc.objectMouseOver.blockY,
mc.objectMouseOver.blockZ, mc.objectMouseOver.sideHit,
mc.objectMouseOver.hitVec);
player.inventory.currentItem = current;
return (result);
}
return false;
}
private void applyDamage(EntityLivingBase entity, ItemStack stack, int damage) {
EnergyUpgrade eu = EnergyUpgrade.loadFromItem(stack);
if(eu != null && eu.isAbsorbDamageWithPower(stack) && eu.getEnergy() > 0) {
eu.extractEnergy(damage * Config.darkSteelPickPowerUsePerDamagePoint, false);
} else {
damage = stack.getItemDamage() + damage;
if(damage >= getMaxDamage()) {
stack.stackSize = 0;
}
stack.setItemDamage(damage);
}
if(eu != null) {
eu.writeToItem(stack);
}
}
@Override
public boolean canHarvestBlock(Block block, ItemStack item) {
if(hasSpoonUpgrade(item) && getEnergyStored(item) > 0) {
return block == Blocks.snow_layer ? true : block == Blocks.snow || super.canHarvestBlock(block, item);
} else {
return super.canHarvestBlock(block, item);
}
}
private boolean hasSpoonUpgrade(ItemStack item) {
return SpoonUpgrade.loadFromItem(item) != null;
}
@Override
public float getDigSpeed(ItemStack stack, Block block, int meta) {
if(useObsidianEffeciency(stack, block)) {
return ItemDarkSteelSword.MATERIAL.getEfficiencyOnProperMaterial() + Config.darkSteelPickEffeciencyBoostWhenPowered
+ Config.darkSteelPickEffeciencyObsidian;
}
if(ForgeHooks.isToolEffective(stack, block, meta)) {
if(Config.darkSteelPickPowerUsePerDamagePoint <= 0 || getEnergyStored(stack) > 0) {
return ItemDarkSteelSword.MATERIAL.getEfficiencyOnProperMaterial() + Config.darkSteelPickEffeciencyBoostWhenPowered;
}
return ItemDarkSteelSword.MATERIAL.getEfficiencyOnProperMaterial();
}
return super.getDigSpeed(stack, block, meta);
}
@Override
public float func_150893_a(ItemStack item, Block block) {
if(block.getMaterial() == Material.glass) {
return efficiencyOnProperMaterial;
}
return super.func_150893_a(item, block);
}
private boolean useObsidianEffeciency(ItemStack item, Block block) {
boolean useObsidianSpeed = false;
int energy = getEnergyStored(item);
if(energy > 0) {
useObsidianSpeed = block == Blocks.obsidian;
if(!useObsidianSpeed && Config.darkSteelPickApplyObsidianEffeciencyAtHardess > 0) {
try {
useObsidianSpeed = (block != null && block.getBlockHardness(null, -1, -1, -1) >= Config.darkSteelPickApplyObsidianEffeciencyAtHardess);
} catch (Exception e) {
//given we are passing in a null world to getBlockHardness it is possible this could cause an NPE, so just ignore it
}
}
}
return useObsidianSpeed;
}
@Override
public Set<String> getToolClasses(ItemStack stack) {
Set<String> set = Sets.newHashSet("pickaxe");
if(hasSpoonUpgrade(stack)) {
set.add("shovel");
}
return set;
}
protected void init() {
GameRegistry.registerItem(this, getUnlocalizedName());
}
@Override
public int receiveEnergy(ItemStack container, int maxReceive, boolean simulate) {
return EnergyUpgrade.receiveEnergy(container, maxReceive, simulate);
}
@Override
public int extractEnergy(ItemStack container, int maxExtract, boolean simulate) {
return EnergyUpgrade.extractEnergy(container, maxExtract, simulate);
}
@Override
public int getEnergyStored(ItemStack container) {
return EnergyUpgrade.getEnergyStored(container);
}
@Override
public int getMaxEnergyStored(ItemStack container) {
return EnergyUpgrade.getMaxEnergyStored(container);
}
@Override
public boolean getIsRepairable(ItemStack i1, ItemStack i2) {
return false;
}
@Override
public void addCommonEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
DarkSteelRecipeManager.instance.addCommonTooltipEntries(itemstack, entityplayer, list, flag);
}
@Override
public void addBasicEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
DarkSteelRecipeManager.instance.addBasicTooltipEntries(itemstack, entityplayer, list, flag);
}
@Override
public void addDetailedEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
if(!Config.addDurabilityTootip) {
list.add(ItemUtil.getDurabilityString(itemstack));
}
String str = EnergyUpgrade.getStoredEnergyString(itemstack);
if(str != null) {
list.add(str);
}
if(EnergyUpgrade.itemHasAnyPowerUpgrade(itemstack)) {
list.add(EnumChatFormatting.WHITE + "+" + Config.darkSteelPickEffeciencyBoostWhenPowered + " "
+ Lang.localize("item.darkSteel_pickaxe.tooltip.effPowered"));
list.add(EnumChatFormatting.WHITE + "+" + Config.darkSteelPickEffeciencyObsidian + " "
+ Lang.localize("item.darkSteel_pickaxe.tooltip.effObs") + " ");
list.add(EnumChatFormatting.WHITE + " (cost "
+ PowerDisplayUtil.formatPower(Config.darkSteelPickPowerUseObsidian / 10) + " "
+ PowerDisplayUtil.abrevation() + ")");
}
DarkSteelRecipeManager.instance.addAdvancedTooltipEntries(itemstack, entityplayer, list, flag);
}
public ItemStack createItemStack() {
return new ItemStack(this);
}
@Override
public boolean isActive(EntityPlayer ep, ItemStack equipped) {
return isTravelUpgradeActive(ep, equipped);
}
@Override
public void extractInternal(ItemStack equipped, int power) {
extractEnergy(equipped, power, false);
}
private boolean isTravelUpgradeActive(EntityPlayer ep, ItemStack equipped) {
return isEquipped(ep) && ep.isSneaking() && TravelUpgrade.loadFromItem(equipped) != null;
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
if(isTravelUpgradeActive(player, stack)) {
if(world.isRemote) {
if(TravelController.instance.activateTravelAccessable(stack, world, player, TravelSource.STAFF)) {
player.swingItem();
return stack;
}
}
long ticksSinceBlink = EnderIO.proxy.getTickCount() - lastBlickTick;
if(ticksSinceBlink < 0) {
lastBlickTick = -1;
}
if(Config.travelStaffBlinkEnabled && world.isRemote && ticksSinceBlink >= Config.travelStaffBlinkPauseTicks) {
if(TravelController.instance.doBlink(stack, player)) {
player.swingItem();
lastBlickTick = EnderIO.proxy.getTickCount();
}
}
return stack;
}
return super.onItemRightClick(stack, world, player);
}
}
|
package de.craften.plugins.rpgplus.scripting.api;
import de.craften.plugins.rpgplus.RpgPlus;
import de.craften.plugins.rpgplus.common.entity.RPGVillager;
import de.craften.plugins.rpgplus.components.commands.CommandHandler;
import de.craften.plugins.rpgplus.scripting.ScriptingManager;
import de.craften.plugins.rpgplus.scripting.util.ScriptUtil;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.util.Vector;
import org.luaj.vm2.LuaError;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.lib.TwoArgFunction;
import org.luaj.vm2.lib.VarArgFunction;
import org.luaj.vm2.lib.jse.CoerceJavaToLua;
import java.util.List;
public class RpgPlusObject extends LuaTable {
public RpgPlusObject(final ScriptingManager plugin) {
set("log", new VarArgFunction() {
@Override
public Varargs invoke(Varargs varargs) {
if (varargs.narg() >= 2) {
switch (varargs.checkjstring(1)) {
case "info":
plugin.getLogger().info(varargs.checkjstring(2));
break;
case "warn":
plugin.getLogger().warning(varargs.checkjstring(2));
break;
case "error":
plugin.getLogger().severe(varargs.checkjstring(2));
break;
default:
throw new LuaError("Invalid argument, first parameter must be info, warn or error.");
}
} else {
plugin.getLogger().info(varargs.checkjstring(1));
}
return LuaValue.NIL;
}
});
set("registerVillager", new TwoArgFunction() {
@Override
public LuaValue call(LuaValue options, final LuaValue interactCallback) {
RPGVillager villager = new RPGVillager(
options.get("name").checkjstring(),
true,
new Location(
Bukkit.getWorld(options.get("world").checkjstring()),
options.get("x").checkdouble(),
options.get("y").checkdouble(),
options.get("z").checkdouble()),
new Vector(0, 0, 0), 1, true, new String[0]) {
@Override
public void onPlayerInteract(PlayerInteractEntityEvent event) {
interactCallback.checkfunction().invoke(CoerceJavaToLua.coerce(event));
}
};
villager.spawn();
RpgPlus.getPlugin(RpgPlus.class).getEntityManager().registerEntity(villager);
return LuaValue.NIL;
}
});
set("command", new TwoArgFunction() {
@Override
public LuaValue call(LuaValue command, final LuaValue handler) {
String[] commandPath;
if (command.istable()) {
commandPath = new String[command.checktable().length()];
for (int i = 0; i < commandPath.length; i++) {
commandPath[i] = command.get(i + 1).checkjstring();
}
} else {
commandPath = new String[]{command.checkjstring()};
}
RpgPlus.getPlugin(RpgPlus.class).getCommandManager().registerCommand(commandPath, new CommandHandler() {
@Override
public boolean onCommand(CommandSender sender, String command, List<String> args) {
LuaValue[] luaArgs = new LuaValue[args.size()];
for (int i = 0; i < luaArgs.length; i++) {
luaArgs[i] = LuaValue.valueOf(args.get(i));
}
return handler
.invoke(CoerceJavaToLua.coerce(sender), LuaValue.valueOf(command), LuaValue.varargsOf(luaArgs))
.optboolean(1, true);
}
});
return LuaValue.NIL;
}
});
set("playercommand", new TwoArgFunction() {
@Override
public LuaValue call(LuaValue command, final LuaValue handler) {
String[] commandPath;
if (command.istable()) {
commandPath = new String[command.checktable().length()];
for (int i = 0; i < commandPath.length; i++) {
commandPath[i] = command.get(i + 1).checkjstring();
}
} else {
commandPath = new String[]{command.checkjstring()};
}
RpgPlus.getPlugin(RpgPlus.class).getCommandManager().registerCommand(commandPath, new CommandHandler() {
@Override
public boolean onCommand(CommandSender sender, String command, List<String> args) {
if (sender instanceof Player) {
LuaValue[] luaArgs = new LuaValue[args.size()];
for (int i = 0; i < luaArgs.length; i++) {
luaArgs[i] = LuaValue.valueOf(args.get(i));
}
return handler
.invoke(CoerceJavaToLua.coerce(sender), LuaValue.valueOf(command), LuaValue.varargsOf(luaArgs))
.optboolean(1, true);
} else {
return false;
}
}
});
return LuaValue.NIL;
}
});
set("sendMessage", new VarArgFunction() {
@Override
public Varargs invoke(Varargs varargs) {
if (varargs.narg() >= 2) {
LuaTable players;
if (varargs.istable(1)) {
players = varargs.checktable(1);
} else {
players = LuaTable.listOf(new LuaValue[]{varargs.arg(1)});
}
for (int i = 1; i <= players.length(); i++) {
Player p = ScriptUtil.getPlayer(players.get(i));
for (int j = 2; j <= varargs.narg(); j++) {
p.sendMessage(varargs.checkjstring(j));
}
}
} else {
throw new LuaError("Invalid count of arguments. At least two arguments are required.");
}
return LuaValue.NIL;
}
});
set("broadcastMessage", new VarArgFunction() {
@Override
public Varargs invoke(Varargs varargs) {
if (varargs.narg() >= 1) {
for (int i = 1; i <= varargs.narg(); i++) {
plugin.getServer().broadcastMessage(varargs.checkjstring(i));
}
} else {
throw new LuaError("Invalid count of arguments. At least one argument are required.");
}
return LuaValue.NIL;
}
});
//Functions to register and unregister event handlers
ScriptEventManager events = new ScriptEventManager();
plugin.registerEvents(events);
events.installOn(this);
}
}
|
package de.prob2.ui.groovy.codecompletion;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.prob2.ui.groovy.GroovyConsole;
import de.prob2.ui.groovy.GroovyMethodOption;
import de.prob2.ui.groovy.MetaPropertiesHandler;
import de.prob2.ui.groovy.objects.GroovyClassPropertyItem;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.shape.Path;
import javafx.stage.Popup;
public class GroovyCodeCompletion extends Popup {
private final Logger logger = LoggerFactory.getLogger(GroovyCodeCompletion.class);
@FXML
private ListView<GroovyClassPropertyItem> lv_suggestions;
private ObservableList<GroovyClassPropertyItem> suggestions = FXCollections.observableArrayList();
private ScriptEngine engine;
private GroovyConsole parent;
private List<GroovyClassPropertyItem> currentObjectMethodsAndProperties;
private String currentSuggestion;
private int currentPosInSuggestion;
private int charCounterInSuggestion;
public GroovyCodeCompletion(FXMLLoader loader, ScriptEngine engine) {
loader.setLocation(getClass().getResource("groovy_codecompletion_popup.fxml"));
loader.setRoot(this);
loader.setController(this);
try {
loader.load();
} catch (IOException e) {
logger.error("loading fxml failed", e);
}
this.engine = engine;
this.parent = null;
this.currentObjectMethodsAndProperties = new ArrayList<>();
this.currentSuggestion = "";
this.currentPosInSuggestion = 0;
this.charCounterInSuggestion = 0;
lv_suggestions.setItems(suggestions);
lv_suggestions.setOnMouseClicked(this::chooseMethod);
lv_suggestions.setOnKeyPressed(e-> {
if(e.getCode().equals(KeyCode.ENTER)) {
//handle Enter in Groovy Code Completion
chooseMethod(e);
return;
}
if(";".equals(e.getText())) {
//handle Semicolon
chooseFirst(e);
return;
}
if(e.getCode().equals(KeyCode.LEFT) || e.getCode().equals(KeyCode.RIGHT)) {
handleArrowKey(e);
return;
}
if(e.getCode().equals(KeyCode.DELETE) || e.getCode().equals(KeyCode.BACK_SPACE)) {
handleDeletion(e);
return;
}
if(e.getText().length() == 1 && !".".equals(e.getText())) {
//handle Insert Char
filterSuggestions(e.getText(), CodeCompletionAction.INSERTION);
}
});
}
private void handleArrowKey(KeyEvent e) {
if(e.getCode().equals(KeyCode.LEFT)) {
if('.' == getParent().getCurrentLine().charAt(getParent().getCurrentPosInLine() - 1)) {
deactivate();
return;
}
currentPosInSuggestion = Math.max(0, currentPosInSuggestion-1);
} else if(e.getCode().equals(KeyCode.RIGHT)) {
if(';' == getParent().getCurrentLine().charAt(getParent().getCurrentPosInLine() - 1)) {
deactivate();
return;
}
currentPosInSuggestion = Math.min(currentSuggestion.length(), currentPosInSuggestion + 1);
}
filterSuggestions("", CodeCompletionAction.ARROWKEY);
}
private void handleDeletion(KeyEvent e) {
if(e.getCode().equals(KeyCode.DELETE) && currentPosInSuggestion != charCounterInSuggestion) {
charCounterInSuggestion
currentSuggestion = currentSuggestion.substring(0, currentPosInSuggestion) + currentSuggestion.substring(Math.min(currentPosInSuggestion + 1, currentSuggestion.length()), currentSuggestion.length());
} else if(e.getCode().equals(KeyCode.BACK_SPACE) && currentPosInSuggestion != 0) {
currentPosInSuggestion
charCounterInSuggestion
currentSuggestion = currentSuggestion.substring(0, currentPosInSuggestion) + currentSuggestion.substring(Math.max(currentPosInSuggestion + 1, currentSuggestion.length()), currentSuggestion.length());
}
filterSuggestions("", CodeCompletionAction.DELETION);
if('.' == getParent().getCurrentLine().charAt(getParent().getCurrentPosInLine() - 1)) {
deactivate();
}
}
private void chooseMethod(Event e) {
if(lv_suggestions.getSelectionModel().getSelectedItem() != null) {
getParent().fireEvent(new CodeCompletionEvent(e, lv_suggestions.getSelectionModel().getSelectedItem().getNameAndParams(), currentSuggestion.substring(0, currentPosInSuggestion)));
}
deactivate();
}
private void chooseFirst(Event e) {
if(lv_suggestions.getItems().get(0) != null) {
getParent().fireEvent(new CodeCompletionEvent(e, lv_suggestions.getItems().get(0).getNameAndParams(), currentSuggestion.substring(0, currentPosInSuggestion)));
}
deactivate();
}
private void filterSuggestions(String addition, CodeCompletionAction action) {
String currentInstruction = currentSuggestion;
if(action.equals(CodeCompletionAction.ARROWKEY)) {
currentInstruction = currentSuggestion.substring(0, currentPosInSuggestion);
} else if(action.equals(CodeCompletionAction.INSERTION)) {
currentSuggestion = new StringBuilder(currentSuggestion).insert(currentPosInSuggestion, addition.charAt(0)).toString();
currentPosInSuggestion++;
charCounterInSuggestion++;
currentInstruction = currentSuggestion;
}
refresh(currentInstruction);
}
private void refresh(String filter) {
suggestions.clear();
for(int i = 0; i < currentObjectMethodsAndProperties.size(); i++) {
GroovyClassPropertyItem suggestion = currentObjectMethodsAndProperties.get(i);
if(suggestion.getNameAndParams().startsWith(filter)) {
suggestions.add(suggestion);
}
}
lv_suggestions.getSelectionModel().selectFirst();
if(suggestions.isEmpty()) {
this.deactivate();
}
}
public void activate(GroovyConsole console, String currentLine) {
this.parent = console;
handleObjects(currentLine);
handleStaticClasses(currentLine);
showPopup(console);
}
private void handleStaticClasses(String currentLine) {
String[] methods = getMethodsFromCurrentLine(currentLine);
Package[] packages = Package.getPackages();
for (Package pack : packages) {
String fullClassName= pack.getName() + "." + methods[methods.length - 1];
Class <? extends Object> clazz = null;
try {
clazz = Class.forName(fullClassName);
fillAllMethodsAndProperties(clazz, GroovyMethodOption.STATIC);
showSuggestions(clazz, GroovyMethodOption.STATIC);
} catch (ClassNotFoundException e1) {
// Just try with the next package if the current fullClassName does not fit any classes
}
}
}
private void handleObjects(String currentLine) {
String[] methods = getMethodsFromCurrentLine(currentLine);
if(methods == null) {
return;
}
Object object = getObjectFromScope(methods[0]);
if(object == null) {
return;
}
Class<? extends Object> clazz = object.getClass();
for(int i = 1; i < methods.length; i++) {
fillAllMethodsAndProperties(clazz, GroovyMethodOption.NONSTATIC);
for(GroovyClassPropertyItem item: currentObjectMethodsAndProperties) {
if(item.getNameAndParams().equals(methods[i])) {
clazz = item.getReturnTypeClass();
break;
}
if(item.equals(currentObjectMethodsAndProperties.get(currentObjectMethodsAndProperties.size() - 1))) {
return;
}
}
}
showSuggestions(clazz, GroovyMethodOption.NONSTATIC);
}
private String[] getMethodsFromCurrentLine(String currentLine) {
String currentInstruction = currentLine.substring(0, getParent().getCurrentPosInLine());
if(getParent().getCurrentPosInLine() == 0 || currentInstruction.charAt(getParent().getCurrentPosInLine() - 1) == ';') {
return null;
}
currentInstruction = currentInstruction.replaceAll("\\s","");
currentInstruction = splitBraces(currentInstruction);
String[] currentObjects = currentInstruction.split(";");
String[] methods = currentObjects[currentObjects.length-1].split("\\.");
return methods;
}
private void fillAllMethodsAndProperties(Class <? extends Object> clazz, GroovyMethodOption option) {
fillMethodsAndProperties(clazz, option);
MetaPropertiesHandler.handleMethods(clazz, currentObjectMethodsAndProperties, option);
MetaPropertiesHandler.handleProperties(clazz, currentObjectMethodsAndProperties);
}
public String splitBraces(String currentInstruction) {
char[] instruction = currentInstruction.toCharArray();
String result = "";
for(int i = 0; i < instruction.length; i++) {
if(instruction[i] == '(' && instruction[i+1] != ')') {
result += ";";
} else {
result += instruction[i];
}
}
return result;
}
private Object getObjectFromScope(String currentLine) {
Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
Bindings globalScope = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
Object object = null;
if(engineScope.keySet().contains(currentLine)) {
object = engineScope.get(currentLine);
} else if(globalScope.keySet().contains(currentLine)) {
object = globalScope.get(currentLine);
}
return object;
}
public GroovyConsole getParent() {
return parent;
}
private void showPopup(GroovyConsole console) {
if(suggestions.isEmpty()) {
return;
}
lv_suggestions.getSelectionModel().selectFirst();
Point2D point = findCaretPosition(findCaret(console));
double x = point.getX() + 10;
double y = point.getY() + 20;
this.show(console, x, y);
}
public void deactivate() {
suggestions.clear();
currentObjectMethodsAndProperties.clear();
currentSuggestion ="";
currentPosInSuggestion = 0;
charCounterInSuggestion = 0;
this.hide();
}
private void fillMethodsAndProperties(Class <? extends Object> clazz, GroovyMethodOption option) {
for(Method m : clazz.getMethods()) {
currentObjectMethodsAndProperties.add(new GroovyClassPropertyItem(m));
}
for(Field f : clazz.getFields()) {
currentObjectMethodsAndProperties.add(new GroovyClassPropertyItem(f));
}
}
private void showSuggestions(Class <? extends Object> clazz, GroovyMethodOption option) {
currentObjectMethodsAndProperties.clear();
fillMethodsAndProperties(clazz, option);
MetaPropertiesHandler.handleMethods(clazz, currentObjectMethodsAndProperties, option);
MetaPropertiesHandler.handleProperties(clazz, currentObjectMethodsAndProperties);
suggestions.addAll(currentObjectMethodsAndProperties);
}
public boolean isVisible() {
return this.isShowing();
}
private Path findCaret(Parent parent) {
for (Node node : parent.getChildrenUnmodifiable()) {
if (node instanceof Path) {
return (Path) node;
} else if (node instanceof Parent) {
Path caret = findCaret((Parent) node);
if (caret != null) {
return caret;
}
}
}
return null;
}
private Point2D findCaretPosition(Node node) {
double x = 0;
double y = 0;
if(node == null) {
return null;
}
for (Node n = node; n != null; n=n.getParent()) {
Bounds parentBounds = n.getBoundsInParent();
x += parentBounds.getMinX();
y += parentBounds.getMinY();
}
if(node.getScene() != null) {
Scene scene = node.getScene();
x += scene.getX() + scene.getWindow().getX();
y += scene.getY() + scene.getWindow().getY();
x = Math.min(scene.getWindow().getX() + scene.getWindow().getWidth() - 20, x);
y = Math.min(scene.getWindow().getY() + scene.getWindow().getHeight() - 20, y);
}
return new Point2D(x,y);
}
}
|
package de.retest.recheck.ui.diff;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAttribute;
import lombok.Data;
import lombok.RequiredArgsConstructor;
@Data
@RequiredArgsConstructor
public class ElementIdentificationWarning implements Serializable {
private static final long serialVersionUID = 1L;
@XmlAttribute
private final String testClassName;
@XmlAttribute
@SuppressWarnings( "unused" )
private ElementIdentificationWarning() {
testClassName = null;
}
}
|
package authoringEnvironment.objects;
import java.util.ArrayList;
import java.util.List;
import authoringEnvironment.Controller;
import authoringEnvironment.DataFormatException;
import authoringEnvironment.MissingInformationException;
import authoringEnvironment.ProjectReader;
/**
* Extends FlowEditor
*
* @author Megan Gutter
* @author Johnny Kumpf
*
*/
public class WaveStrip extends FlowStrip {
private Controller myController;
private static final String WAVE = "Wave";
public WaveStrip (String type, String componentName, Controller c) {
super(type, componentName, c);
myController = c;
}
@Override
protected void addAtLeftOfRow () {
}
@Override
protected void saveData (String componentName) {
List<String> partFileNames = new ArrayList<String>();
List<Double> delays = new ArrayList<Double>();
List<Double> times = new ArrayList<Double>();
times.add(0.0);
for (FlowView unit : myComponents) {
partFileNames.addAll(unit.getFileNames());
delays.addAll(unit.getDelays());
}
for (Double d : delays) {
Double all = 0.0;
for (Double t : times)
all += t;
times.add(all + d);
}
List<Object> data = new ArrayList<Object>();
data.add(partFileNames);
data.add(times);
try {
if (myKey.equals(Controller.KEY_BEFORE_CREATION))
myKey = myController.addPartToGame(WAVE, componentName,
ProjectReader.getParamsNoTypeOrName(WAVE), data);
else
myKey =
myController.addPartToGame(myKey, WAVE, componentName,
ProjectReader.getParamsNoTypeOrName(WAVE), data);
}
catch (MissingInformationException | DataFormatException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package de.uni_potsdam.hpi.bpt.bp2014.jcore.rest;
import de.uni_potsdam.hpi.bpt.bp2014.database.DbActivityInstance;
import de.uni_potsdam.hpi.bpt.bp2014.database.DbEmailConfiguration;
import de.uni_potsdam.hpi.bpt.bp2014.database.DbScenario;
import de.uni_potsdam.hpi.bpt.bp2014.database.DbScenarioInstance;
import de.uni_potsdam.hpi.bpt.bp2014.jcore.ExecutionService;
import de.uni_potsdam.hpi.bpt.bp2014.util.JsonUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.annotation.XmlRootElement;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
/**
* This class implements the REST interface of the JEngine core.
* The core module provides methods to execute PCM instances
* and to access the date inside the engine.
* This REST interface provides methods to access this information
* and to control the instances.
* Methods which are necessary for the controlling can be found
* inside the {@link de.uni_potsdam.hpi.bpt.bp2014.jcore.ExecutionService}.
* This class will use {@link de.uni_potsdam.hpi.bpt.bp2014.database.Connection}
* to access the database directly.
*/
@Path("interface/v2")
public class RestInterface {
/**
* This method allows to give an overview of all scenarios.
* The response will return a JSON-Array containing the basic
* information of all scenarios currently inside the database.
* If different versions of an scenarios exist only the latest
* ones will be added to the json.
*
* @param filterString Specifies a search. Only scenarios which
* name contain the specified string will be
* returned.
* @return Returns a JSON-Object with an Array with entries for
* every Scenario.
* Each Entry is a JSON-Object with a label and id of a scenario.
*/
@GET
@Path("scenario")
@Produces(MediaType.APPLICATION_JSON)
public Response getScenarios(@QueryParam("filter") String filterString) {
DbScenario scenario = new DbScenario();
Map<Integer, String> scenarios;
if (filterString == null || filterString.equals("")) {
scenarios = scenario.getScenarios();
} else {
scenarios = scenario.getScenariosLike(filterString);
}
//TODO: add links to detail REST calls for each scenarios
return Response
.ok()
.type(MediaType.APPLICATION_JSON)
.entity(mapToKeysAndResults(scenarios, "ids", "labels").toString())
.build();
}
/**
* This method provides information about one scenario.
* The scenario is specified by an given id.
* The response of this request will contain a valid JSON-Object
* containing detailed information about the scenario.
* If there is no scenario with the specific id a 404 will be returned,
* with a meaningful error message.
*
* @param scenarioID The Id of the scenario used inside the database.
* @return Returns a JSON-Object with detailed information about one scenario.
* The Information contain the id, label, number of instances, latest version
* and more.
*/
@GET
@Path("scenario/{scenarioID}")
@Produces(MediaType.APPLICATION_JSON)
public Response getScenario(@PathParam("scenarioID") int scenarioID) {
DbScenario dbScenario = new DbScenario();
Map<String, Object> data = dbScenario.getScenarioDetails(scenarioID);
//TODO: add links to detail REST calls for scenarioInstance overview
//TODO: add link to detail REST call to create new scenarioInstance
if (data.isEmpty()) {
return Response
.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON)
.entity("{}")
.build();
}
return Response
.ok()
.type(MediaType.APPLICATION_JSON)
.entity(new JSONObject(data).toString())
.build();
}
/**
* This method provides information about all email Tasks inside
* a given scenario.
* The information consists of the id and the label.
* A Json Object will be returned with an array of ids and a Map
* from ids to labels.
*
* @param scenarioID The ID of the scenario, its mail tasks will be returned.
* @param filterString A Filter String, only mail tasks with a label containing
* this filter String will be returned.
* @return The JSON Object with ids and labels.
*/
@GET
@Path("scenario/{scenarioID}/emailtask")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllEmailTasks(
@PathParam("scenarioID") int scenarioID,
@QueryParam("filter") String filterString) {
DbScenario scenario = new DbScenario();
DbEmailConfiguration mail = new DbEmailConfiguration();
//TODO: add links to detail REST calls for each emailtask
if (!scenario.existScenario(scenarioID)) {
return Response
.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON)
.entity("{}")
.build();
}
String jsonRepresentation = JsonUtil.JsonWrapperLinkedList(mail.getAllEmailTasksForScenario(scenarioID));
return Response.ok(jsonRepresentation, MediaType.APPLICATION_JSON).build();
}
/**
* This method provides information about an email Task.
* It will return a JSON-Object with information about the mail
* configuration.
* A Configuration contains a receiver, a subject and a content.
* A Mail task is specified by:
*
* @param scenarioID The ID of the scenario model.
* @param mailTaskID The control node ID of the mail Task.
* @return Returns a 404 if the mail Task or scenario does not exist
* and a 200 (OK) with a JSON-Object if the emailTask was found.
*/
@GET
@Path("scenario/{scenarioID}/emailtask/{emailTaskID}")
@Produces(MediaType.APPLICATION_JSON)
public Response getEmailTaskConfiguration(
@PathParam("scenarioID") int scenarioID,
@PathParam("emailTaskID") int mailTaskID) {
DbScenario scenario = new DbScenario();
DbEmailConfiguration mail = new DbEmailConfiguration();
EmailConfigJaxBean mailConfig = new EmailConfigJaxBean();
mailConfig.receiver = mail.getReceiverEmailAddress(mailTaskID);
if (!scenario.existScenario(scenarioID) || mailConfig.receiver.equals("")) {
return Response
.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON)
.entity("{}")
.build();
}
mailConfig.content = mail.getMessage(mailTaskID);
mailConfig.subject = mail.getSubject(mailTaskID);
return Response.ok(mailConfig, MediaType.APPLICATION_JSON).build();
}
/**
* This method provides information about all instances of one scenario.
* The scenario is specified by an given id.
* If there is no scenario with the specific id a 404 response with a meaningful
* error message will be returned.
* If the Scenario exists a JSON-Array containing JSON-Objects with
* important information about an instance of the scenario will be returned.
*
* @param scenarioID The id of the scenario which instances should be returned.
* @param filterString Specifies a search. Only scenarios which
* name contain the specified string will be
* returned.
* @return A JSON-Object with an array of information about all instances of
* one specified scenario. The information contains the id and name.
*/
@GET
@Path("scenario/{scenarioID}/instance")
@Produces(MediaType.APPLICATION_JSON)
public Response getScenarioInstances(
@PathParam("scenarioID") int scenarioID,
@QueryParam("filter") String filterString) {
ExecutionService executionService = new ExecutionService();
if (!executionService.existScenario(scenarioID)) {
return Response
.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON)
.entity("{\"error\":\"Scenario not found!\"}")
.build();
}
DbScenarioInstance instance = new DbScenarioInstance();
JSONObject result = new JSONObject();
Map<Integer, String> data = instance.getScenarioInstancesLike(scenarioID, filterString);
result.put("ids", new JSONArray(data.keySet()));
result.put("labels", new JSONObject(data));
//TODO: add links to detail REST calls for each scenarioinstance
return Response
.ok(result.toString(), MediaType.APPLICATION_JSON)
.build();
}
/**
* Creates a new instance of a specified scenario.
* This method assumes that the name of then new instance will be the same
* as the name of the scenario.
* Hence no additional information should be transmitted.
* The response will imply if the post was successful.
*
* @param scenarioID the id of the scenario.
* @return The Response of the POST. The Response code will be
* either a 201 (CREATED) if the post was successful or 400 (BAD_REQUEST)
* if the scenarioID was invalid.
* The content of the Response will be a JSON-Object containing information
* about the new instance.
*/
public Response startNewInstance(@PathParam("scenarioID") int scenarioID) {
ExecutionService executionService = new ExecutionService();
//TODO: add link to detail REST call for more information about new scenarioinstanceID
if (executionService.existScenario(scenarioID)) {
return Response.status(Response.Status.CREATED)
.type(MediaType.APPLICATION_JSON)
.entity("{\"id\":" + executionService.startNewScenarioInstance(scenarioID) + "}")
.build();
} else {
return Response.status(Response.Status.BAD_REQUEST)
.type(MediaType.APPLICATION_JSON)
.entity("{\"error\":\"The Scenario could not be found!\"}")
.build();
}
}
/**
* Creates a new instance of a specified scenario.
* This method assumes that the new instance will be named.
* The name will be received as a JSON-Object inside the request
* Body.
* The JSON should have the format
* {@code {"name": <nameOfInstance>}}.
* The response will imply if the post was successful.
*
* @param scenarioID the id of the scenario.
* @param name The name, which will be used for the new instance.
* @return The Response of the POST. The Response code will be
* either a 201 (CREATED) if the post was successful or 400 (BAD_REQUEST)
* if the scenarioID was invalid.
* The content of the Response will be a JSON-Object containing information
* about the new instance.
*/
@POST
@Path("scenario/{scenarioID}/instance")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response startNewNamedInstance(@PathParam("scenarioID") int scenarioID, NamedJaxBean name) {
if (name == null) {
return startNewInstance(scenarioID);
}
ExecutionService executionService = new ExecutionService();
//TODO: add link to detail REST call for more information about new scenarioinstanceID
if (executionService.existScenario(scenarioID)) {
DbScenarioInstance instance = new DbScenarioInstance();
return Response.status(Response.Status.CREATED)
.type(MediaType.APPLICATION_JSON)
.entity("{\"id\":" + instance.createNewScenarioInstance(scenarioID, name.name) + "}")
.build();
} else {
return Response.status(Response.Status.BAD_REQUEST)
.type(MediaType.APPLICATION_JSON)
.entity("{\"error\":\"The Scenario could not be found!\"}")
.build();
}
}
// TODO: Change the state of an instance via POST
/**
* This method provides detailed information about a scenario instance.
* The information will contain the id, name, parent scenario and the
* number of activities in the different states.
* The Response is JSON-Object.
*
* @param scenarioID The ID of the scenario.
* @param instanceID The ID of the instance.
* @return Will return a Response with a JSON-Object body, containing
* the information about the instance.
* If the instance ID or both are incorrect 404 (NOT_FOUND) will be
* returned.
* If the scenario ID is wrong but the instance ID is correct a 301
* (REDIRECT) will be returned.
* If both IDs are correct a 200 (OK) with the expected JSON-Content
* will be returned.
*/
@GET
@Path("scenario/{scenarioID}/instance/{instanceID}")
@Produces(MediaType.APPLICATION_JSON)
public Response getScenarioInstance(
@PathParam("scenarioID") int scenarioID,
@PathParam("instanceID") int instanceID) {
ExecutionService executionService = new ExecutionService();
DbScenarioInstance instance = new DbScenarioInstance();
//TODO: add links to detail REST calls for more information about each activity instance
if (!executionService.existScenarioInstance(instanceID)) {
return Response.status(Response.Status.NOT_FOUND)
.entity("{\"message\":\"There is no instance with the id " + instanceID + "\"}")
.type(MediaType.APPLICATION_JSON)
.build();
} else if (!executionService.existScenario(scenarioID)) {
scenarioID = instance.getScenarioID(instanceID);
try {
return Response
.seeOther(new URI("interface/v2/scenario/" + scenarioID + "/instance/" + instanceID))
.build();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return Response
.ok((new JSONObject(instance.getInstanceMap(instanceID))).toString(),
MediaType.APPLICATION_JSON)
.build();
}
/**
* Returns a JSON-Object containing information about all activity
* instances of a specified scenario instance.
* The JSON-Object will group the activities regarding their state.
* If the scenario instance does not exist, the response code will
* specify the error which occurred.
*
* @param scenarioID The id of the scenario
* @param instanceID The id of the instance.
* @param filterString Defines a search strings. Only activities
* with a label containing this String will be
* shown.
* @return A Response with the status and content of the request.
* A 200 (OK) implies that the instance was found and the
* result contains the JSON-Object.
* If only the scenario ID is incorrect a 301 (REDIRECT)
* will point to the correct URL.
* If the instance ID is incorrect a 404 (NOT_FOUND) will
* be returned.
* TODO: Use the ExecutionService instead - be aware that using the E.S. leads to state changes.
*/
@GET
@Path("scenario/{scenarioID}/instance/{instanceID}/activity")
@Produces(MediaType.APPLICATION_JSON)
public Response getActivitiesOfInstance(
@PathParam("scenarioID") int scenarioID,
@PathParam("instanceID") int instanceID,
@QueryParam("filter") String filterString,
@QueryParam("status") String state) {
ExecutionService executionService = new ExecutionService();
if (!executionService.existScenarioInstance(instanceID)) {
return Response.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON)
.entity("{\"message\":\"There is no instance with id" + instanceID + "\"}")
.build();
} else if (!executionService.existScenario(scenarioID)) {
try {
return Response.seeOther(new URI("interface/v2/scenario/" +
executionService.getScenarioIDForScenarioInstance(instanceID) +
"/instance/" + instanceID + "/activity")).build();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
if ((filterString == null || filterString.isEmpty()) && (state == null || state.isEmpty())) {
return getAllActivitiesOfInstance(instanceID);
} else if ((filterString == null || filterString.isEmpty())) {
return getAllActivitiesOfInstanceWithState(instanceID, state);
} else if ((state == null || state.isEmpty())) {
return getAllActivitiesOfInstanceWithFilter(instanceID, filterString);
} else {
return getAllActivitiesWithFilterAndState(instanceID, filterString, state);
}
}
/**
* Returns a Response object.
* The Object will be either a 200 with the activities in an JSON-Object
* or an 400 with an error message if the state is invalid
*
* @param instanceID The id of the scenario instance
* @param filterString the filter string to be applied
* @param state the state of the activity
* @return The Response object as described above.
*/
private Response getAllActivitiesWithFilterAndState(int instanceID, String filterString, String state) {
String states[] = {"enabled", "terminated"};
if ((new LinkedList<>(Arrays.asList(states))).contains(state)) {
DbActivityInstance activityInstance = new DbActivityInstance();
Map<Integer, Map<String, Object>> instances =
activityInstance.getMapForActivityInstancesWithFilterAndState(instanceID, filterString, state);
JSONObject result = buildJSONObjectForActivities(instances);
return Response
.ok(result.toString(), MediaType.APPLICATION_JSON)
.build();
}
return Response.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON)
.entity("{\"error\":\"The state is not allowed " + state + " \"}")
.build();
}
/**
* Returns a Response Object.
* The Response Object will be a 200 with JSON content.
* The Content will be a JSON Object, containing information about activities.
* The Label of the activities mus correspond to the filter String and be
* part of the scenario instance specified by the instanceID.
* @param instanceID The id of the scenario instance.
* @param filterString The string which will be the filter condition for the activity ids.
* @return The created Response object with a 200 and a JSON.
*/
private Response getAllActivitiesOfInstanceWithFilter(int instanceID, String filterString) {
DbActivityInstance activityInstance = new DbActivityInstance();
Map<Integer, Map<String, Object>> instances;
instances = activityInstance.getMapForActivityInstancesWithFilter(instanceID, filterString);
JSONObject result = buildJSONObjectForActivities(instances);
return Response
.ok(result.toString(), MediaType.APPLICATION_JSON)
.build();
}
private Response getAllActivitiesOfInstanceWithState(int instanceID, String state) {
String states[] = {"enabled", "terminated"};
if ((new LinkedList<>(Arrays.asList(states))).contains(state)) {
DbActivityInstance activityInstance = new DbActivityInstance();
Map<Integer, Map<String, Object>> instances;
instances = activityInstance.getMapForActivityInstancesWithState(instanceID, state);
JSONObject result = buildJSONObjectForActivities(instances);
return Response
.ok(result.toString(), MediaType.APPLICATION_JSON)
.build();
}
return Response.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON)
.entity("{\"error\":\"The state is not allowed " + state + " \"}")
.build();
}
/**
* Builds a JSON Object for a Map with data
* corresponding to a set of activities.
*
* @param instances The Map containing information about the activity instances.
* We Assume that the key is a the id and the value is a Map
* from String to Object with the properties of the instance.
* @return The newly created JSON Object with the activity data.
*/
private JSONObject buildJSONObjectForActivities(Map<Integer, Map<String, Object>> instances) {
JSONObject result = new JSONObject();
result.put("ids", instances.keySet());
JSONArray activities = new JSONArray();
for (Map<String, Object> value : instances.values()) {
activities.put(new JSONObject(value));
}
result.put("activities", activities);
return result;
}
/**
* Returns a Response Object for all activities with the instance Id.
* We assume that the instanceId is correct.
* The Response will be a 200 with json content.
* The Content will be a json object with information about each activity.
*
* @param instanceID the instance id of the scenario instance.
* @return The Response Object, with 200 and JSON Content.
*/
private Response getAllActivitiesOfInstance(int instanceID) {
DbActivityInstance activityInstance = new DbActivityInstance();
Map<Integer, Map<String, Object>> instances = activityInstance.getMapForAllActivityInstances(instanceID);
JSONObject result = new JSONObject();
result.put("ids", instances.keySet());
JSONArray activities = new JSONArray();
for (Map<String, Object> value : instances.values()) {
activities.put(new JSONObject(value));
}
result.put("activities", activities);
return Response
.ok(result.toString(), MediaType.APPLICATION_JSON)
.build();
}
/**
* Updates the state of an activity instance.
* The state will be changed to the specified one.
* The activity Instance is specified by:
*
* @param scenarioID The id of a scenario model.
* @param scenarioInstanceID the id of an scenario instance.
* @param activityID the control node id of the activity.
* @param state the new status of the activity.
* @return Returns a Response, the response code implies the
* outcome of the POST-Request.
* A 202 (ACCEPTED) means that the POST was successful.
* A 400 (BAD_REQUEST) if the transition was not allowed.
*/
@POST
@Path("scenario/{scenarioID}/instance/{instanceID}/activity/{activityID}/")
public Response updateActivityStatus(@PathParam("scenarioID") String scenarioID,
@PathParam("instanceID") int scenarioInstanceID,
@PathParam("activityID") int activityID,
@QueryParam("status") String state) {
boolean result;
ExecutionService executionService = new ExecutionService();
executionService.openExistingScenarioInstance(new Integer(scenarioID), scenarioInstanceID);
switch (state) {
case "begin":
result = executionService.beginActivity(scenarioInstanceID, activityID);
break;
case "terminate":
result = executionService.terminateActivity(scenarioInstanceID, activityID);
break;
default:
return Response.status(Response.Status.BAD_REQUEST)
.type(MediaType.APPLICATION_JSON)
.entity("{\"error\":\"The state transition " + state + "is unknown\"}")
.build();
}
if (result) {
return Response.status(Response.Status.ACCEPTED)
.type(MediaType.APPLICATION_JSON)
.entity("{\"message\":\"activity state changed.\"}")
.build();
} else {
return Response.status(Response.Status.BAD_REQUEST)
.type(MediaType.APPLICATION_JSON)
.entity("{\"error\":\"impsossible to " + (state.equals("begin") ? "start" : "terminate") +
"activity with id" + activityID + "\"}")
.build();
}
}
/**
* Returns a JSON-Object, which contains information about all
* data objects of a specified scenario instance.
* The data contains the id, label and state.
*
* @param scenarioID The ID of the scenario model.
* @param instanceID The ID of the scenario instance.
* @param filterString A String which specifies a filter. Only Data
* Objects with a label containing this string
* will be returned.
* @return A Response with the outcome of the GET-Request. The Response
* will be a 200 (OK) if the specified instance was found. Hence
* the JSON-Object will be returned.
* It will be a 301 (REDIRECT) if the scenarioID is wrong.
* And a 404 if the instance id is wrong.
*/
@GET
@Path("scenario/{scenarioID}/instance/{instanceID}/dataobject")
@Produces(MediaType.APPLICATION_JSON)
public Response getDataObjects(
@PathParam("scenarioID") int scenarioID,
@PathParam("instanceID") int instanceID,
@QueryParam("filter") String filterString) {
ExecutionService executionService = new ExecutionService();
//TODO: add link to detail REST call for more information about each dataobject
if (!executionService.existScenarioInstance(instanceID)) {
return Response.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON)
.entity("{\"error\":\"There is no instance with the id " + instanceID + "\"}")
.build();
} else if (!executionService.existScenario(scenarioID)) {
try {
return Response.seeOther(new URI("interface/v2/scenario/" +
executionService.getScenarioIDForScenarioInstance(instanceID) +
"/instance/" + instanceID + "/dataobject")).build();
} catch (URISyntaxException e) {
return Response.serverError().build();
}
}
executionService.openExistingScenarioInstance(scenarioID, instanceID);
LinkedList<Integer> dataObjects = executionService.getAllDataObjectIDs(instanceID);
HashMap<Integer, String> states = executionService.getAllDataObjectStates(instanceID);
HashMap<Integer, String> labels = executionService.getAllDataObjectNames(instanceID);
if (filterString != null && !filterString.isEmpty()) {
for (Map.Entry<Integer, String> labelEntry : labels.entrySet()) {
if (!labelEntry.getValue().contains(filterString)) {
dataObjects.remove(labelEntry.getKey());
states.remove(labelEntry.getKey());
labels.remove(labelEntry.getKey());
}
}
}
JSONObject result = buildListForDataObjects(dataObjects, states, labels);
return Response.ok(result.toString(),
MediaType.APPLICATION_JSON).build();
}
/**
* This method provides detailed information about an data Object.
* The information contain the id, parent scenario instance, label
* and the current state,
* This information will be provided as a JSON-Object.
* A Data object is specified by:
*
* @param scenarioID The scenario Model ID.
* @param instanceID The scenario Instance ID.
* @param dataObjectID The Data Object ID.
* @return Returns a JSON-Object with information about the dataObject,
* the response code will be a 200 (OK).
* If the data object does not exist a 404 (NOT_FOUND) will not be
* returned.
* If the instance does exist but some params are wrong a 301
* (REDIRECT) will be returned.
*/
@GET
@Path("scenario/{scenarioID}/instance/{instanceID}/dataobject/{dataObjectID}")
@Produces(MediaType.APPLICATION_JSON)
public Response getDataObject(
@PathParam("scenarioID") int scenarioID,
@PathParam("instanceID") int instanceID,
@PathParam("dataObjectID") int dataObjectID) {
ExecutionService executionService = new ExecutionService();
if (!executionService.existScenarioInstance(instanceID)) {
return Response.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON)
.entity("{\"error\":\"There is no instance with the id " + instanceID + "\"}")
.build();
} else if (!executionService.existScenario(scenarioID)) {
try {
return Response.seeOther(new URI("interface/v2/scenario/" +
executionService.getScenarioIDForScenarioInstance(instanceID) +
"/instance/" + instanceID + "/dataobject/" + dataObjectID)).build();
} catch (URISyntaxException e) {
return Response.serverError().build();
}
}
executionService.openExistingScenarioInstance(scenarioID, instanceID);
LinkedList<Integer> dataObjects = executionService.getAllDataObjectIDs(instanceID);
HashMap<Integer, String> states = executionService.getAllDataObjectStates(instanceID);
HashMap<Integer, String> labels = executionService.getAllDataObjectNames(instanceID);
if (!dataObjects.contains(new Integer(dataObjectID))) {
return Response.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON)
.entity("{\"error\":\"There is no dataobject with the id " + dataObjectID +
" for the scenario instance " + instanceID + "\"}")
.build();
}
DataObjectJaxBean dataObject = new DataObjectJaxBean();
dataObject.id = dataObjectID;
dataObject.label = labels.get(new Integer(dataObjectID));
dataObject.state = states.get(new Integer(dataObjectID));
return Response.ok(dataObject, MediaType.APPLICATION_JSON).build();
}
/*
* Helper
*/
/**
* Creates an array of DataObjects.
* The data objects will be created out of the information received from the execution Service.
* The array elements will be of type {@link RestInterface.DataObjectJaxBean), hence JSON and
* XML can be generated automatically.
*
* @param dataObjectIds an Arraqy of IDs used for the dataobjects inside the database.
* @param states The states, mapped from dataobject database id to state (String)
* @param labels The labels, mapped from dataobject database id to label (String)
* @return A array with a DataObject for each entry in dataObjectIds
*/
private JSONObject buildListForDataObjects(
LinkedList<Integer> dataObjectIds,
HashMap<Integer, String> states,
HashMap<Integer, String> labels) {
JSONObject result = new JSONObject();
result.put("ids", dataObjectIds);
JSONObject results = new JSONObject();
for (int i = 0; i < dataObjectIds.size(); i++) {
Integer id = dataObjectIds.get(i);
JSONObject dataObject = new JSONObject();
dataObject.put("id", id);
dataObject.put("label", labels.get(id));
dataObject.put("state", states.get(id));
results.put("" + id, dataObject);
}
result.put("results", results);
return result;
}
/**
* Creates a JSON object from an HashMap.
* The keys will be listed seperatly.
*
* @param data The HashMap which contains the data of the Object
* @param keyLabel The name which will be used
* @param resultLabel The label of the results.
* @return The newly created JSON Object.
*/
public JSONObject mapToKeysAndResults(Map data, String keyLabel, String resultLabel) {
JSONObject result = new JSONObject();
result.put(keyLabel, new JSONArray(data.keySet()));
result.put(resultLabel, data);
return result;
}
/**
* This is a data class for the email configuration.
* It is used by Jersey to deserialize JSON.
* Also it can be used for tests to provide the correct contents.
* This class in particular is used by the POST for the email configuration.
* See the {@link #updateEmailConfiguration(int,
* de.uni_potsdam.hpi.bpt.bp2014.jcore.rest.RestInterface.EmailConfigJaxBean)}
* updateEmailConfiguration} method for more information.
*/
@XmlRootElement
public static class EmailConfigJaxBean {
/**
* The receiver of the email.
* coded as an valid email address (as String)
*/
public String receiver;
/**
* The subject of the email.
* Could be any String but null.
*/
public String subject;
/**
* The content of the email.
* Could be any String but null.
*/
public String content;
}
/**
* A JAX bean which is used for a naming an entity.
* Therefor a name can be transmitted.
*/
@XmlRootElement
public static class NamedJaxBean {
/**
* The name which should be assigned to the entity.
*/
public String name;
}
/**
* A JAX bean which is used for dataobject data.
* It contains the data of one dataobject.
* It can be used to create a JSON Object
*/
@XmlRootElement
public static class DataObjectJaxBean {
/**
* The label of the data object.
*/
public String label;
/**
* The id the dataobject (not the instance) has inside
* the database
*/
public int id;
/**
* The state inside the database of the dataobject
* which is stored in the table.
* The label not the id will be holded.
*/
public String state;
}
}
|
package org.opennms.netmgt.poller.pollables;
import static org.easymock.EasyMock.anyInt;
import static org.easymock.EasyMock.endsWith;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.isA;
import static org.opennms.core.utils.InetAddressUtils.addr;
import java.io.File;
import java.io.FileWriter;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opennms.core.resource.Vault;
import org.opennms.core.utils.InetAddressUtils;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.config.DataSourceFactory;
import org.opennms.netmgt.config.PollOutagesConfigFactory;
import org.opennms.netmgt.config.PollerConfig;
import org.opennms.netmgt.config.poller.Package;
import org.opennms.netmgt.config.poller.Rrd;
import org.opennms.netmgt.dao.FilterDao;
import org.opennms.netmgt.dao.support.RrdTestUtils;
import org.opennms.netmgt.eventd.EventIpcManager;
import org.opennms.netmgt.eventd.EventIpcManagerFactory;
import org.opennms.netmgt.filter.FilterDaoFactory;
import org.opennms.netmgt.mock.EventAnticipator;
import org.opennms.netmgt.mock.MockDatabase;
import org.opennms.netmgt.mock.MockEventIpcManager;
import org.opennms.netmgt.mock.MockNetwork;
import org.opennms.netmgt.model.PollStatus;
import org.opennms.netmgt.model.events.EventBuilder;
import org.opennms.netmgt.poller.MonitoredService;
import org.opennms.netmgt.poller.ServiceMonitor;
import org.opennms.netmgt.rrd.RrdDataSource;
import org.opennms.netmgt.rrd.RrdStrategy;
import org.opennms.netmgt.rrd.RrdUtils;
import org.opennms.test.mock.EasyMockUtils;
import org.opennms.test.mock.MockLogAppender;
import org.springframework.core.io.FileSystemResource;
public class LatencyStoringServiceMonitorAdaptorTest {
private EasyMockUtils m_mocks = new EasyMockUtils();
private PollerConfig m_pollerConfig = m_mocks.createMock(PollerConfig.class);
// Cannot avoid this warning since there is no way to fetch the class object for an interface
// that uses generics
@SuppressWarnings("unchecked")
private RrdStrategy<Object,Object> m_rrdStrategy = m_mocks.createMock(RrdStrategy.class);
@Before
public void setUp() throws Exception {
MockLogAppender.setupLogging();
RrdTestUtils.initializeNullStrategy();
RrdUtils.setStrategy(m_rrdStrategy);
System.setProperty("opennms.home", "src/test/resources");
PollOutagesConfigFactory.init();
}
@After
public void tearDown() throws Throwable {
MockLogAppender.assertNoWarningsOrGreater();
}
@Test
public void testUpdateRrdWithLocaleThatUsesCommasForDecimals() throws Exception {
Locale defaultLocale = Locale.getDefault();
Locale.setDefault(Locale.FRENCH);
// Make sure we actually have a valid test
NumberFormat nf = NumberFormat.getInstance();
Assert.assertEquals("ensure that the newly set default locale (" + Locale.getDefault() + ") uses ',' as the decimal marker", "1,5", nf.format(1.5));
LatencyStoringServiceMonitorAdaptor adaptor = new LatencyStoringServiceMonitorAdaptor(null, m_pollerConfig, new Package());
LinkedHashMap<String, Number> map = new LinkedHashMap<String, Number>();
map.put("cheese", 1.5);
expect(m_pollerConfig.getStep(isA(Package.class))).andReturn(0).anyTimes();
expect(m_pollerConfig.getRRAList(isA(Package.class))).andReturn(new ArrayList<String>(0));
expect(m_rrdStrategy.getDefaultFileExtension()).andReturn(".rrd").anyTimes();
expect(m_rrdStrategy.createDefinition(isA(String.class), isA(String.class), isA(String.class), anyInt(), isAList(RrdDataSource.class), isAList(String.class))).andReturn(new Object());
m_rrdStrategy.createFile(isA(Object.class));
expect(m_rrdStrategy.openFile(isA(String.class))).andReturn(new Object());
m_rrdStrategy.updateFile(isA(Object.class), isA(String.class), endsWith(":1.5"));
m_rrdStrategy.closeFile(isA(Object.class));
m_mocks.replayAll();
adaptor.updateRRD("foo", InetAddress.getLocalHost(), "baz", map);
m_mocks.verifyAll();
Locale.setDefault(defaultLocale);
}
@Test
public void testThresholds() throws Exception {
EventBuilder bldr = new EventBuilder(EventConstants.HIGH_THRESHOLD_EVENT_UEI, "LatencyStoringServiceMonitorAdaptorTest");
bldr.setNodeid(1);
bldr.setInterface(addr("127.0.0.1"));
bldr.setService("ICMP");
EventAnticipator anticipator = new EventAnticipator();
anticipator.anticipateEvent(bldr.getEvent());
executeThresholdTest(anticipator);
anticipator.verifyAnticipated();
}
@Test
public void testThresholdsWithScheduledOutage() throws Exception {
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
sb.append("<outages>");
sb.append("<outage name=\"junit outage\" type=\"specific\">");
sb.append("<time begins=\"");
sb.append(formatter.format(new Date(System.currentTimeMillis() - 3600000)));
sb.append("\" ends=\"");
sb.append(formatter.format(new Date(System.currentTimeMillis() + 3600000)));
sb.append("\"/>");
sb.append("<interface address=\"match-any\"/>");
sb.append("</outage>");
sb.append("</outages>");
File file = new File("target/poll-outages.xml");
FileWriter writer = new FileWriter(file);
writer.write(sb.toString());
writer.close();
PollOutagesConfigFactory.setInstance(new PollOutagesConfigFactory(new FileSystemResource(file)));
PollOutagesConfigFactory.getInstance().afterPropertiesSet();
EventAnticipator anticipator = new EventAnticipator();
executeThresholdTest(anticipator);
anticipator.verifyAnticipated();
}
private void executeThresholdTest(EventAnticipator anticipator) throws Exception {
System.setProperty("opennms.home", "src/test/resources");
Map<String,Object> parameters = new HashMap<String,Object>();
parameters.put("rrd-repository", "/tmp");
parameters.put("ds-name", "icmp");
parameters.put("rrd-base-name", "icmp");
parameters.put("thresholding-enabled", "true");
FilterDao filterDao = m_mocks.createMock(FilterDao.class);
expect(filterDao.getActiveIPAddressList((String)EasyMock.anyObject())).andReturn(Collections.singletonList(addr("127.0.0.1"))).anyTimes();
FilterDaoFactory.setInstance(filterDao);
MonitoredService svc = m_mocks.createMock(MonitoredService.class);
expect(svc.getNodeId()).andReturn(1);
expect(svc.getIpAddr()).andReturn("127.0.0.1");
expect(svc.getAddress()).andReturn(InetAddressUtils.addr("127.0.0.1"));
expect(svc.getSvcName()).andReturn("ICMP");
ServiceMonitor service = m_mocks.createMock(ServiceMonitor.class);
PollStatus value = PollStatus.get(PollStatus.SERVICE_AVAILABLE, 100.0);
expect(service.poll(svc, parameters)).andReturn(value);
int step = 300;
List<String> rras = Collections.singletonList("RRA:AVERAGE:0.5:1:2016");
Package pkg = new Package();
Rrd rrd = new Rrd();
rrd.setStep(step);
rrd.setRra(rras);
pkg.setRrd(rrd);
expect(m_pollerConfig.getRRAList(pkg)).andReturn(rras);
expect(m_pollerConfig.getStep(pkg)).andReturn(step).anyTimes();
expect(m_rrdStrategy.getDefaultFileExtension()).andReturn(".rrd").anyTimes();
expect(m_rrdStrategy.createDefinition(isA(String.class), isA(String.class), isA(String.class), anyInt(), isAList(RrdDataSource.class), isAList(String.class))).andReturn(new Object());
m_rrdStrategy.createFile(isA(Object.class));
expect(m_rrdStrategy.openFile(isA(String.class))).andReturn(new Object());
m_rrdStrategy.updateFile(isA(Object.class), isA(String.class), endsWith(":100"));
m_rrdStrategy.closeFile(isA(Object.class));
MockEventIpcManager eventMgr = new MockEventIpcManager();
eventMgr.setEventAnticipator(anticipator);
eventMgr.setSynchronous(true);
EventIpcManager eventdIpcMgr = (EventIpcManager)eventMgr;
EventIpcManagerFactory.setIpcManager(eventdIpcMgr);
MockNetwork network = new MockNetwork();
network.setCriticalService("ICMP");
network.addNode(1, "testNode");
network.addInterface("127.0.0.1");
network.setIfAlias("eth0");
network.addService("ICMP");
network.addService("SNMP");
MockDatabase db = new MockDatabase();
db.populate(network);
db.update("update snmpinterface set snmpifname=?, snmpifdescr=? where id=?", "eth0", "eth0", 1);
DataSourceFactory.setInstance(db);
Vault.setDataSource(db);
m_mocks.replayAll();
LatencyStoringServiceMonitorAdaptor adaptor = new LatencyStoringServiceMonitorAdaptor(service, m_pollerConfig, pkg);
adaptor.poll(svc, parameters);
m_mocks.verifyAll();
}
@SuppressWarnings("unchecked")
private static <T> List<T> isAList(Class<T> clazz) {
return isA(List.class);
}
}
|
package eu.socialsensor.framework.client.dao.impl;
import eu.socialsensor.framework.client.dao.DyscoDAO;
import eu.socialsensor.framework.client.dao.MediaItemDAO;
import eu.socialsensor.framework.client.dao.WebPageDAO;
import eu.socialsensor.framework.client.search.Query;
import eu.socialsensor.framework.client.search.SearchEngineHandler;
import eu.socialsensor.framework.client.search.SearchEngineResponse;
import eu.socialsensor.framework.client.search.solr.SolrHandler;
import eu.socialsensor.framework.client.search.solr.SolrItemHandler;
import eu.socialsensor.framework.client.search.solr.SolrMediaItemHandler;
import eu.socialsensor.framework.client.search.solr.SolrWebPageHandler;
import eu.socialsensor.framework.client.search.visual.JsonResultSet;
import eu.socialsensor.framework.client.search.visual.JsonResultSet.JsonResult;
import eu.socialsensor.framework.client.search.visual.VisualIndexHandler;
import eu.socialsensor.framework.common.domain.Item;
import eu.socialsensor.framework.common.domain.MediaItem;
import eu.socialsensor.framework.common.domain.WebPage;
import eu.socialsensor.framework.common.domain.dimension.Dimension;
import eu.socialsensor.framework.common.domain.dysco.CustomDysco;
import eu.socialsensor.framework.common.domain.dysco.Dysco;
import eu.socialsensor.framework.common.domain.dysco.Dysco.DyscoType;
import eu.socialsensor.framework.common.domain.dysco.Entity;
import eu.socialsensor.framework.common.domain.dysco.Entity.Type;
import eu.socialsensor.framework.common.util.Util;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
/**
*
* @author etzoannos - e.tzoannos@atc.gr
*/
public class DyscoDAOImpl implements DyscoDAO {
SearchEngineHandler searchEngineHandler;
private MediaItemDAO mediaItemDAO;
private WebPageDAO webPageDAO;
private SolrItemHandler solrItemHandler;
private SolrMediaItemHandler solrMediaItemHandler;
private SolrWebPageHandler solrWebPageHandler;
private VisualIndexHandler visualIndexHandler;
public DyscoDAOImpl(String mongoHost, String webPageDB, String webPageColl, String mediaItemsDB, String mediaItemsColl,
String solrDyscoCollection, String solrItemCollection, String solrMediaItemCollection, String solrWebPageCollection,
String visualIndexService, String visualIndexCollection)
throws Exception {
searchEngineHandler = new SolrHandler(solrDyscoCollection, solrItemCollection);
try {
mediaItemDAO = new MediaItemDAOImpl(mongoHost, mediaItemsDB, mediaItemsColl);
webPageDAO = new WebPageDAOImpl(mongoHost, webPageDB, webPageColl);
solrItemHandler = SolrItemHandler.getInstance(solrItemCollection);
solrMediaItemHandler = SolrMediaItemHandler.getInstance(solrMediaItemCollection);
solrWebPageHandler = SolrWebPageHandler.getInstance(solrWebPageCollection);
visualIndexHandler = new VisualIndexHandler(visualIndexService, visualIndexCollection);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean insertDysco(Dysco dysco) {
return searchEngineHandler.insertDysco(dysco);
}
@Override
public boolean updateDysco(Dysco dysco) {
return searchEngineHandler.updateDysco(dysco);
}
@Override
public boolean destroyDysco(String id) {
// TODO: check if this is actually string or long - try to unify it
return searchEngineHandler.deleteDysco(id);
}
@Override
public List<Item> findDyscoItems(String id) {
SearchEngineResponse<Item> response = searchEngineHandler
.findAllDyscoItems(id);
List<Item> items = response.getResults();
return items;
}
@Override
public SearchEngineResponse<Item> findNDyscoItems(String id, int size) {
SearchEngineResponse<Item> response = searchEngineHandler.findNDyscoItems(id, size);
return response;
}
@Override
public List<Item> findSortedDyscoItems(String id, String fieldToSort,
ORDER order, int rows, boolean original) {
SearchEngineResponse<Item> response = searchEngineHandler
.findSortedItems(id, fieldToSort, order, rows, original);
List<Item> items = response.getResults();
return items;
}
@Override
public List<Item> findSortedDyscoItemsByQuery(Query query, String fieldToSort,
ORDER order, int rows, boolean original) {
SearchEngineResponse<Item> response = searchEngineHandler
.findSortedItems(query, fieldToSort, order, rows, original);
List<Item> items = response.getResults();
return items;
}
@Override
public Dysco findDysco(String id) {
return searchEngineHandler.findDysco(id);
}
@Override
public SearchEngineResponse<Dysco> findDyscosLight(Query query) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Dysco findDyscoLight(String id) {
return searchEngineHandler.findDysco(id);
}
@Override
public SearchEngineResponse<Item> findLatestItems(int count) {
return searchEngineHandler.findLatestItems(count);
}
@Override
public List<Dysco> findDyscoByTitle(String title) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<Dysco> findDyscoByContainingItem(Item item) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<Dysco> findDyscoByDimension(Dimension dim) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<Dysco> findCommunityRelatedDyscos(Dysco queryDysco) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<Dysco> findContentRelatedDyscos(Dysco queryDysco) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public SearchEngineResponse<Item> findItems(Query query) {
return searchEngineHandler.findItems(query);
}
@Override
public boolean updateDyscoWithoutItems(Dysco dysco) {
return searchEngineHandler.updateDyscoWithoutItems(dysco);
}
@Override
public SearchEngineResponse<Item> findNDyscoItems(String id, int size, boolean original) {
SearchEngineResponse<Item> response = searchEngineHandler.findNDyscoItems(id, size, original);
return response;
}
@Override
public List<Item> findTotalItems(String _query) {
List<Item> _totalItems;
SolrQuery totalQuery = new SolrQuery(_query);
//TODO: searchVar... maybe this should be -1 to get all
totalQuery.setRows(1000);
//TODO: see if we could minimize the fields returned for totalItems:
//links are needed for sure, maybe also sentiment which is used as facet
//totalQuery.setFields("links","sentiment");
_totalItems = solrItemHandler.findItems(totalQuery).getResults();
return _totalItems;
}
@Override
public List<Item> findTotalItems(List<String> dyscoIdsOfGroup) {
List<Item> _totalItems;
//getting items of the whole dysco group
//formulating the "find all items of dysco group" query
String totalItemsQuery;
//this means it's a trending Dysco
int count = 0;
String itemsOfGroupQuery = "dyscoId:(";
for (String dyscoIdToSearch : dyscoIdsOfGroup) {
if (count == 0) {
itemsOfGroupQuery = itemsOfGroupQuery + dyscoIdToSearch;
} else {
itemsOfGroupQuery = itemsOfGroupQuery + " OR " + dyscoIdToSearch;
}
count++;
}
itemsOfGroupQuery = itemsOfGroupQuery + ")";
totalItemsQuery = itemsOfGroupQuery;
SolrQuery totalQuery = new SolrQuery(totalItemsQuery);
//TODO: searchVar... maybe this should be -1 to get all
totalQuery.setRows(1000);
//TODO: see if we could minimize the fields returned for totalItems:
//links are needed for sure, maybe also sentiment which is used as facet
totalQuery.setFields("links", "sentiment");
_totalItems = solrItemHandler.findItems(totalQuery).getResults();
return _totalItems;
}
@Override
//TODO: I think we can get this directly from Solr
public List<String> findTotalUrls(List<Item> totalItems) {
//convert HashSet to ArrayList
Set<String> totalItemsUrls = new HashSet<String>();
for (Item totalItem : totalItems) {
URL[] totalItemLinks = totalItem.getLinks();
if (totalItemLinks != null) {
for (int i = 0; i < totalItemLinks.length; i++) {
totalItemsUrls.add(totalItemLinks[i].toString());
}
}
}
List<String> totalUrlsToSearch = new ArrayList<String>(totalItemsUrls);
return totalUrlsToSearch;
}
@Override
public List<Dysco> findRelatedTopics(Dysco dysco) {
List<Dysco> _relatedTopics = new ArrayList<Dysco>();
// if ((dysco.getDyscoGroup() != null) && (!dysco.getDyscoGroup().equals(""))) {
//// uncomment the following line for getting only the "deprecated" Dyscos
//// String relatedDyscosQuery = "dyscoGroup:" + dysco.getDyscoGroup() + " AND evolution:old";
// String relatedDyscosQuery = "dyscoGroup:" + dysco.getDyscoGroup();
// SolrQuery _solrQuery = new SolrQuery(relatedDyscosQuery);
// _solrQuery.setFields("id", "title", "creationDate");
// _solrQuery.addSortField("creationDate", SolrQuery.ORDER.desc);
// _solrQuery.setRows(4);
// _relatedTopics = handler.findDyscosLight(_solrQuery).getResults();
// List<Dysco> tempTopics = new ArrayList<Dysco>();
// //remove itself since it's included in the results (think of uncommenting the line above)
// for (Dysco relatedTopic : _relatedTopics) {
// if (!dysco.getId().equals(relatedTopic.getId())) {
// tempTopics.add(relatedTopic);
// _relatedTopics = tempTopics;
return _relatedTopics;
}
@Override
public SearchEngineResponse<Item> findItems(String query, List<String> filters, List<String> facets, String orderBy, Map<String, String> params, int size) {
return collectItemsByQuery(query, filters, facets, orderBy, params, size);
}
@Override
public SearchEngineResponse<Item> findItems(Dysco dysco, List<String> filters, List<String> facets, String orderBy, Map<String, String> params, int size) {
if (dysco.getDyscoType().equals(DyscoType.TRENDING)) {
postProcess(dysco);
List<eu.socialsensor.framework.common.domain.Query> queries = dysco.getSolrQueries();
return collectItemsByQueries(queries, filters, facets, orderBy, params, size);
} else {
CustomDysco customDysco = (CustomDysco) dysco;
List<eu.socialsensor.framework.common.domain.Query> queries = customDysco.getSolrQueries();
List<String> twitterMentions = customDysco.getMentionedUsers();
List<String> twitterUsers = customDysco.getTwitterUsers();
List<String> wordsToExclude = customDysco.getWordsToAvoid();
List<String> otherSocialNetworks = customDysco.getOtherSocialNetworks();
if(otherSocialNetworks != null && !otherSocialNetworks.isEmpty()) {
if(twitterUsers == null)
twitterUsers = new ArrayList<String>();
for(String url : otherSocialNetworks) {
try {
Map<String, String> parts = Util.findNetworkSource(url);
for(String username : parts.keySet()) {
twitterUsers.add(username);
}
} catch (Exception e) {
}
}
}
return collectItems(queries, twitterMentions, twitterUsers, wordsToExclude, filters, facets, orderBy, params, size);
}
}
@Override
public SearchEngineResponse<MediaItem> findVideos(String query, List<String> filters, List<String> facets, String orderBy, int size) {
return collectMediaItemsByQuery(query, "video", filters, facets, orderBy, size);
}
@Override
public SearchEngineResponse<MediaItem> findVideos(Dysco dysco, List<String> filters, List<String> facets, String orderBy, int size) {
if (dysco.getDyscoType().equals(DyscoType.TRENDING)) {
postProcess(dysco);
List<eu.socialsensor.framework.common.domain.Query> queries = dysco.getSolrQueries();
return collectMediaItemsByQueries(queries, "video", filters, facets, orderBy, size);
} else {
CustomDysco customDysco = (CustomDysco) dysco;
List<eu.socialsensor.framework.common.domain.Query> queries = customDysco.getSolrQueries();
List<String> twitterMentions = customDysco.getMentionedUsers();
List<String> twitterUsers = customDysco.getTwitterUsers();
List<String> wordsToExclude = customDysco.getWordsToAvoid();
List<String> otherSocialNetworks = customDysco.getOtherSocialNetworks();
if(otherSocialNetworks != null && !otherSocialNetworks.isEmpty()) {
if(twitterUsers == null)
twitterUsers = new ArrayList<String>();
for(String url : otherSocialNetworks) {
try {
Map<String, String> parts = Util.findNetworkSource(url);
for(String username : parts.keySet()) {
twitterUsers.add(username);
}
} catch (Exception e) {
}
}
}
return collectMediaItems(queries, twitterMentions, twitterUsers, wordsToExclude, "video", filters, facets, orderBy, size);
}
}
@Override
public SearchEngineResponse<MediaItem> findImages(String query, List<String> filters, List<String> facets, String orderBy, int size) {
return collectMediaItemsByQuery(query, "image", filters, facets, orderBy, size);
}
@Override
public SearchEngineResponse<MediaItem> findImages(Dysco dysco, List<String> filters, List<String> facets, String orderBy, int size) {
SearchEngineResponse<MediaItem> mediaItems;
if (dysco.getDyscoType().equals(DyscoType.TRENDING)) {
postProcess(dysco);
List<eu.socialsensor.framework.common.domain.Query> queries = dysco.getSolrQueries();
mediaItems = collectMediaItemsByQueries(queries, "image", filters, facets, orderBy, size);
} else {
CustomDysco customDysco = (CustomDysco) dysco;
List<eu.socialsensor.framework.common.domain.Query> queries = customDysco.getSolrQueries();
List<String> twitterMentions = customDysco.getMentionedUsers();
List<String> twitterUsers = customDysco.getTwitterUsers();
List<String> wordsToExclude = customDysco.getWordsToAvoid();
List<String> otherSocialNetworks = customDysco.getOtherSocialNetworks();
if(otherSocialNetworks != null && !otherSocialNetworks.isEmpty()) {
if(twitterUsers == null)
twitterUsers = new ArrayList<String>();
for(String url : otherSocialNetworks) {
try {
Map<String, String> parts = Util.findNetworkSource(url);
for(String username : parts.keySet()) {
twitterUsers.add(username);
}
} catch (Exception e) {
}
}
}
mediaItems = collectMediaItems(queries, twitterMentions, twitterUsers, wordsToExclude, "image", filters, facets, orderBy, size);
}
return mediaItems;
}
@Override
public List<WebPage> findHealines(Dysco dysco, int size) {
Logger.getRootLogger().info("============ Web Pages Retrieval =============");
List<WebPage> webPages = new ArrayList<WebPage>();
postProcess(dysco);
List<eu.socialsensor.framework.common.domain.Query> queries = dysco.getSolrQueries();
if (queries == null || queries.isEmpty()) {
return webPages;
}
// Retrieve web pages from solr index
Set<String> uniqueUrls = new HashSet<String>();
Set<String> expandedUrls = new HashSet<String>();
Set<String> titles = new HashSet<String>();
String allQueriesToOne = buildKeywordSolrQuery(queries, "AND");
String sinceDateStr = "*";
try {
Date sinceDate = new Date(System.currentTimeMillis() - 24 * 3600 * 1000);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sinceDateStr = df.format(sinceDate);
}
catch(Exception e) {
Logger.getRootLogger().error(e);
}
String queryForRequest = "((title : (" + allQueriesToOne + ")) OR (text:(" + allQueriesToOne + ")) AND (date : [" + sinceDateStr + " TO * ]) )";
SolrQuery solrQuery = new SolrQuery(queryForRequest);
solrQuery.setRows(size);
solrQuery.addSortField("score", ORDER.desc);
solrQuery.addSortField("date", ORDER.desc);
Logger.getRootLogger().info("Query : " + queryForRequest);
SearchEngineResponse<WebPage> response = solrWebPageHandler.findItems(solrQuery);
if (response != null) {
List<WebPage> results = response.getResults();
for (WebPage webPage : results) {
String url = webPage.getUrl();
String expandedUrl = webPage.getExpandedUrl();
String title = webPage.getTitle();
if (!expandedUrls.contains(expandedUrl) && !uniqueUrls.contains(url)
&& !titles.contains(title)) {
int shares = webPageDAO.getWebPageShares(url);
webPage.setShares(shares);
webPages.add(webPage);
uniqueUrls.add(url);
expandedUrls.add(expandedUrl);
titles.add(title);
}
}
}
Logger.getRootLogger().info(webPages.size() + " web pages retrieved. Re-rank by popularity (#shares)");
Collections.sort(webPages, new Comparator<WebPage>() {
public int compare(WebPage wp1, WebPage wp2) {
if (wp1.getShares() == wp2.getShares()) {
if (wp1.getDate().before(wp2.getDate())) {
return 1;
} else {
return -1;
}
} else {
return wp1.getShares() < wp2.getShares() ? 1 : -1;
}
}
});
return webPages.subList(0, Math.min(webPages.size(), size));
}
@Override
public List<WebPage> findHealines(String query, int size) {
Logger.getRootLogger().info("============ Web Pages Retrieval =============");
List<WebPage> webPages = new ArrayList<WebPage>();
// Retrieve web pages from solr index
Set<String> uniqueUrls = new HashSet<String>();
Set<String> expandedUrls = new HashSet<String>();
Set<String> titles = new HashSet<String>();
String sinceDateStr = "*";
try {
Date sinceDate = new Date(System.currentTimeMillis() - 24 * 3600 * 1000);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sinceDateStr = df.format(sinceDate);
}
catch(Exception e) {
Logger.getRootLogger().error(e);
}
String queryForRequest = "((title : (" + query + ")) OR (text:(" + query + ")) AND (date : [" + sinceDateStr + " TO * ]) )";
SolrQuery solrQuery = new SolrQuery(queryForRequest);
solrQuery.setRows(size);
solrQuery.addSortField("score", ORDER.desc);
solrQuery.addSortField("date", ORDER.desc);
Logger.getRootLogger().info("Query : " + query);
Logger.getRootLogger().info("Solr Query : " + solrQuery);
SearchEngineResponse<WebPage> response = solrWebPageHandler.findItems(solrQuery);
if (response != null) {
List<WebPage> results = response.getResults();
for (WebPage webPage : results) {
String url = webPage.getUrl();
String expandedUrl = webPage.getExpandedUrl();
String title = webPage.getTitle();
if (!expandedUrls.contains(expandedUrl) && !uniqueUrls.contains(url)
&& !titles.contains(title)) {
int shares = webPageDAO.getWebPageShares(url);
webPage.setShares(shares);
webPages.add(webPage);
uniqueUrls.add(url);
expandedUrls.add(expandedUrl);
titles.add(title);
}
}
}
Logger.getRootLogger().info(webPages.size() + " web pages retrieved. Re-rank by popularity (#shares)");
Collections.sort(webPages, new Comparator<WebPage>() {
public int compare(WebPage wp1, WebPage wp2) {
if (wp1.getShares() == wp2.getShares()) {
if (wp1.getDate().before(wp2.getDate())) {
return 1;
} else {
return -1;
}
} else {
return wp1.getShares() < wp2.getShares() ? 1 : -1;
}
}
});
return webPages.subList(0, Math.min(webPages.size(), size));
}
@Override
public List<MediaItem> getMediaItemHistory(String mediaItemId) {
return getMediaItemHistory(mediaItemId, 10);
}
@Override
public List<MediaItem> getMediaItemHistory(String mediaItemId, int size) {
List<MediaItem> mediaItems = new ArrayList<MediaItem>();
Logger.getRootLogger().info("Get visually similar media items for " + mediaItemId);
int page = 1;
Set<String> ids = new HashSet<String>();
while (true) {
JsonResultSet similar = visualIndexHandler.getSimilarImages(mediaItemId, page++, 100);
if (similar != null && similar.getResults() != null && similar.getResults().size() > 0) {
List<JsonResult> results = similar.getResults();
for (JsonResult result : results) {
String mId = result.getId();
if (!ids.contains(mId)) {
MediaItem mediaItem = mediaItemDAO.getMediaItem(mId);
if (mediaItem != null) {
mediaItems.add(mediaItem);
}
}
}
} else {
break;
}
}
Logger.getRootLogger().info(mediaItems.size() + "media items retrieved. Re-rank by publication time");
Collections.sort(mediaItems, new Comparator<MediaItem>() {
public int compare(MediaItem mi1, MediaItem mi2) {
if (mi1.getPublicationTime() < mi2.getPublicationTime()) {
return -1;
} else {
return 1;
}
}
});
return mediaItems.subList(0, Math.min(size, mediaItems.size()));
}
private SearchEngineResponse<Item> collectItemsByQuery(String query, List<String> filters, List<String> facets, String orderBy, Map<String, String> params, int size) {
List<Item> items = new ArrayList<Item>();
SearchEngineResponse<Item> response = new SearchEngineResponse<Item>();
if (query == null || query.isEmpty() || query.equals("")) {
return response;
}
query = query.replaceAll("[\"()]", " ");
query = query.trim();
// Join query parts with AND
String[] queryParts = query.split("\\s+");
query = StringUtils.join(queryParts, " AND ");
//Retrieve multimedia content that is stored in solr
if (!query.contains("title") && !query.contains("description")) {
query = "((title : " + query + ") OR (description:" + query + "))";
}
//Set source filters in case they exist exist
for (String filter : filters) {
query += " AND " + filter;
}
SolrQuery solrQuery = new SolrQuery(query);
solrQuery.setRows(size);
for (Map.Entry<String, String> param : params.entrySet()) {
solrQuery.add(param.getKey(), param.getValue());
}
//Set facets if necessary
for (String facet : facets) {
solrQuery.addFacetField(facet);
solrQuery.setFacetLimit(6);
}
if (orderBy != null) {
solrQuery.setSortField(orderBy, ORDER.desc);
} else {
solrQuery.setSortField("score", ORDER.desc);
}
Logger.getRootLogger().info("Solr Query : " + query);
response = solrItemHandler.findItems(solrQuery);
if (response != null) {
List<Item> results = response.getResults();
for (Item it : results) {
items.add(it);
if ((items.size() >= size)) {
break;
}
}
}
response.setResults(items);
return response;
}
private SearchEngineResponse<Item> collectItemsByQueries(List<eu.socialsensor.framework.common.domain.Query> queries, List<String> filters, List<String> facets, String orderBy, Map<String, String> params, int size) {
List<Item> items = new ArrayList<Item>();
SearchEngineResponse<Item> response = new SearchEngineResponse<Item>();
if (queries.isEmpty()) {
return response;
}
//Retrieve multimedia content that is stored in solr
String allQueriesToOne = buildKeywordSolrQuery(queries, "OR");
String queryForRequest = "(title : (" + allQueriesToOne + ") OR description:(" + allQueriesToOne + "))";
//Set source filters in case they exist exist
for (String filter : filters) {
queryForRequest += " AND " + filter;
}
SolrQuery solrQuery = new SolrQuery(queryForRequest);
solrQuery.setRows(size);
for (Map.Entry<String, String> param : params.entrySet()) {
solrQuery.add(param.getKey(), param.getValue());
}
//Set facets if necessary
for (String facet : facets) {
solrQuery.addFacetField(facet);
solrQuery.setFacetLimit(6);
}
solrQuery.addSortField("score", ORDER.desc);
if (orderBy != null) {
solrQuery.addSortField(orderBy, ORDER.desc);
}
Logger.getRootLogger().info("Solr Query: " + queryForRequest);
response = solrItemHandler.findItems(solrQuery);
if (response != null) {
List<Item> results = response.getResults();
for (Item it : results) {
items.add(it);
if (items.size() >= size) {
break;
}
}
}
response.setResults(items);
return response;
}
private SearchEngineResponse<Item> collectItems(List<eu.socialsensor.framework.common.domain.Query> queries, List<String> mentions,
List<String> users, List<String> wordsToExclude, List<String> filters, List<String> facets, String orderBy, Map<String, String> params, int size) {
List<Item> items = new ArrayList<Item>();
SearchEngineResponse<Item> response = new SearchEngineResponse<Item>();
if (queries == null && mentions == null && users == null) {
return response;
}
String query = "";
// Create a Solr Query
String textQuery = buildKeywordSolrQuery(queries, "OR");
//set Twitter mentions
if (mentions != null && !mentions.isEmpty()) {
String mentionsQuery = StringUtils.join(mentions, " OR ");
if (textQuery.isEmpty()) {
textQuery = mentionsQuery;
} else {
textQuery += " OR " + mentionsQuery;
}
}
if (textQuery != null && !textQuery.isEmpty()) {
query += "(title : (" + textQuery + ") OR description:(" + textQuery + "))";
}
//set Twitter users
if (users != null && !users.isEmpty()) {
String usersQuery = StringUtils.join(users, " OR ");
if (query.isEmpty()) {
query = "author : (" + usersQuery + ")";
} else {
query += " OR (author : (" + usersQuery + "))";
}
}
if (query.isEmpty()) {
return response;
}
//add words to exclude in query
if (wordsToExclude != null && !wordsToExclude.isEmpty()) {
String exclude = StringUtils.join(wordsToExclude, " OR ");
query += " NOT (title : (" + exclude + ") OR description:(" + exclude + "))";
}
//Set source filters in case they exist exist
if(filters!=null && !filters.isEmpty()) {
String filtersQuery = StringUtils.join(filters, " AND ");
if (query.isEmpty()) {
query = filtersQuery;
} else {
query = "(" + query + ") AND " + filtersQuery;
}
}
SolrQuery solrQuery = new SolrQuery(query);
solrQuery.setRows(size);
for (Map.Entry<String, String> param : params.entrySet()) {
solrQuery.add(param.getKey(), param.getValue());
}
//Set facets if necessary
for (String facet : facets) {
solrQuery.addFacetField(facet);
solrQuery.setFacetLimit(6);
}
if (orderBy != null) {
solrQuery.setSortField(orderBy, ORDER.desc);
} else {
solrQuery.setSortField("score", ORDER.desc);
}
Logger.getRootLogger().info("Solr Query: " + query);
response = solrItemHandler.findItems(solrQuery);
if (response != null) {
List<Item> results = response.getResults();
for (Item it : results) {
items.add(it);
if (items.size() >= size) {
break;
}
}
}
response.setResults(items);
return response;
}
private SearchEngineResponse<MediaItem> collectMediaItemsByQuery(String query, String type, List<String> filters, List<String> facets, String orderBy, int size) {
List<MediaItem> mediaItems = new LinkedList<MediaItem>();
SearchEngineResponse<MediaItem> response = new SearchEngineResponse<MediaItem>();
if (query.equals("")) {
return response;
}
// TEST CODE FOR MEDIA RETRIEVAL
query = query.replaceAll("[\"()]", " ");
query = query.trim();
// Join query parts with AND
String[] queryParts = query.split("\\s+");
query = StringUtils.join(queryParts, " AND ");
//Retrieve multimedia content that is stored in solr
if (!query.contains("title") && !query.contains("description")) {
query = "((title : " + query + ") OR (description:" + query + "))";
}
//Set filters in case they exist exist
for (String filter : filters) {
query += " AND " + filter;
}
query += " AND (type : " + type + ")";
SolrQuery solrQuery = new SolrQuery(query);
solrQuery.setRows(size);
for (String facet : facets) {
solrQuery.addFacetField(facet);
solrQuery.setFacetLimit(6);
}
Logger.getRootLogger().info("orderBy: " + orderBy);
if (orderBy != null) {
solrQuery.setSortField(orderBy, ORDER.desc);
} else {
solrQuery.setSortField("score", ORDER.desc);
}
Logger.getRootLogger().info("Solr Query : " + query);
response = solrMediaItemHandler.findItems(solrQuery);
if (response != null) {
List<MediaItem> results = response.getResults();
Set<String> urls = new HashSet<String>();
for (MediaItem mi : results) {
System.out.println("Fetched media item: " + mi.getId() + " : " + mi.getSolrScore());
if (!urls.contains(mi.getUrl())) {
mediaItems.add(mi);
urls.add(mi.getUrl());
}
if ((mediaItems.size() >= size)) {
break;
}
}
}
response.setResults(mediaItems);
return response;
}
private SearchEngineResponse<MediaItem> collectMediaItemsByQueries(List<eu.socialsensor.framework.common.domain.Query> queries,
String type, List<String> filters, List<String> facets, String orderBy, int size) {
List<MediaItem> mediaItems = new ArrayList<MediaItem>();
SearchEngineResponse<MediaItem> response = new SearchEngineResponse<MediaItem>();
if (queries.isEmpty()) {
return response;
}
//Retrieve multimedia content that is stored in solr
String allQueriesToOne = buildKeywordSolrQuery(queries, "AND");
String queryForRequest = "(title : (" + allQueriesToOne + ") OR description:(" + allQueriesToOne + "))";
//Set filters in case they exist exist
for (String filter : filters) {
queryForRequest += " AND " + filter;
}
queryForRequest += " AND (type : " + type + ")";
SolrQuery solrQuery = new SolrQuery(queryForRequest);
Logger.getRootLogger().info("Solr Query: " + queryForRequest);
solrQuery.setRows(size);
solrQuery.addSortField("score", ORDER.desc);
if (orderBy != null) {
solrQuery.addSortField(orderBy, ORDER.desc);
}
for (String facet : facets) {
solrQuery.addFacetField(facet);
solrQuery.setFacetLimit(6);
}
response = solrMediaItemHandler.findItems(solrQuery);
if (response != null) {
List<MediaItem> results = response.getResults();
Set<String> urls = new HashSet<String>();
for (MediaItem mi : results) {
if (!urls.contains(mi.getUrl())) {
mediaItems.add(mi);
urls.add(mi.getUrl());
}
if ((mediaItems.size() >= size)) {
break;
}
}
}
response.setResults(mediaItems);
return response;
}
private SearchEngineResponse<MediaItem> collectMediaItems(List<eu.socialsensor.framework.common.domain.Query> queries, List<String> mentions,
List<String> users, List<String> wordsToExclude, String type, List<String> filters, List<String> facets, String orderBy, int size) {
List<MediaItem> mediaItems = new ArrayList<MediaItem>();
SearchEngineResponse<MediaItem> response = new SearchEngineResponse<MediaItem>();
if (queries == null && mentions == null && users == null) {
return response;
}
String query = "";
//Retrieve multimedia content that is stored in solr
String textQuery = buildKeywordSolrQuery(queries, "AND");
//set mentions
if (mentions != null && !mentions.isEmpty()) {
String mentionsQuery = StringUtils.join(mentions, " OR ");
if (textQuery.isEmpty()) {
textQuery = mentionsQuery;
} else {
textQuery += " OR " + mentionsQuery;
}
}
if (textQuery != null && !textQuery.isEmpty()) {
query += "(title : (" + textQuery + ") OR description:(" + textQuery + "))";
}
//set Twitter users
if (users != null && !users.isEmpty()) {
String usersQuery = StringUtils.join(users, " OR ");
if (query.isEmpty()) {
query = " author: (" + usersQuery + ")";
} else {
query += " OR (author: (" + usersQuery + "))";
}
}
if (query.isEmpty()) {
return response;
}
//add words to exclude in query
if (wordsToExclude != null && !wordsToExclude.isEmpty()) {
String exclude = StringUtils.join(wordsToExclude, " OR ");
query += " NOT (title : (" + exclude + ") OR description:(" + exclude + "))";
}
//Set source filters in case they exist exist
if(filters!=null && !filters.isEmpty()) {
String filtersQuery = StringUtils.join(filters, " AND ");
if (query.isEmpty()) {
query = filtersQuery;
} else {
query = "(" + query + ") AND " + filtersQuery;
}
}
query += " AND type : " + type;
SolrQuery solrQuery = new SolrQuery(query);
Logger.getRootLogger().info("Solr Query: " + query);
solrQuery.setRows(size);
for (String facet : facets) {
solrQuery.addFacetField(facet);
solrQuery.setFacetLimit(6);
}
//solrQuery.addFilterQuery("publicationTime:["+86400000+" TO *]");
if (orderBy != null) {
solrQuery.setSortField(orderBy, ORDER.desc);
} else {
solrQuery.setSortField("score", ORDER.desc);
}
response = solrMediaItemHandler.findItems(solrQuery);
if (response != null) {
List<MediaItem> results = response.getResults();
Set<String> urls = new HashSet<String>();
for (MediaItem mi : results) {
if (!urls.contains(mi.getUrl())) {
mediaItems.add(mi);
urls.add(mi.getUrl());
}
if ((mediaItems.size() >= size)) {
break;
}
}
}
response.setResults(mediaItems);
return response;
}
private String buildKeywordSolrQuery(List<eu.socialsensor.framework.common.domain.Query> queries, String liaison) {
Map<String, List<String>> linkedWords = new HashMap<String, List<String>>();
List<eu.socialsensor.framework.common.domain.Query> swingQueries = new ArrayList<eu.socialsensor.framework.common.domain.Query>();
String solrQuery = null;
for (eu.socialsensor.framework.common.domain.Query query : queries) {
//store these queries for later
if (query.getName().startsWith("\"") && (query.getName().endsWith("\"") || query.getName().endsWith("\" "))) {
//System.out.println("entity query : "+query.getName());
if (query.getName().endsWith("\" ")) {
query.setName(query.getName().substring(0, query.getName().length() - 1));
}
// Handle combined entities
String[] queryParts = query.getName().split("\"\\s\"");
if(queryParts != null) {
String name = StringUtils.join(queryParts, "\" AND \"");
swingQueries.add(new eu.socialsensor.framework.common.domain.Query(name, query.getScore()));
}
}
else {
List<String> entities = new ArrayList<String>();
String restQuery = query.getName();
int start = 0, end = 0;
//System.out.println("query : "+query.getName());
while (start != -1 && end != -1) {
start = restQuery.indexOf("\"");
//System.out.println("start:"+start);
if (start == -1) {
break;
}
String temp = restQuery.substring(start + 1);
//System.out.println("temp:"+temp);
end = temp.indexOf("\"") + start + 1;
//System.out.println("end:"+(end));
if (end == -1) {
break;
}
end += 1;
String entity = restQuery.substring(start, end);
//System.out.println("entity:"+entity);
restQuery = restQuery.replace(entity, "").trim();
entities.add(entity);
}
restQuery = restQuery.replaceAll(" +", " ");
restQuery = restQuery.replace("[^A-Za-z0-9 ]", "");
//System.out.println("rest query: "+restQuery);
for (String entity : entities) {
String queryToLink = restQuery;
if (!linkedWords.containsKey(entity)) {
List<String> alreadyIn = new ArrayList<String>();
if (query.getScore() != null) {
queryToLink += "^" + query.getScore();
}
alreadyIn.add(queryToLink);
linkedWords.put(entity, alreadyIn);
} else {
List<String> alreadyIn = linkedWords.get(entity);
if (query.getScore() != null) {
queryToLink += "^" + query.getScore();
}
if (!alreadyIn.contains(queryToLink)) {
alreadyIn.add(queryToLink);
linkedWords.put(entity, alreadyIn);
}
}
}
if (entities.isEmpty()) {
if (solrQuery == null) {
if (query.getScore() != null) {
solrQuery = "(" + restQuery + ")^" + query.getScore();
} else {
solrQuery = "(" + restQuery + ")";
}
} else {
if (!solrQuery.contains(restQuery)) {
if (query.getScore() != null) {
solrQuery += " " + liaison + " (" + restQuery + ")^" + query.getScore();
} else {
solrQuery += " " + liaison + " (" + restQuery + ")";
}
}
}
}
}
}
for (Map.Entry<String, List<String>> entry : linkedWords.entrySet()) {
if (!entry.getValue().isEmpty()) {
String resQuery = entry.getKey() + " AND (";
boolean first = true;
for (String lWord : entry.getValue()) {
if (first) {
resQuery += lWord;
first = false;
} else {
resQuery += " OR " + lWord;
}
}
resQuery += ")";
if (solrQuery == null) {
solrQuery = "(" + resQuery + ")";
} else {
if (!solrQuery.contains(resQuery)) {
solrQuery += " " + liaison + " (" + resQuery + ")";
}
}
}
}
for (eu.socialsensor.framework.common.domain.Query sQuery : swingQueries) {
if (solrQuery == null) {
if (sQuery.getScore() != null) {
solrQuery = "(" + sQuery.getName() + ")^" + sQuery.getScore();
} else {
solrQuery = "(" + sQuery.getName() + ")";
}
} else {
if (!solrQuery.contains(sQuery.getName())) {
if (sQuery.getScore() != null) {
solrQuery += " " + liaison + " (" + sQuery.getName() + ")^" + sQuery.getScore();
} else {
solrQuery += " " + liaison + " (" + sQuery.getName() + ")";
}
}
}
}
if (solrQuery == null) {
solrQuery = "";
}
return solrQuery;
}
public List<MediaItem> requestThumbnails(Dysco dysco, int size) {
return null;
}
private void postProcess(Dysco dysco) {
List<eu.socialsensor.framework.common.domain.Query> queries = dysco.getSolrQueries();
List<Entity> entities = dysco.getEntities();
if(entities != null && entities.size()>1) {
String qStr = "";
for(Entity e : entities) {
qStr += "\"" + e.getName() + "\" ";
}
eu.socialsensor.framework.common.domain.Query q = new eu.socialsensor.framework.common.domain.Query();
q.setName(qStr);
q.setScore(dysco.getScore());
queries.add(q);
}
// Remove Single Hashtags / Entities
Map<String, Double> hashtags = dysco.getHashtags();
List<eu.socialsensor.framework.common.domain.Query> tbRemoved = new ArrayList<eu.socialsensor.framework.common.domain.Query>();
for(eu.socialsensor.framework.common.domain.Query query : queries) {
for(String hashtag : hashtags.keySet()) {
String name = query.getName();
if(name.equalsIgnoreCase(hashtag.replace("
tbRemoved.add(query);
break;
}
}
if(tbRemoved.contains(query))
continue;
for(Entity entity : entities) {
if(entity.getType().equals(Type.LOCATION)) {
tbRemoved.add(query);
break;
}
}
}
for(eu.socialsensor.framework.common.domain.Query query : tbRemoved) {
queries.remove(query);
}
}
public static void main(String[] args) throws Exception {
DyscoDAOImpl dao = new DyscoDAOImpl("Socialsensordb.atc.gr",
"WebPagesDB", "WebPages", "MediaItemsDB", "MediaItems",
"http://socialsensor.atc.gr/solr/dyscos",
"http://socialsensor.atc.gr/solr/items",
"http://socialsensor.atc.gr/solr/MediaItems",
"http://socialsensor.atc.gr/solr/WebPages",
"http://160.40.51.18:8080/VisualIndexService",
"Prototype");
Dysco dysco = dao.findDysco("0038eafd-4998-498a-90a2-07ea69682dcc");
System.out.println(dysco.toJSONString());
List<String> filters = new ArrayList<String>();
List<String> facets = new ArrayList<String>();
String orderBy = "publicationTime";
Map<String, String> params = new HashMap<String, String>();
long now = System.currentTimeMillis();
long window = 24 * 60L * 60L * 1000L;
filters.add("publicationTime:[" + (now - window) + " TO " + now + "]");
SearchEngineResponse<Item> items = dao.findItems(dysco, filters, facets, orderBy, params, 10);
System.out.println(items.getNumFound());
for(Item item : items.getResults()) {
System.out.println("=======================================");
System.out.println(item.getTitle().replaceAll("\n", " "));
System.out.println(item.getDescription());
System.out.println(item.getText());
System.out.println(StringUtils.join(item.getTags(), " "));
System.out.println(item.getStreamId());
System.out.println(item.getShares());
}
}
}
|
package org.csstudio.display.builder.editor.rcp;
import static org.csstudio.display.builder.rcp.Plugin.logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import org.csstudio.display.builder.editor.DisplayEditor;
import org.csstudio.display.builder.editor.Preferences;
import org.csstudio.display.builder.editor.WidgetSelectionHandler;
import org.csstudio.display.builder.editor.undo.AddWidgetAction;
import org.csstudio.display.builder.editor.undo.RemoveWidgetsAction;
import org.csstudio.display.builder.model.ChildrenProperty;
import org.csstudio.display.builder.model.RuntimeWidgetProperty;
import org.csstudio.display.builder.model.Widget;
import org.csstudio.display.builder.model.WidgetCategory;
import org.csstudio.display.builder.model.WidgetDescriptor;
import org.csstudio.display.builder.model.WidgetFactory;
import org.csstudio.display.builder.model.WidgetProperty;
import org.csstudio.display.builder.model.widgets.ArrayWidget;
import org.csstudio.display.builder.util.undo.CompoundUndoableAction;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
/** Helper for creating the SWT/RCP context menu to morph widgets (replace
* widgets with a particular type of widget) in editor.
*
* Intended as a sub-menu in editor's main context menu.
*
* @author Amanda Carpenter
*/
@SuppressWarnings("nls")
public class MorphWidgetMenuSupport
{
private final DisplayEditor editor;
private class MorphAction extends Action
{
final WidgetDescriptor descriptor;
MorphAction(final WidgetDescriptor descr)
{
descriptor = descr;
setText(descriptor.getName());
try
{
setImageDescriptor(ImageDescriptor.createFromImageData(new ImageData(descriptor.getIconStream())));
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Cannot create menu icon for widget type " + descr.getType(), ex);
}
}
@Override
public void run()
{
final WidgetSelectionHandler selection = editor.getWidgetSelectionHandler();
// Copy selected widgets.
// List may be modified during iteration for widgets inside an ArrayWidget
final List<Widget> widgets = new ArrayList<>(selection.getSelection());
final List<Widget> replacements = new ArrayList<>();
final CompoundUndoableAction steps = new CompoundUndoableAction("Morph to " + descriptor.getName());
// Iterate in a way that allows modification of 'widgets' inside the loop
for (int i=0; i<widgets.size(); )
{
final Widget widget = widgets.get(i);
// Already of correct type?
if (widget.getType().equals(descriptor.getType()))
{
++i;
continue;
}
final ChildrenProperty target = ChildrenProperty.getParentsChildren(widget);
// All array elements of an ArrayWidget must have the same type
// to avoid errors with matching element properties.
if (target.getWidget() instanceof ArrayWidget)
{
// Replace _all_ children of ArrayWidget, not just the selected ones
final List<Widget> children = new ArrayList<>(target.getValue());
steps.execute(new RemoveWidgetsAction(selection, children));
for (Widget child : children)
{
final Widget replacement = createNewWidget(child);
steps.execute(new AddWidgetAction(selection, target, replacement));
replacements.add(replacement);
}
// Remove _all_ potentially selected array elements
// from the widgets to be replaced
widgets.removeAll(children);
// No need for ++i since `widgets` has been updated
}
else
{
final Widget replacement = createNewWidget(widget);
steps.execute(new RemoveWidgetsAction(selection, Arrays.asList(widget)));
steps.execute(new AddWidgetAction(selection, target, replacement));
replacements.add(replacement);
++i;
}
}
// Add to undo (steps have already been executed)
editor.getUndoableActionManager().add(steps);
// Change selection from removed widgets to replacements
selection.setSelection(replacements);
}
private Widget createNewWidget(final Widget widget)
{
final Widget new_widget = descriptor.createWidget();
final Set<WidgetProperty<?>> props = widget.getProperties();
for (WidgetProperty<?> prop : props)
{
final Optional<WidgetProperty<Object>> check = new_widget.checkProperty(prop.getName());
if (! check.isPresent())
continue;
final WidgetProperty<Object> new_prop = check.get();
if (new_prop.isReadonly())
continue;
if (new_prop instanceof RuntimeWidgetProperty)
continue;
try
{
new_prop.setValueFromObject(prop.getValue());
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Cannot morph " + prop, ex);
}
}
return new_widget;
}
}
final MenuManager mm;
//not intended for use, but for testing/debugging
public MorphWidgetMenuSupport(final DisplayEditor editor, final Composite parent)
{
this.editor = editor;
mm = createMenuManager();
final Menu menu = createMenu(mm, parent);
parent.setMenu(menu);
}
public MorphWidgetMenuSupport(final DisplayEditor editor)
{
this.editor = editor;
mm = createMenuManager();
}
public MenuManager getMenuManager()
{
return mm;
}
private MenuManager createMenuManager()
{
final MenuManager mm = new MenuManager(Messages.ReplaceWith);
mm.setRemoveAllWhenShown(true);
mm.addMenuListener((manager)->
{
if (editor.getWidgetSelectionHandler().getSelection().isEmpty())
manager.add(new Action(Messages.ReplaceWith_NoWidgets) {});
else
{ // Create menu that lists all widget types
WidgetCategory category = null;
for (WidgetDescriptor descr : WidgetFactory.getInstance().getWidgetDescriptions())
{
if (Preferences.getHiddenWidgets().contains(descr.getType()))
continue;
// Header for start of each category
if (descr.getCategory() != category)
{
category = descr.getCategory();
// Use disabled, empty action to show category name
final Action info = new Action(category.getDescription()) {};
info.setEnabled(false);
manager.add(new Separator());
manager.add(info);
}
manager.add(new MorphAction(descr));
}
}
});
mm.setImageDescriptor(Plugin.getIcon("replace.png"));
return mm;
}
private Menu createMenu(final MenuManager mm, final Composite parent)
{
final Menu menu = mm.createContextMenu(parent);
menu.setVisible(true);
return menu;
}
}
|
package com.acrussell.learnalanguage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.prefs.Preferences;
import javax.swing.JButton;
import javax.swing.SwingWorker;
public class Runner extends SwingWorker<String, String> {
private Preferences prefs = Preferences.userNodeForPackage(this.getClass());
private Console output, status;
private JButton runButton, stopButton;
private File mainClass;
private List<String> parameters;
private StreamPiper piper;
/**
* Creates an object to handle running an executable Java process.
*
* @param terminal
* @param status
*/
public Runner(File mainClass, List<String> parameters, JButton runButton,
JButton stopButton, Console output, Console status) {
this.output = output;
this.status = status;
this.runButton = runButton;
this.stopButton = stopButton;
this.mainClass = mainClass;
this.parameters = parameters;
}
@Override
public String doInBackground() {
runButton.setEnabled(false);
stopButton.setEnabled(true);
List<String> processParams = new ArrayList<String>();
// Execute with Java
processParams.add("java");
// Add directory of main file to classpath
processParams.add("-cp");
processParams.add(mainClass.getParent());
// Extract the name of the class from the file
String mainClassName = mainClass.getName().split("\\.")[0];
processParams.add(mainClassName);
// Add the program's runtime parameters
processParams.addAll(parameters);
ProcessBuilder pb = new ProcessBuilder(processParams);
status.appendLine(String.format("Running %s.java...", mainClassName));
// Execute process
Process p;
try {
p = pb.start();
} catch (IOException ioe) {
return "Error: Could not access the program.";
}
// Clear the terminal at each execution if the user desires
if (prefs.getBoolean("terminal_should_clear", false)) {
output.setText("");
}
// Send process output to console
piper = new StreamPiper(p.getInputStream(), output.getStream());
piper.start();
// Thread that notifies GUI that the process has completed
int statusCode = -1;
try {
statusCode = p.waitFor();
String statusMessage = String.format("Machine returned %d (%s).",
statusCode, statusCode == 0 ? "success" : "error");
publish(statusMessage);
} catch (InterruptedException e) {
publish("Interrupting machine...");
p.destroy();
piper.interrupt();
publish("Machine interrupted.");
}
return "Execution complete.";
}
protected void process(List<String> messages) {
for (String message : messages) {
status.appendLine(message);
}
}
@Override
protected void done() {
if (!this.isCancelled()) {
try {
status.appendLine(get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
runButton.setEnabled(true);
stopButton.setEnabled(false);
}
class StreamPiper extends Thread {
private static final int BUFFER_SIZE = 2048;
private static final int FLUSH_DELAY = 1;
private BufferedReader reader;
private BufferedWriter writer;
private boolean isInterrupted = false;
private char[] buffer = new char[BUFFER_SIZE];
public StreamPiper(InputStream is, OutputStream os) {
reader = new BufferedReader(new InputStreamReader(is));
writer = new BufferedWriter(new OutputStreamWriter(os));
}
public void interrupt() {
isInterrupted = true;
}
@Override
public void run() {
try {
long currentTime = System.currentTimeMillis();
while (!isInterrupted) {
int charsRead = reader.read(buffer);
// Break if there is nothing to read
if (charsRead == -1) {
break;
}
// Write the number of chars read to the output stream
writer.append(new String(buffer, 0, charsRead));
// Flush stream if sufficient time has passed.
// There may be a better solution to this!
if (System.currentTimeMillis() - currentTime > FLUSH_DELAY) {
writer.flush();
currentTime = System.currentTimeMillis();
}
}
// Flush output when process is interrupted
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
package cc.rainwave.android;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;
import cc.rainwave.android.adapters.SongListAdapter;
import cc.rainwave.android.adapters.StationListAdapter;
import cc.rainwave.android.api.Session;
import cc.rainwave.android.api.types.Album;
import cc.rainwave.android.api.types.RainwaveException;
import cc.rainwave.android.api.types.Song;
import cc.rainwave.android.api.types.SongRating;
import cc.rainwave.android.api.types.Station;
import cc.rainwave.android.views.HorizontalRatingBar;
import cc.rainwave.android.views.PagerWidget;
import com.android.music.TouchInterceptor;
import com.google.android.apps.iosched.ui.widget.Workspace;
import com.google.android.apps.iosched.ui.widget.Workspace.OnScreenChangeListener;
/**
* This is the primary activity for this application. It announces
* which song is playing, handles ratings, and also elections.
*/
public class NowPlayingActivity extends Activity {
/** Debug tag */
private static final String TAG = "NowPlaying";
/** This manages our connection with the Rainwave server */
private Session mSession;
private RainwavePreferences mPreferences;
/** Reference to song countdown timer. */
private CountDownTimer mCountdown;
/** True if device supports Window.FEATURE_INDETERMINATE_PROGRESS. */
private boolean mHasIndeterminateProgress;
@Override
public void onCreate(Bundle savedInstanceState) {
mHasIndeterminateProgress = requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
initializeSession();
setContentView(R.layout.activity_main);
setListeners();
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onResume() {
// Assuming a cold start every time, so need to register the schedule
// update receiver and update the schedule if needed.
super.onResume();
initializeSession();
// Construct intent filter
IntentFilter filter = new IntentFilter();
filter.addAction(SyncService.BROADCAST_EVENT_UPDATE);
filter.addAction(SyncService.BROADCAST_EVENT_UPDATE_FAILED);
filter.addAction(SyncService.BROADCAST_REAUTHENTICATE);
registerReceiver(mEventUpdateReceiver, filter);
fetchSchedules();
}
public void onPause() {
// Should not continue any long-running background tasks when not in
// the foreground.
super.onPause();
if(mCountdown != null) {
mCountdown.cancel();
}
stopSyncService();
unregisterReceiver(mEventUpdateReceiver);
}
public void onStop() {
super.onStop();
}
public void onDestroy() {
super.onDestroy();
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
public boolean onKeyDown(int keyCode, KeyEvent ev) {
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
SlidingDrawer drawer = (SlidingDrawer) findViewById(R.id.np_drawer);
if(drawer.isOpened()) {
drawer.animateClose();
return true;
}
else if(drawer.isMoving()) {
drawer.close();
return true;
}
}
return super.onKeyDown(keyCode, ev);
}
public Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
switch(id) {
case DIALOG_STATION_PICKER:
builder.setTitle(R.string.label_pickStation)
.setNegativeButton(R.string.label_cancel, null);
// Print a slightly helpful message if the stations were not
// retrieved for some reason.
if(!mSession.hasStations()) {
return builder.setMessage(R.string.msg_noStations).create();
}
Station stations[] = mSession.cloneStations();
// Change station when one is selected from dialog.
final ListView listView = new ListView(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int index, long id) {
Station s = (Station) listView.getItemAtPosition(index);
mSession.setStation(s.getId());
NowPlayingActivity.this.dismissDialog(DIALOG_STATION_PICKER);
refresh();
}
});
listView.setAdapter(new StationListAdapter(this, stations));
return builder.setView(listView)
.create();
default:
// Assume the number must be a string resource id.
return builder.setTitle(R.string.label_error)
.setMessage(id)
.setPositiveButton(R.string.label_ok, null)
.create();
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
TouchInterceptor list = (TouchInterceptor) findViewById(R.id.np_request_list);
inflater.inflate(R.menu.queue_menu, menu);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
Song s = (Song) list.getItemAtPosition(info.position);
menu.setHeaderTitle(s.getTitle());
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.remove:
TouchInterceptor list = (TouchInterceptor) findViewById(R.id.np_request_list);
SongListAdapter adapter = (SongListAdapter) list.getAdapter();
Song s = adapter.removeSong(info.position);
requestRemove(s);
resyncRequests();
return true;
default:
return super.onContextItemSelected(item);
}
}
/**
* Sets up listeners for this activity.
*/
private void setListeners() {
// The rating dialog should show up if the Song rating view is clicked.
findViewById(R.id.np_songRating).setOnTouchListener(
new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent e) {
Workspace w = (Workspace) findViewById(R.id.np_workspace);
HorizontalRatingBar b = (HorizontalRatingBar) findViewById(R.id.np_songRating);
if(mSession == null || !mSession.isTunedIn() || !mSession.hasCredentials()) {
if(e.getAction() == MotionEvent.ACTION_DOWN) {
w.lockCurrentScreen();
b.setLabel(R.string.msg_tuneInFirst);
}
else if(e.getAction() == MotionEvent.ACTION_UP) {
w.unlockCurrentScreen();
b.setLabel(R.string.label_song);
}
return true;
}
HorizontalRatingBar hrb = (HorizontalRatingBar) v;
float rating = 0.0f;
float max = 5.0f;
switch(e.getAction()) {
case MotionEvent.ACTION_DOWN:
w.lockCurrentScreen();
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
v.performClick();
rating = hrb.snapPositionToMinorIncrement(e.getX());
rating = Math.max(1.0f, Math.min(rating, 5.0f));
max = hrb.getMax();
hrb.setPrimaryValue(rating);
String label = String.format(Locale.US, "%.1f/%.1f",rating,max);
hrb.setLabel(label);
if(e.getAction() == MotionEvent.ACTION_UP) {
w.unlockCurrentScreen();
Song s = mSession.getCurrentEvent().getCurrentSong();
new RateTask(rating).execute(s);
b.setLabel(R.string.label_song);
}
}
return true;
}
});
// Show album rating when the album rating bar is touched.
findViewById(R.id.np_albumRating).setOnTouchListener(
new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent e) {
Workspace w = (Workspace) findViewById(R.id.np_workspace);
HorizontalRatingBar b = (HorizontalRatingBar) findViewById(R.id.np_albumRating);
if(mSession == null || !mSession.isTunedIn() || !mSession.hasCredentials()) {
if(e.getAction() == MotionEvent.ACTION_DOWN) {
w.lockCurrentScreen();
b.setLabel(R.string.msg_tuneInFirst);
}
else if(e.getAction() == MotionEvent.ACTION_UP) {
w.unlockCurrentScreen();
b.setLabel(R.string.label_album);
}
return true;
}
HorizontalRatingBar hrb = (HorizontalRatingBar) v;
float rating = 0.0f;
float max = 5.0f;
switch(e.getAction()) {
case MotionEvent.ACTION_DOWN:
w.lockCurrentScreen();
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
v.performClick();
rating = hrb.getPrimary();
max = hrb.getMax();
String label = String.format(Locale.US, "%.1f/%.1f",rating,max);
hrb.setLabel(label);
if(e.getAction() == MotionEvent.ACTION_UP) {
w.unlockCurrentScreen();
b.setLabel(R.string.label_album);
}
}
return true;
}
});
// Spawn a vote task when an item from the election drawer is selected.
final ListView election = (ListView) findViewById(R.id.np_electionList);
election.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int i, long id) {
SongListAdapter adapter = (SongListAdapter) election.getAdapter();
Song song = adapter.getSong(i);
// Do nothing if they selected the item we last voted for.
if(song.getElectionEntryId() == mSession.getLastVoteId()) {
return;
}
// Show a message if they are not tuned in.
if(mSession.isTunedIn() && mSession.hasCredentials()) {
new VoteTask(i).execute();
}
else {
showDialog(R.string.msg_tunedInVote);
}
}
});
// Reorder requests when the users drags-and-drops them.
final TouchInterceptor requestList = ((TouchInterceptor) findViewById(R.id.np_request_list));
requestList.setDropListener(new TouchInterceptor.DropListener() {
@Override
public void drop(int from, int to) {
if(from == to) return;
SongListAdapter adapter = (SongListAdapter) requestList.getAdapter();
adapter.moveSong(from, to);
ArrayList<Song> songs = adapter.getSongs();
requestReorder( songs.toArray(new Song[songs.size()]) );
}
});
// Lock down the current workspace when clicking on the drag handles of
// the request list.
requestList.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent ev) {
if(ev.getAction() == MotionEvent.ACTION_UP) {
v.performClick();
}
if(requestList.getCount() == 0) return false;
Workspace w = (Workspace) findViewById(R.id.np_workspace);
// Benefit of the doubt: unlock in case we locked earlier.
if(ev.getAction() == MotionEvent.ACTION_UP) {
w.unlockCurrentScreen();
}
float x = ev.getX();
if(ev.getAction() == MotionEvent.ACTION_DOWN && x < 64) {
w.lockCurrentScreen();
}
return false;
}
});
// Update the pager when the workspace changes.
Workspace w = (Workspace) findViewById(R.id.np_workspace);
w.setOnScreenChangeListener(new OnScreenChangeListener() {
@Override
public void onScreenChanged(View newScreen, int newScreenIndex) {
PagerWidget pw = (PagerWidget) findViewById(R.id.pager);
pw.setCurrent(newScreenIndex);
}
@Override
public void onScreenChanging(View newScreen, int newScreenIndex) {
}
});
registerForContextMenu(findViewById(R.id.np_request_list));
}
/** Tell a SyncService that it should stop. */
private void stopSyncService() {
stopService(new Intent(NowPlayingActivity.this, SyncService.class)
.setAction(SyncService.ACTION_INFO)
);
stopService(new Intent(NowPlayingActivity.this, SyncService.class)
.setAction(SyncService.ACTION_SYNC)
);
}
/**
* Force an update of the schedule information.
*/
private void refresh() {
stopSyncService();
Intent local = new Intent(this, SyncService.class);
local.setAction(SyncService.ACTION_INFO);
startService(local);
if(mHasIndeterminateProgress) {
setProgressBarIndeterminateVisibility(true);
setProgressBarIndeterminate(true);
}
}
/**
* Performs an update of song info.
* @param init flag to indicate this
* is an initial (non-long-poll) fetch.
*/
private void fetchSchedules() {
// Only do an immediate fetch from here.
if(mSession.requiresSync()) {
refresh();
}
else {
// already have one so just sync
onScheduleSync();
}
}
/** Spawn a background task to send new request ordering. */
private void requestReorder(Song requests[]) {
new ReorderTask().execute(requests);
}
/** Spawn a new background task to remove a requested song. */
private void requestRemove(Song s) {
new RemoveTask().execute(s);
}
/**
* Sets the vote drawer to opened or closed. Does nothing if the auto-slide preference is disabled.
*
* @param state, true for open, false for closed
*/
private void setDrawerState(boolean state) {
if(!mPreferences.getAutoshowElection()) {
return;
}
SlidingDrawer v = (SlidingDrawer) this.findViewById(R.id.np_drawer);
if(state && !v.isOpened()) {
v.animateOpen();
}
else if(v.isOpened()) {
v.animateClose();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
// Start RainwavePreferenceActivity.
case R.id.menu_preferences:
startPreferences();
break;
case R.id.menu_refresh:
refresh();
break;
case R.id.menu_playStream:
startPlayer();
break;
case R.id.menu_playlist:
startPlaylist();
break;
case R.id.menu_pickStation:
showDialog(NowPlayingActivity.DIALOG_STATION_PICKER);
break;
}
return false;
}
/** Starts the media player for the current station's stream. */
private void startPlayer() {
int stationId = mSession.getStationId();
Station s = mSession.getStation(stationId);
if(s != null) {
Intent i = new Intent(Intent.ACTION_VIEW);
/** Start the PlaylistActivity. */
/** Start the PreferencesActivity. */
/**
* Destroys any existing Session and creates a new Session object for us to
* use, pulling the user_id and key attributes from the default Preference
* store.
*/
private void initializeSession() {
handleIntent();
mSession = Session.getInstance(this);
mSession.unpickle();
mPreferences = RainwavePreferences.getInstance(this);
}
/**
* Handle activity intent. This activity is configured to handle rw:// URL's
* if triggered from elsewhere in the OS.
*/
private void handleIntent() {
final Intent i = getIntent();
if(i == null) {
return;
}
Bundle b = i.getExtras();
Uri uri = i.getData();
if(uri == null){
return;
}
// check if this Intent was previously handled
boolean handled = (b != null) && b.getBoolean("handled-uri", false);
if(handled) {
return;
}
// store in preferences if all is well
final String parts[] = Utility.parseUrl(uri);
if(parts != null) {
mPreferences.setUserInfo(parts[0], parts[1]);
}
i.putExtra("handled-uri", true);
}
/**
* Executes when a schedule sync finished.
* @param response the response the server issued
*/
private void onScheduleSync() {
// Updates title, album, and artists.
updateSongInfo(mSession.getCurrentEvent().getCurrentSong());
// Updates song, album ratings.
setRatings(mSession.getCurrentEvent().getCurrentSong());
// Updates election info.
updateElection();
// Refresh clock and title bar state.
refreshTitle();
// Updates request lsit.
updateRequests();
// Update album art if there is any
updateAlbumArt(mSession.getCurrentAlbumArt());
// Cancel old countdown if there is one.
if(mCountdown != null) {
mCountdown.cancel();
}
// Start a countdown task for the event.
if(mSession.getCurrentEvent() != null) {
mCountdown = new CountDownTimer(mSession.getCurrentEvent().getEnd() - mSession.getDrift(), 1000) {
public void onFinish() { }
public void onTick(long millisUntilFinished) {
refreshTitle();
}
}.start();
}
}
/** Update the song countdown timer in the application heading. */
private void refreshTitle() {
long end = mSession.getCurrentEvent().getEnd();
long utc = System.currentTimeMillis() / 1000;
long seconds = (end - utc) - mSession.getDrift();
seconds = Math.max(0, seconds);
long minutes = seconds / 60;
seconds %= 60;
Resources r = getResources();
int id = mSession.getStationId();
String stationName = (mSession.hasStations()) ? mSession.getStation(id).getName() : null;
String title = (stationName != null) ? stationName : r.getString(R.string.app_name);
String state = r.getString(R.string.label_nottunedin);
if(!mSession.hasCredentials()) {
state = r.getString(R.string.label_anonymous);
}
else if(mSession.isTunedIn()) {
state = r.getString(R.string.label_tunedin);
}
setTitle(String.format("[%2d:%02d] %s (%s)", minutes, seconds, title, state));
}
/** Make the election drawer update to the latest known election. */
private void updateElection() {
SongListAdapter adapter = new SongListAdapter(
this,
R.layout.item_song_election,
new ArrayList<Song>(Arrays.asList(mSession.getNextEvent().cloneSongs()))
);
((ListView)findViewById(R.id.np_electionList))
.setAdapter(adapter);
// Set vote deadline for when the song ends.
adapter.setDeadline(mSession.getCurrentEvent().getEnd() - mSession.getDrift());
// Open the drawer if the user can vote.
boolean canVote = !mSession.hasLastVote() && mSession.isTunedIn();
setDrawerState(canVote);
if(mSession.hasLastVote()) {
adapter.updateVoteState(mSession.getLastVoteId());
}
}
/** Update the request list UI to the latest known request list. */
private void updateRequests() {
Song songs[];
if(mSession.hasRequests()){
songs = mSession.cloneRequests();
}
else {
songs = new Song[0];
}
TouchInterceptor requestList = (TouchInterceptor) findViewById(R.id.np_request_list);
requestList.setAdapter(
new SongListAdapter(
this,
R.layout.item_song_request,
new ArrayList<Song>(Arrays.asList(songs))
)
);
resyncRequests();
}
/** Update the visibility of the "no pending requests" message. */
private void resyncRequests() {
TouchInterceptor requestList = (TouchInterceptor) findViewById(R.id.np_request_list);
SongListAdapter adapter = (SongListAdapter) requestList.getAdapter();
if(adapter != null) {
int visibility = (adapter.getCount()) > 0 ? View.GONE : View.VISIBLE;
findViewById(R.id.np_request_overlay).setVisibility(visibility);
}
}
/**
* Updates the song title, album title, and artists in the user interface.
*
* @param current
* the current song that's playing.
*/
private void updateSongInfo(Song current) {
((TextView) findViewById(R.id.np_songTitle)).setText(current.getTitle());
((TextView) findViewById(R.id.np_albumTitle)).setText(current.getDefaultAlbum().getName());
((TextView) findViewById(R.id.np_artist)).setText(current.collapseArtists());
ImageView accent = (ImageView)findViewById(R.id.np_accent);
TextView requestor = (TextView)findViewById(R.id.np_requestor);
Resources r = getResources();
if(current.isRequest()) {
accent.setImageResource(R.drawable.accent_song_hilight);
requestor.setVisibility(View.VISIBLE);
requestor.setText(String.format(r.getString(R.string.label_requestor), current.getRequestor()));
}
else {
accent.setImageResource(R.drawable.accent_song);
requestor.setVisibility(View.GONE);
}
}
/**
* Updates the song and album ratings.
*
* @param current
* the current song playing
*/
private void setRatings(Song current) {
final Album album = current.getDefaultAlbum();
((HorizontalRatingBar) findViewById(R.id.np_songRating))
.setBothValues(current.getUserRating(), current.getCommunityRating());
((HorizontalRatingBar) findViewById(R.id.np_albumRating))
.setBothValues(album.getUserRating(), album.getCommunityRating());
}
/**
* Executes when a "rate song" request has finished.
*
* @param result
* the result the server issued
*/
private void onRateSong(SongRating rating) {
((HorizontalRatingBar) findViewById(R.id.np_songRating))
.setPrimaryValue(rating.getUserRating());
((HorizontalRatingBar) findViewById(R.id.np_albumRating))
.setPrimaryValue(rating.getDefaultAlbumRating().getUserRating());
}
/**
* Sets the album art to the provided Bitmap, or a default image if art is
* null.
*
* @param art
* desired album art
*/
private void updateAlbumArt(Bitmap art) {
if(art == null) {
art = BitmapFactory.decodeResource(getResources(), R.drawable.noart);
}
((ImageView) findViewById(R.id.np_albumArt)).setImageBitmap(art);
}
/** Receives schedule updates from the sync service. */
private BroadcastReceiver mEventUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, String.format("Got '%s'", action));
Context ctx = NowPlayingActivity.this;
setProgressBarIndeterminateVisibility(false);
// Success -- update the UI and receive further updates.
if(SyncService.BROADCAST_EVENT_UPDATE.equals(action)) {
onScheduleSync();
if(mSession.hasCredentials()) {
Intent local = new Intent(NowPlayingActivity.this, SyncService.class);
local.setAction(SyncService.ACTION_SYNC);
startService(local);
}
}
// Credentials are bad. Automatic sync will not be attempted. The
// user may re-initiate and an anonymous request is attempted.
else if(SyncService.BROADCAST_REAUTHENTICATE.equals(action)) {
mSession.clearUserInfo();
Toast.makeText(ctx, R.string.msg_authenticationFailure, Toast.LENGTH_LONG).show();
}
// General failure -- connection or otherwise.
else if(SyncService.BROADCAST_EVENT_UPDATE_FAILED.equals(action)) {
Toast.makeText(ctx, R.string.msg_eventUpdateFailure, Toast.LENGTH_LONG).show();
}
else if(action == null) {
Log.w(TAG, "Sync service sent no action -- ignoring.");
}
else {
Log.w(TAG,
String.format("Sync service sent unrecognized action '%s'.", action)
);
}
}
};
/** Removes a sequence of requests in background */
private class RemoveTask extends AsyncTask<Song, Integer, Boolean> {
@Override
protected Boolean doInBackground(Song... songs) {
boolean result = true;
for(Song song : songs) {
try {
mSession.deleteRequest(song);
} catch (RainwaveException exc) {
Log.w(TAG, "Remove request operation failed", exc);
result |= false;
}
}
return result;
}
@Override
protected void onPostExecute(Boolean result) {
if(!result) {
Toast.makeText(NowPlayingActivity.this, R.string.msg_genericError, Toast.LENGTH_SHORT).show();
}
}
}
/** Rates a batch of songs in background */
private class RateTask extends AsyncTask<Song, Integer, SongRating[]> {
private float mRating;
public RateTask(float rating) {
mRating = rating;
}
@Override
protected SongRating[] doInBackground(Song... params) {
SongRating[] results = new SongRating[params.length];
for(int i = 0; i < params.length; i++) {
try {
results[i] = mSession.rateSong(params[i].getId(), mRating);
} catch (RainwaveException exc) {
String msg = String.format(Locale.US, "Can't rate %s", params[i]);
Log.w(TAG, msg, exc);
}
}
return results;
}
@Override
protected void onPostExecute(SongRating[] result) {
boolean error = false;
for(SongRating rating : result) {
if(rating != null) {
onRateSong(rating);
}
else {
error = true;
}
}
if(error) {
Toast.makeText(NowPlayingActivity.this, R.string.msg_genericError, Toast.LENGTH_SHORT).show();
}
}
}
/** Reorders requests in background. */
private class ReorderTask extends AsyncTask<Song, Integer, Song[]> {
@Override
protected Song[] doInBackground(Song... requests) {
try {
return mSession.reorderRequests(requests);
} catch (RainwaveException exc) {
Log.w(TAG, "Reorder requests operation failed", exc);
return null;
}
}
@Override
protected void onPostExecute(Song[] reorderResult) {
if(reorderResult == null) {
Toast.makeText(NowPlayingActivity.this, R.string.msg_genericError, Toast.LENGTH_SHORT).show();
}
}
}
/** AsyncTask for voting in the election. */
private class VoteTask extends AsyncTask<Song, Integer, Boolean> {
private Song mSong;
private int mSelection;
public VoteTask(int selection) {
ListView electionList = (ListView) findViewById(R.id.np_electionList);
SongListAdapter adapter = (SongListAdapter) electionList.getAdapter();
mSelection = selection;
mSong = adapter.getSong(selection);
}
@Override
protected void onPreExecute() {
ListView electionList = (ListView) findViewById(R.id.np_electionList);
SongListAdapter adapter = (SongListAdapter) electionList.getAdapter();
adapter.setVoting(mSelection);
}
protected Boolean doInBackground(Song...params) {
try {
mSession.vote(mSong.getElectionEntryId());
return true;
} catch (RainwaveException e) {
Log.e(TAG, "API error", e);
}
return false;
}
protected void onPostExecute(Boolean result) {
if(!result) {
Toast.makeText(NowPlayingActivity.this, R.string.msg_genericError, Toast.LENGTH_SHORT).show();
}
ListView electionList = (ListView) findViewById(R.id.np_electionList);
SongListAdapter adapter = (SongListAdapter) electionList.getAdapter();
adapter.resyncVoteState(mSession.getLastVoteId());
}
}
/** Dialog identifiers */
public static final int
DIALOG_STATION_PICKER = 0xb1c7;
}
|
package mapeper.ticonautotoolstation;
import mapeper.ticonautotoolstation.modes.IATSMode;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.Constants;
import org.apache.logging.log4j.Level;
public class AutoToolStationTileEntity extends TileEntity implements ISidedInventory {
boolean haveNewToolInSlot;
int mode;
ItemStack[] inventory;
public AutoToolStationTileEntity() {
inventory = new ItemStack[3];
}
public static final int[] accessibleSlots = new int[]{C.MODSLOT, C.TOOLSLOT, C.TOOLOUTSLOT};
@Override
public int[] getAccessibleSlotsFromSide(int side) {
return accessibleSlots;
}
@Override
public boolean canInsertItem(int slot, ItemStack stack, int side) {
if (TinkerUtils.isModifyableTool(stack)) {
return slot == C.TOOLSLOT && (inventory[C.TOOLOUTSLOT] == null || inventory[C.TOOLOUTSLOT].stackSize == 0);
} else {
return slot == C.MODSLOT;
}
}
@Override
public boolean canExtractItem(int slot, ItemStack stack, int side) {
return slot == C.TOOLOUTSLOT;
}
@Override
public int getSizeInventory() {
return inventory.length;
}
@Override
public ItemStack getStackInSlot(int slot) {
return inventory[slot];
}
@Override
public ItemStack decrStackSize(int slot, int amt) {
ItemStack stack = getStackInSlot(slot);
if (stack != null) {
if (stack.stackSize <= amt) {
setInventorySlotContents(slot, null);
} else {
stack = stack.splitStack(amt);
if (stack.stackSize == 0) {
setInventorySlotContents(slot, null);
}
}
}
return stack;
}
@Override
public ItemStack getStackInSlotOnClosing(int slot) {
ItemStack stack = getStackInSlot(slot);
if (stack != null) {
setInventorySlotContents(slot, null);
}
return stack;
}
@Override
public void setInventorySlotContents(int slot, ItemStack stack) {
inventory[slot] = stack;
if (!worldObj.isRemote) {
if (stack != null && slot == C.TOOLSLOT) {
haveNewToolInSlot = true;
}
}
if (stack != null && stack.stackSize > getInventoryStackLimit()) {
stack.stackSize = getInventoryStackLimit();
}
}
@Override
public String getInventoryName() {
return "tile.ats_autotoolstation.name";
}
@Override
public boolean hasCustomInventoryName() {
return false;
}
@Override
public int getInventoryStackLimit() {
return 64;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
return worldObj.getTileEntity(xCoord, yCoord, zCoord) == this &&
player.getDistanceSq(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5) < 64;
}
@Override
public void openInventory() {
}
@Override
public void closeInventory() {
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack stack) {
if (slot == C.TOOLSLOT)
return TinkerUtils.isModifyableTool(stack) && (inventory[C.TOOLOUTSLOT] == null || inventory[C.TOOLOUTSLOT].stackSize == 0);
return true;
}
@Override
public void updateEntity() {
if (!this.worldObj.isRemote) {
if (inventory[C.MODSLOT] != null && inventory[C.MODSLOT].stackSize >= 1 && inventory[C.TOOLSLOT] != null) {
ItemStack modifierCopy = inventory[C.MODSLOT].copy();
modifierCopy.stackSize = 1;
ItemStack modifyResult = TinkerUtils.modifyItem(inventory[C.TOOLSLOT], new ItemStack[]{modifierCopy.copy()});
if (!haveNewToolInSlot) {
modifyResult = getMode().shouldMoveToOutput(inventory[C.TOOLSLOT], modifyResult);
} else {
haveNewToolInSlot = false;
}
if (modifyResult == null) {
//Could not apply more modifiers
if (inventory[C.TOOLOUTSLOT] == null || inventory[C.TOOLOUTSLOT].stackSize == 0) {
inventory[C.TOOLOUTSLOT] = inventory[C.TOOLSLOT];
inventory[C.TOOLSLOT] = null;
this.markDirty();
} else {
TiConAutoToolStation.LOGGER.log(Level.ERROR, "Auto Tool Station output slot was not empty, but we want to move a tool there!");
}
} else {
decrStackSize(C.MODSLOT, 1);
inventory[C.TOOLSLOT] = modifyResult;
this.markDirty();
}
}
}
}
@Override
public void readFromNBT(NBTTagCompound tagCompound) {
super.readFromNBT(tagCompound);
NBTTagList tagList = tagCompound.getTagList("Inventory", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < tagList.tagCount(); i++) {
NBTTagCompound tag = tagList.getCompoundTagAt(i);
byte slot = tag.getByte("Slot");
if (slot >= 0 && slot < inventory.length) {
inventory[slot] = ItemStack.loadItemStackFromNBT(tag);
}
}
if (tagCompound.hasKey("Mode")) {
mode = tagCompound.getInteger("Mode");
} else {
mode = 0;
}
if (tagCompound.hasKey("newTool")) {
haveNewToolInSlot = tagCompound.getBoolean("newTool");
} else {
haveNewToolInSlot = false;
}
}
@Override
public Packet getDescriptionPacket() {
NBTTagCompound tagCompound = new NBTTagCompound();
tagCompound.setInteger("Mode", mode);
return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, tagCompound);
}
@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) {
NBTTagCompound tag = pkt.func_148857_g();
this.mode = tag.getInteger("Mode");
}
@Override
public void writeToNBT(NBTTagCompound tagCompound) {
super.writeToNBT(tagCompound);
NBTTagList itemList = new NBTTagList();
for (int i = 0; i < inventory.length; i++) {
ItemStack stack = inventory[i];
if (stack != null) {
NBTTagCompound tag = new NBTTagCompound();
tag.setByte("Slot", (byte) i);
stack.writeToNBT(tag);
itemList.appendTag(tag);
}
}
tagCompound.setTag("Inventory", itemList);
tagCompound.setInteger("Mode", mode);
tagCompound.setBoolean("newTool", haveNewToolInSlot);
}
public IATSMode getMode() {
return IATSMode.modes.get(this.mode);
}
}
|
package agaricus.applysrg;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import java.util.ArrayList;
import java.util.List;
public class ApplySrgActionExperimental extends AnAction {
public Project project;
public JavaPsiFacade facade;
public ApplySrgActionExperimental() {
super("Apply Srg");
}
/** Get list of Java files selected by the user
*
* @param event
* @return List of Java files with PSI ready to process
*/
private List<PsiJavaFile> getSelectedJavaFiles(AnActionEvent event) {
List<PsiJavaFile> javaFileList = new ArrayList<PsiJavaFile>();
PsiManager psiManager = PsiManager.getInstance(project);
// Get selected files
VirtualFile[] selectedFiles = event.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);
if (selectedFiles == null || selectedFiles.length == 0) {
Messages.showMessageDialog(project, "Please select the files you want to transform in the View > Tool Windows > Project view, then try again.", "No selection", Messages.getErrorIcon());
return null;
}
System.out.println("Selected "+ selectedFiles.length+" files");
List<VirtualFile> skippedFiles = new ArrayList<VirtualFile>();
for(VirtualFile file: selectedFiles) {
System.out.println("- " + file);
PsiFile psiFile = psiManager.findFile(file);
if (psiFile == null) {
// no psi structure for this file
skippedFiles.add(file);
continue;
}
System.out.println("psiFile: " + psiFile);
if (!(psiFile instanceof PsiJavaFile)) {
System.out.println("Skipping non-Java file "+file);
skippedFiles.add(file);
// TODO: possibly try to load this file as Java for PSI parsing
continue;
}
PsiJavaFile psiJavaFile = (PsiJavaFile)psiFile;
javaFileList.add(psiJavaFile);
}
if (skippedFiles.size() != 0) {
StringBuilder sb = new StringBuilder("Non-Java files were selected ("+skippedFiles.size()+" of "+selectedFiles.length+"): \n\n");
for (VirtualFile skippedFile: skippedFiles) {
sb.append("- " + skippedFile.getPresentableName() + "\n");
}
if (skippedFiles.size() == selectedFiles.length) {
sb.append("\nNo valid Java source files in your project were selected. Please select the files you want to process in View > Tool Windows > Project and try again.");
Messages.showMessageDialog(project, sb.toString(), "No Java files selected", Messages.getErrorIcon());
return null;
}
sb.append("\nThe above files will not be processed. Do you want to continue processing the other "+javaFileList.size()+" files?");
if (Messages.showYesNoDialog(project, sb.toString(), "Skipping non-Java files", Messages.getWarningIcon()) != 0) {
return null;
}
}
return javaFileList;
}
private void processFile(PsiJavaFile psiJavaFile) {
System.out.println("processing "+psiJavaFile);
PsiPackageStatement psiPackageStatement = psiJavaFile.getPackageStatement();
if (psiPackageStatement != null) {
System.out.println("@,"+psiPackageStatement.getPackageReference().getTextRange()+",package,"+psiPackageStatement.getPackageName());
//TODO psiJavaFile.setPackageName("");
}
PsiImportList psiImportList = psiJavaFile.getImportList();
PsiImportStatementBase[] psiImportStatements = psiImportList.getAllImportStatements();
for (PsiImportStatementBase psiImportStatement : psiImportStatements) {
PsiJavaCodeReferenceElement psiJavaCodeReferenceElement = psiImportStatement.getImportReference();
String qualifiedName = psiJavaCodeReferenceElement.getQualifiedName();
System.out.println("@,"+psiJavaCodeReferenceElement.getTextRange()+",import,"+qualifiedName);
// TODO: replace through map
}
PsiClass[] psiClasses = psiJavaFile.getClasses();
for (PsiClass psiClass : psiClasses) {
processClass(psiClass);
}
}
private void processClass(PsiClass psiClass) {
String className = psiClass.getQualifiedName();
System.out.println("@,"+psiClass.getNameIdentifier().getTextRange()+",class,"+className);
// Methods and fields in this class (not 'all', which includes superclass)
PsiField[] psiFields = psiClass.getFields();
for (PsiField psiField : psiFields) {
PsiTypeElement psiTypeElement = psiField.getTypeElement();
System.out.println("@,"+psiTypeElement.getTextRange()+",type,"+psiTypeElement.getType().getInternalCanonicalText());
System.out.println("@,"+psiField.getNameIdentifier().getTextRange()+",field,"+className+","+psiField.getName());
//TODO psiField.setName("");
}
PsiMethod[] psiMethods = psiClass.getMethods();
for (PsiMethod psiMethod: psiMethods) {
processMethod(className, psiMethod);
}
}
private void processMethod(String className, PsiMethod psiMethod) {
System.out.println("@,"+psiMethod.getNameIdentifier().getTextRange()+",method,"+className+","+psiMethod.getName());
PsiParameterList psiParameterList = psiMethod.getParameterList();
PsiParameter[] psiParameters = psiParameterList.getParameters();
for (int pindex = 0; pindex < psiParameters.length; ++pindex) {
PsiParameter psiParameter = psiParameters[pindex];
PsiTypeElement psiTypeElement = psiParameter.getTypeElement();
System.out.println("@,"+psiTypeElement.getTextRange()+",type,"+className+","+psiMethod.getName()+","+pindex+","+psiTypeElement.getType().getInternalCanonicalText());
System.out.println("@,"+psiParameter.getNameIdentifier().getTextRange()+",methodparam,"+className+","+psiMethod.getName()+","+pindex+","+psiParameter.getName());
}
PsiCodeBlock psiCodeBlock = psiMethod.getBody();
walk(className, psiMethod, psiCodeBlock, 0);
/*
PsiStatement[] psiStatements = psiCodeBlock.getStatements();
for (PsiStatement psiStatement : psiStatements) {
}
*/
}
private void walk(String className, PsiMethod psiMethod, PsiElement psiElement, int depth) {
System.out.println("walking "+className+" "+psiMethod.getName()+" -- "+psiElement);
if (psiElement == null) {
return;
}
if (psiElement instanceof PsiReferenceExpression) {
PsiReferenceExpression psiReferenceExpression = (PsiReferenceExpression)psiElement;
PsiElement parent = psiReferenceExpression.getParent();
boolean isMethodCall = parent instanceof PsiMethodCallExpression;
PsiExpression psiQualifierExpression = psiReferenceExpression.getQualifierExpression();
PsiType psiQualifierType = psiQualifierExpression != null ? psiQualifierExpression.getType() : null;
System.out.println(" ref "+psiReferenceExpression+
" resolve="+psiReferenceExpression.resolve()+
" text="+psiReferenceExpression.getText()+
" qualifiedName="+psiReferenceExpression.getQualifiedName()+
" qualifierExpr="+psiReferenceExpression.getQualifierExpression()+
" qualifierType="+(psiQualifierType != null ? psiQualifierType.getInternalCanonicalText() : "null")
);
}
PsiElement[] children = psiElement.getChildren();
if (children != null) {
for (PsiElement child: children) {
walk(className, psiMethod, child, depth + 1);
}
}
}
public void actionPerformed(AnActionEvent event) {
System.out.println("ApplySrg2Source experimental starting");
project = event.getData(PlatformDataKeys.PROJECT);
facade = JavaPsiFacade.getInstance(project);
VirtualFile projectFileDirectory = event.getData(PlatformDataKeys.PROJECT_FILE_DIRECTORY);
System.out.println("project file directory = "+projectFileDirectory);
List<PsiJavaFile> psiJavaFiles = getSelectedJavaFiles(event);
if (psiJavaFiles == null) {
return;
}
System.out.println("Processing "+psiJavaFiles.size()+" files");
for (PsiJavaFile psiJavaFile: psiJavaFiles) {
processFile(psiJavaFile);
}
/*
PsiPackage psiPackage = facade.findPackage("agaricus.applysrg.samplepackage");
PsiClass[] psiClasses = psiPackage.getClasses();
System.out.println("psiClasses="+psiClasses);
for (PsiClass psiClass: psiClasses) {
System.out.println("* "+psiClass.getQualifiedName());
PsiMethod[] psiMethods = psiClass.getMethods();
for (PsiMethod psiMethod: psiMethods) {
System.out.println("- method: "+psiMethod);
PsiParameterList psiParameterList = psiMethod.getParameterList();
PsiParameter[] psiParameters = psiParameterList.getParameters();
PsiCodeBlock psiCodeBlock = psiMethod.getBody();
PsiElement element = psiCodeBlock.getFirstBodyElement();
do {
element = element.getNextSibling();
System.out.println("-- "+element);
} while(element != null);
}
PsiField[] psiFields = psiClass.getFields();
for (PsiField psiField: psiFields) {
System.out.println("- field: "+psiField);
}
}*/
List<RenamingClass> classes = new ArrayList<RenamingClass>();
List<RenamingField> fields = new ArrayList<RenamingField>();
List<RenamingMethod> methods = new ArrayList<RenamingMethod>();
List<RenamingMethodParametersList> parametersLists = new ArrayList<RenamingMethodParametersList>();
if (!SrgLoader.promptAndLoadSrg(project, classes, fields, methods, parametersLists))
return;
}
}
|
package com.dmdirc.ui.swing;
import com.dmdirc.Channel;
import com.dmdirc.FrameContainer;
import com.dmdirc.ui.IconManager;
import com.dmdirc.Query;
import com.dmdirc.Server;
import com.dmdirc.WritableFrameContainer;
import com.dmdirc.commandparser.parsers.CommandParser;
import com.dmdirc.config.IdentityManager;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.ui.core.dialogs.sslcertificate.SSLCertificateDialogModel;
import com.dmdirc.ui.interfaces.ChannelWindow;
import com.dmdirc.ui.interfaces.InputWindow;
import com.dmdirc.ui.interfaces.QueryWindow;
import com.dmdirc.ui.interfaces.ServerWindow;
import com.dmdirc.ui.interfaces.StatusBar;
import com.dmdirc.ui.interfaces.UIController;
import com.dmdirc.ui.interfaces.Window;
import com.dmdirc.ui.swing.components.FeedbackNag;
import com.dmdirc.ui.swing.components.SwingStatusBar;
import com.dmdirc.ui.swing.dialogs.updater.SwingUpdaterDialog;
import com.dmdirc.ui.swing.dialogs.url.URLDialog;
import com.dmdirc.ui.swing.dialogs.channelsetting.ChannelSettingsDialog;
import com.dmdirc.ui.swing.dialogs.error.ErrorListDialog;
import com.dmdirc.ui.swing.dialogs.wizard.firstrun.SwingFirstRunWizard;
import com.dmdirc.ui.swing.dialogs.serversetting.ServerSettingsDialog;
import com.dmdirc.ui.swing.dialogs.sslcertificate.SSLCertificateDialog;
import com.dmdirc.ui.swing.dialogs.wizard.WizardListener;
import com.dmdirc.updater.Update;
import com.dmdirc.util.ReturnableThread;
import java.awt.Font;
import java.awt.Toolkit;
import java.net.URI;
import java.util.List;
import java.util.concurrent.Semaphore;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import net.miginfocom.layout.PlatformDefaults;
/**
* Controls the main swing UI.
*/
public final class SwingController implements UIController {
/** Singleton instance of MainFrame. */
private static MainFrame me;
/** Status bar. */
private static SwingStatusBar statusBar;
/** Semaphore used for controlling access to statusBar. */
private static final Semaphore STATUSBAR_SEMAPHORE = new Semaphore(1);
/** Instantiates a new SwingController. */
public SwingController() {
//Do nothing
}
/**
* Does the main frame exist?
*
* @return true iif mainframe exists
*/
protected static boolean hasMainFrame() {
return me != null;
}
/** {@inheritDoc} */
@Override
public synchronized MainFrame getMainWindow() {
return getMainFrame();
}
/**
* Retrieves the main window used by this UI.
*
* @return This UI's main window
*/
public synchronized static MainFrame getMainFrame() {
if (me == null) {
UIUtilities.invokeAndWait(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
me = new MainFrame();
}
});
UIUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
ErrorListDialog.getErrorListDialog();
}
});
}
return me;
}
/** {@inheritDoc} */
@Override
public StatusBar getStatusBar() {
return getSwingStatusBar();
}
/**
* Retrieves the Swing Status Bar used by this UI.
*
* @return This UI's status bar
*/
public static SwingStatusBar getSwingStatusBar() {
STATUSBAR_SEMAPHORE.acquireUninterruptibly();
if (statusBar == null) {
statusBar = UIUtilities.invokeAndWait(new ReturnableThread<SwingStatusBar>() {
/** {@inheritDoc} */
@Override
public void run() {
setObject(new SwingStatusBar());
}
});
}
STATUSBAR_SEMAPHORE.release();
return statusBar;
}
/** {@inheritDoc} */
@Override
public ChannelWindow getChannel(final Channel channel) {
return UIUtilities.invokeAndWait(new ReturnableThread<ChannelFrame>() {
/** {@inheritDoc} */
@Override
public void run() {
setObject(new ChannelFrame(channel));
}
});
}
/** {@inheritDoc} */
@Override
public ServerWindow getServer(final Server server) {
return UIUtilities.invokeAndWait(new ReturnableThread<ServerFrame>() {
/** {@inheritDoc} */
@Override
public void run() {
setObject(new ServerFrame(server));
}
});
}
/** {@inheritDoc} */
@Override
public QueryWindow getQuery(final Query query) {
return UIUtilities.invokeAndWait(new ReturnableThread<QueryFrame>() {
/** {@inheritDoc} */
@Override
public void run() {
setObject(new QueryFrame(query));
}
});
}
/** {@inheritDoc} */
@Override
public Window getWindow(final FrameContainer owner) {
return UIUtilities.invokeAndWait(new ReturnableThread<CustomFrame>() {
/** {@inheritDoc} */
@Override
public void run() {
setObject(new CustomFrame(owner));
}
});
}
/** {@inheritDoc} */
@Override
public InputWindow getInputWindow(final WritableFrameContainer owner,
final CommandParser commandParser) {
return UIUtilities.invokeAndWait(new ReturnableThread<CustomInputFrame>() {
/** {@inheritDoc} */
@Override
public void run() {
setObject(new CustomInputFrame(owner, commandParser));
}
});
}
/** {@inheritDoc} */
@Override
public SwingUpdaterDialog getUpdaterDialog(final List<Update> updates) {
return UIUtilities.invokeAndWait(new ReturnableThread<SwingUpdaterDialog>() {
/** {@inheritDoc} */
@Override
public void run() {
setObject(SwingUpdaterDialog.getSwingUpdaterDialog(updates));
}
});
}
/** {@inheritDoc} */
@Override
public void showFirstRunWizard() {
showFirstRunWizard(true);
}
/** {@inheritDoc} */
@Override
public void showMigrationWizard() {
showFirstRunWizard(false);
}
/**
* Shows a first run wizard, or a migration wizard.
*
* @param firstRun First run?
*/
private synchronized void showFirstRunWizard(final boolean firstRun) {
final Semaphore semaphore = new Semaphore(0);
UIUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final WizardListener listener = new WizardListener() {
/** {@inheritDoc} */
@Override
public void wizardFinished() {
semaphore.release();
}
/** {@inheritDoc} */
@Override
public void wizardCancelled() {
semaphore.release();
}
};
final SwingFirstRunWizard wizard =
new SwingFirstRunWizard(firstRun);
wizard.getWizardDialog().addWizardListener(listener);
wizard.display();
}
});
semaphore.acquireUninterruptibly();
}
/** {@inheritDoc} */
@Override
public void showChannelSettingsDialog(final Channel channel) {
UIUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
ChannelSettingsDialog.showChannelSettingsDialog(channel);
}
});
}
/** {@inheritDoc} */
@Override
public void showServerSettingsDialog(final Server server) {
UIUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
ServerSettingsDialog.showServerSettingsDialog(server);
}
});
}
/**
* Updates the look and feel to the current config setting.
*/
static void updateLookAndFeel() {
try {
UIManager.setLookAndFeel(UIUtilities.getLookAndFeel(IdentityManager.
getGlobalConfig().
getOption("ui", "lookandfeel", "")));
final int state = UIUtilities.invokeAndWait(new ReturnableThread<Integer>() {
/** {@inheritDoc} */
@Override
public void run() {
setObject(getMainFrame().getExtendedState());
}
});
for (final java.awt.Window window : getMainFrame().
getTopLevelWindows()) {
UIUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
SwingUtilities.updateComponentTreeUI(window);
if (window != getMainFrame()) {
window.pack();
}
}
});
}
UIUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
getMainFrame().setExtendedState(state);
}
});
} catch (ClassNotFoundException ex) {
Logger.userError(ErrorLevel.LOW,
"Unable to change Look and Feel: " +
ex.getMessage());
} catch (InstantiationException ex) {
Logger.userError(ErrorLevel.LOW,
"Unable to change Look and Feel: " +
ex.getMessage());
} catch (IllegalAccessException ex) {
Logger.userError(ErrorLevel.LOW,
"Unable to change Look and Feel: " +
ex.getMessage());
} catch (UnsupportedLookAndFeelException ex) {
Logger.userError(ErrorLevel.LOW,
"Unable to change Look and Feel: " +
ex.getMessage());
}
}
/** {@inheritDoc} */
@Override
public void initUISettings() {
// For this to work it *HAS* to be before anything else UI related.
final boolean aaSetting = IdentityManager.getGlobalConfig().
getOptionBool("ui", "antialias", true);
System.setProperty("awt.useSystemAAFontSettings",
Boolean.toString(aaSetting));
System.setProperty("swing.aatext", Boolean.toString(aaSetting));
// This will do nothing on non OS X Systems
if (Apple.isApple()) {
final Apple apple = Apple.getApple();
apple.setUISettings();
apple.setListener();
}
final Font defaultFont = new Font(Font.DIALOG, Font.TRUETYPE_FONT,
12);
if (UIManager.getFont("TextField.font") == null) {
UIManager.put("TextField.font", defaultFont);
}
if (UIManager.getFont("TextPane.font") == null) {
UIManager.put("TextPane.font", defaultFont);
}
UIManager.put("Tree.collapsedIcon",
IconManager.getIconManager().getIcon("nothing"));
UIManager.put("Tree.expandedIcon",
IconManager.getIconManager().getIcon("nothing"));
try {
UIUtilities.initUISettings();
UIManager.setLookAndFeel(UIUtilities.getLookAndFeel(IdentityManager.
getGlobalConfig().
getOption("ui", "lookandfeel", "")));
} catch (UnsupportedOperationException ex) {
Logger.userError(ErrorLevel.LOW, "Unable to set UI Settings");
} catch (UnsupportedLookAndFeelException ex) {
Logger.userError(ErrorLevel.LOW, "Unable to set UI Settings");
} catch (IllegalAccessException ex) {
Logger.userError(ErrorLevel.LOW, "Unable to set UI Settings");
} catch (InstantiationException ex) {
Logger.userError(ErrorLevel.LOW, "Unable to set UI Settings");
} catch (ClassNotFoundException ex) {
Logger.userError(ErrorLevel.LOW, "Unable to set UI Settings");
}
if ("Metal".equals(UIManager.getLookAndFeel().getName())) {
PlatformDefaults.setPlatform(PlatformDefaults.WINDOWS_XP);
}
Toolkit.getDefaultToolkit().getSystemEventQueue().
push(new DMDircEventQueue());
}
/** {@inheritDoc} */
@Override
public Window getActiveWindow() {
if (me == null) {
return null;
}
return me.getActiveFrame();
}
/** {@inheritDoc} */
@Override
public Server getActiveServer() {
if (me == null) {
return null;
}
if (getActiveWindow() == null) {
return null;
} else {
return getActiveWindow().getContainer().getServer();
}
}
/** {@inheritDoc} */
@Override
public void showURLDialog(final URI url) {
UIUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
URLDialog.showURLDialog(url);
}
});
}
/** {@inheritDoc} */
@Override
public void showSSLCertificateDialog(final SSLCertificateDialogModel model) {
UIUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
new SSLCertificateDialog(getMainFrame(), model).setVisible(true);
}
});
}
/** {@inheritDoc} */
@Override
public void showFeedbackNag() {
UIUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
new FeedbackNag();
}
});
}
/** {@inheritDoc} */
@Override
public void showMessageDialog(final String title, final String message) {
UIUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
JOptionPane.showMessageDialog(null, message, title,
JOptionPane.PLAIN_MESSAGE);
}
});
}
/** {@inheritDoc} */
@Override
public String getUserInput(final String prompt) {
return JOptionPane.showInputDialog(prompt);
}
/**
* Returns the current look and feel.
*
* @return Current look and feel
*/
public static String getLookAndFeel() {
return UIManager.getLookAndFeel().getName();
}
}
|
package com.ecyrd.jspwiki.plugin;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.*;
import java.util.*;
/**
* Inserts page contents. Muchos thanks to Scott Hurlbert for the initial code.
*
* @since 2.1.37
* @author Scott Hurlbert
* @author Janne Jalkanen
*/
public class InsertPage
implements WikiPlugin
{
private static Logger log = Logger.getLogger( InsertPage.class );
public static final String PARAM_PAGENAME = "page";
public static final String PARAM_STYLE = "style";
public static final String PARAM_MAXLENGTH = "maxlength";
public static final String PARAM_CLASS = "class";
public static final String PARAM_SECTION = "section";
private static final String DEFAULT_STYLE = "";
public String execute( WikiContext context, Map params )
throws PluginException
{
WikiEngine engine = context.getEngine();
StringBuffer res = new StringBuffer();
String clazz = (String) params.get( PARAM_CLASS );
String includedPage = (String) params.get( PARAM_PAGENAME );
String style = (String) params.get( PARAM_STYLE );
int section = TextUtil.parseIntParameter((String) params.get( PARAM_SECTION ),
-1 );
int maxlen = TextUtil.parseIntParameter((String) params.get( PARAM_MAXLENGTH ),
-1 );
if( style == null ) style = DEFAULT_STYLE;
if( maxlen == -1 ) maxlen = Integer.MAX_VALUE;
if( includedPage != null )
{
WikiPage page = engine.getPage( includedPage );
if( page != null )
{
/**
* We want inclusion to occur within the context of
* its own page, because we need the links to be correct.
*/
WikiContext includedContext = (WikiContext) context.clone();
includedContext.setPage( page );
String pageData = engine.getPureText( page );
String moreLink = "";
if( section != -1 )
{
try
{
pageData = TextUtil.getSection( pageData, section );
}
catch( IllegalArgumentException e )
{
throw new PluginException( e.getMessage() );
}
}
if( pageData.length() > maxlen )
{
pageData = pageData.substring( 0, maxlen )+" ...";
moreLink = "<p><a href=\""+engine.getViewURL(includedPage)+"\">More...</a></p>";
}
res.append("<div style=\""+style+"\""+(clazz != null ? " class=\""+clazz+"\"" : "")+">");
res.append( engine.textToHTML( includedContext, pageData ) );
res.append( moreLink );
res.append("</div>");
}
else
{
res.append("There is no page called '"+includedPage+"'. Would you like to ");
res.append("<a href=\""+engine.getEditURL( includedPage )+"\">create it?</a>");
}
}
else
{
res.append("<span class=\"error\">");
res.append("You have to define a page!");
res.append("</span>");
}
return res.toString();
}
}
|
package mil.nga.geopackage.extension.coverage;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import mil.nga.geopackage.BoundingBox;
import mil.nga.geopackage.GeoPackageConstants;
import mil.nga.geopackage.GeoPackageCore;
import mil.nga.geopackage.GeoPackageException;
import mil.nga.geopackage.core.contents.ContentsDataType;
import mil.nga.geopackage.extension.BaseExtension;
import mil.nga.geopackage.extension.ExtensionScopeType;
import mil.nga.geopackage.extension.Extensions;
import mil.nga.geopackage.property.GeoPackageProperties;
import mil.nga.geopackage.property.PropertyConstants;
import mil.nga.geopackage.tiles.matrix.TileMatrix;
import mil.nga.geopackage.tiles.matrixset.TileMatrixSet;
import mil.nga.geopackage.tiles.user.TileTable;
import mil.nga.sf.proj.Projection;
import mil.nga.sf.proj.ProjectionTransform;
import org.osgeo.proj4j.ProjCoordinate;
/**
* Tiled Gridded Coverage Core Data Extension
*
* @param <TImage>
* image type
*
* @author osbornb
* @since 2.0.1
*/
public abstract class CoverageDataCore<TImage extends CoverageDataImage>
extends BaseExtension {
/**
* Extension author
*/
public static final String EXTENSION_AUTHOR = GeoPackageConstants.GEO_PACKAGE_EXTENSION_AUTHOR;
/**
* Extension name without the author
*/
public static final String EXTENSION_NAME_NO_AUTHOR = "2d_gridded_coverage";
/**
* Extension, with author and name
*/
public static final String EXTENSION_NAME = Extensions.buildExtensionName(
EXTENSION_AUTHOR, EXTENSION_NAME_NO_AUTHOR);
/**
* Extension definition URL
*/
public static final String EXTENSION_DEFINITION = GeoPackageProperties
.getProperty(PropertyConstants.EXTENSIONS, EXTENSION_NAME_NO_AUTHOR);
/**
* Tile Matrix Set
*/
private final TileMatrixSet tileMatrixSet;
/**
* Gridded Coverage DAO
*/
private final GriddedCoverageDao griddedCoverageDao;
/**
* Gridded Tile DAO
*/
private final GriddedTileDao griddedTileDao;
/**
* Gridded coverage
*/
private GriddedCoverage griddedCoverage;
/**
* Coverage data results width
*/
protected Integer width;
/**
* Coverage data results height
*/
protected Integer height;
/**
* Projection of the requests
*/
protected final Projection requestProjection;
/**
* Projection of the coverage data
*/
protected final Projection coverageProjection;
/**
* Coverage data bounding box
*/
protected final BoundingBox coverageBoundingBox;
/**
* Flag indicating the coverage data and request projections are the same
*/
protected final boolean sameProjection;
/**
* True if zooming in should be performed to find a tile matrix with
* coverage data values
*/
protected boolean zoomIn = true;
/**
* True if zooming out should be performed to find a tile matrix with
* coverage data values
*/
protected boolean zoomOut = true;
/**
* True if zoom in in before zooming out, false to zoom out first
*/
protected boolean zoomInBeforeOut = true;
/**
* Interpolation algorithm
*/
protected CoverageDataAlgorithm algorithm = CoverageDataAlgorithm.NEAREST_NEIGHBOR;
/**
* Value pixel encoding type
*/
protected GriddedCoverageEncodingType encoding = GriddedCoverageEncodingType.CENTER;
/**
* Constructor
*
* @param geoPackage
* GeoPackage
* @param tileMatrixSet
* tile matrix set
* @param width
* specified results width
* @param height
* specified results height
* @param requestProjection
* request projection
*/
protected CoverageDataCore(GeoPackageCore geoPackage,
TileMatrixSet tileMatrixSet, Integer width, Integer height,
Projection requestProjection) {
super(geoPackage);
this.tileMatrixSet = tileMatrixSet;
griddedCoverageDao = geoPackage.getGriddedCoverageDao();
griddedTileDao = geoPackage.getGriddedTileDao();
queryGriddedCoverage();
this.width = width;
this.height = height;
this.requestProjection = requestProjection;
coverageProjection = tileMatrixSet.getSrs().getProjection();
coverageBoundingBox = tileMatrixSet.getBoundingBox();
// Check if the projections have the same units
if (requestProjection != null) {
sameProjection = (requestProjection.getUnit().name
.equals(coverageProjection.getUnit().name));
} else {
sameProjection = true;
}
}
/**
* Constructor for creating extension rows when creating a new coverage data
* tile table
*
* @param geoPackage
* GeoPackage
* @param tileMatrixSet
* tile matrix set
*/
protected CoverageDataCore(GeoPackageCore geoPackage,
TileMatrixSet tileMatrixSet) {
this(geoPackage, tileMatrixSet, null, null, null);
}
/**
* Get the coverage data value from the image at the coordinate
*
* @param griddedTile
* gridded tile
* @param image
* coverage data image
* @param x
* x coordinate
* @param y
* y coordinate
* @return coverage data value
*/
public abstract Double getValue(GriddedTile griddedTile, TImage image,
int x, int y);
/**
* Get the requested coverage data values with the requested width and
* height
*
* @param request
* coverage data request
* @param width
* coverage data request width
* @param height
* coverage data request height
* @return coverage data results
*/
public abstract CoverageDataResults getValues(CoverageDataRequest request,
Integer width, Integer height);
/**
* Get the requested unbounded coverage data values. Unbounded results
* retrieves and returns each coverage data pixel. The results size equals
* the width and height of all matching pixels.
*
* @param request
* coverage data request
* @return coverage data results
*/
public abstract CoverageDataResults getValuesUnbounded(
CoverageDataRequest request);
/**
* Get the Tile Matrix Set
*
* @return Tile Matrix Set
*/
public TileMatrixSet getTileMatrixSet() {
return tileMatrixSet;
}
/**
* Get the Gridded Coverage DAO
*
* @return Gridded Coverage DAO
*/
public GriddedCoverageDao getGriddedCoverageDao() {
return griddedCoverageDao;
}
/**
* Get the Gridded Tile DAO
*
* @return Gridded Tile DAO
*/
public GriddedTileDao getGriddedTileDao() {
return griddedTileDao;
}
/**
* Get the requested coverage data width
*
* @return width
*/
public Integer getWidth() {
return width;
}
/**
* Set the requested coverage data width
*
* @param width
* requested coverage data width
*/
public void setWidth(Integer width) {
this.width = width;
}
/**
* Get the requested coverage data height
*
* @return height
*/
public Integer getHeight() {
return height;
}
/**
* Set the requested coverage data height
*
* @param height
* requested coverage data height
*/
public void setHeight(Integer height) {
this.height = height;
}
/**
* Get the request projection
*
* @return request projection
*/
public Projection getRequestProjection() {
return requestProjection;
}
/**
* Get the coverage data projection
*
* @return coverage data projection
*/
public Projection getCoverageProjection() {
return coverageProjection;
}
/**
* Get the coverage data bounding box
*
* @return coverage data bounding box
*/
public BoundingBox getCoverageBoundingBox() {
return coverageBoundingBox;
}
/**
* Is the request and coverage data projection the same
*
* @return true if the same
*/
public boolean isSameProjection() {
return sameProjection;
}
/**
* Is the zooming in (higher zoom level values) enabled to find matching
* coverage data
*
* @return true if zoom in enabled
*/
public boolean isZoomIn() {
return zoomIn;
}
/**
* Set the zoom in enabled state
*
* @param zoomIn
* true to zoom in when finding coverage data, false to disable
*/
public void setZoomIn(boolean zoomIn) {
this.zoomIn = zoomIn;
}
/**
* Is the zooming out (lower zoom level values) enabled to find matching
* coverage data
*
* @return true if zoom out enabled
*/
public boolean isZoomOut() {
return zoomOut;
}
/**
* Set the zoom out enabled state
*
* @param zoomOut
* true to zoom out when finding coverage data, false to disable
*/
public void setZoomOut(boolean zoomOut) {
this.zoomOut = zoomOut;
}
/**
* Is zooming in (when enabled) performed before zooming out (when enabled)
*
* @return true to zoom in for results first, false to zoom out for results
* first
*/
public boolean isZoomInBeforeOut() {
return zoomInBeforeOut;
}
/**
* Set the zoom order between in and out
*
* @param zoomInBeforeOut
* true to zoom in for results first, false to zoom out first
*/
public void setZoomInBeforeOut(boolean zoomInBeforeOut) {
this.zoomInBeforeOut = zoomInBeforeOut;
}
/**
* Get the interpolation algorithm
*
* @return algorithm
*/
public CoverageDataAlgorithm getAlgorithm() {
return algorithm;
}
/**
* Set the interpolation algorithm
*
* @param algorithm
* algorithm type
*/
public void setAlgorithm(CoverageDataAlgorithm algorithm) {
if (algorithm == null) {
algorithm = CoverageDataAlgorithm.NEAREST_NEIGHBOR;
}
this.algorithm = algorithm;
}
/**
* Get the value pixel encoding type
*
* @return encoding type
* @since 2.0.1
*/
public GriddedCoverageEncodingType getEncoding() {
return encoding;
}
/**
* Set the value pixel encoding type
*
* @param encoding
* encoding type
* @since 2.0.1
*/
public void setEncoding(GriddedCoverageEncodingType encoding) {
if (encoding == null) {
encoding = GriddedCoverageEncodingType.CENTER;
}
this.encoding = encoding;
}
/**
* Get or create the extension
*
* @return extensions list
*/
public List<Extensions> getOrCreate() {
// Create tables
geoPackage.createGriddedCoverageTable();
geoPackage.createGriddedTileTable();
List<Extensions> extensionList = new ArrayList<>();
Extensions coverage = getOrCreate(EXTENSION_NAME,
GriddedCoverage.TABLE_NAME, null, EXTENSION_DEFINITION,
ExtensionScopeType.READ_WRITE);
Extensions tile = getOrCreate(EXTENSION_NAME, GriddedTile.TABLE_NAME,
null, EXTENSION_DEFINITION, ExtensionScopeType.READ_WRITE);
Extensions table = getOrCreate(EXTENSION_NAME,
tileMatrixSet.getTableName(), TileTable.COLUMN_TILE_DATA,
EXTENSION_DEFINITION, ExtensionScopeType.READ_WRITE);
extensionList.add(coverage);
extensionList.add(tile);
extensionList.add(table);
return extensionList;
}
/**
* Determine if the Tile Matrix Set has the extension
*
* @return true if has extension
*/
public boolean has() {
boolean exists = has(EXTENSION_NAME, tileMatrixSet.getTableName(),
TileTable.COLUMN_TILE_DATA);
return exists;
}
/**
* Get the gridded coverage
*
* @return gridded coverage
*/
public GriddedCoverage getGriddedCoverage() {
return griddedCoverage;
}
/**
* Query and update the gridded coverage
*
* @return gridded coverage
*/
public GriddedCoverage queryGriddedCoverage() {
try {
if (griddedCoverageDao.isTableExists()) {
griddedCoverage = griddedCoverageDao.query(tileMatrixSet);
}
} catch (SQLException e) {
throw new GeoPackageException(
"Failed to get Gridded Coverage for table name: "
+ tileMatrixSet.getTableName(), e);
}
return griddedCoverage;
}
/**
* Get the gridded tile
*
* @return gridded tiles
*/
public List<GriddedTile> getGriddedTile() {
List<GriddedTile> griddedTile = null;
try {
if (griddedTileDao.isTableExists()) {
griddedTile = griddedTileDao
.query(tileMatrixSet.getTableName());
}
} catch (SQLException e) {
throw new GeoPackageException(
"Failed to get Gridded Tile for table name: "
+ tileMatrixSet.getTableName(), e);
}
return griddedTile;
}
/**
* Get the gridded tile by id
*
* @param tileId
* tile id
* @return gridded tile
*/
public GriddedTile getGriddedTile(long tileId) {
GriddedTile griddedTile = null;
try {
if (griddedTileDao.isTableExists()) {
griddedTile = griddedTileDao.query(
tileMatrixSet.getTableName(), tileId);
}
} catch (SQLException e) {
throw new GeoPackageException(
"Failed to get Gridded Tile for table name: "
+ tileMatrixSet.getTableName() + ", tile id: "
+ tileId, e);
}
return griddedTile;
}
/**
* Get the data null value
*
* @return data null value or null
*/
public Double getDataNull() {
Double dataNull = null;
if (griddedCoverage != null) {
dataNull = griddedCoverage.getDataNull();
}
return dataNull;
}
/**
* Check the pixel value to see if it is the null equivalent
*
* @param value
* pixel value
* @return true if equivalent to data null
*/
public boolean isDataNull(double value) {
Double dataNull = getDataNull();
boolean isDataNull = dataNull != null && dataNull == value;
return isDataNull;
}
/**
* Get the coverage data tile tables
*
* @param geoPackage
* GeoPackage
* @return table names
*/
public static List<String> getTables(GeoPackageCore geoPackage) {
return geoPackage.getTables(ContentsDataType.GRIDDED_COVERAGE);
}
/**
* Reproject the coverage data to the requested projection
*
* @param values
* coverage data values
* @param requestedCoverageWidth
* requested coverage data width
* @param requestedCoverageHeight
* requested coverage data height
* @param requestBoundingBox
* request bounding box in the request projection
* @param transformRequestToCoverage
* transformation from request to coverage data
* @param coverageBoundingBox
* coverage data bounding box
* @return projected coverage data
*/
protected Double[][] reprojectCoverageData(Double[][] values,
int requestedCoverageWidth, int requestedCoverageHeight,
BoundingBox requestBoundingBox,
ProjectionTransform transformRequestToCoverage,
BoundingBox coverageBoundingBox) {
final double requestedWidthUnitsPerPixel = (requestBoundingBox
.getMaxLongitude() - requestBoundingBox.getMinLongitude())
/ requestedCoverageWidth;
final double requestedHeightUnitsPerPixel = (requestBoundingBox
.getMaxLatitude() - requestBoundingBox.getMinLatitude())
/ requestedCoverageHeight;
final double tilesDistanceWidth = coverageBoundingBox.getMaxLongitude()
- coverageBoundingBox.getMinLongitude();
final double tilesDistanceHeight = coverageBoundingBox.getMaxLatitude()
- coverageBoundingBox.getMinLatitude();
final int width = values[0].length;
final int height = values.length;
Double[][] projectedValues = new Double[requestedCoverageHeight][requestedCoverageWidth];
// Retrieve each coverage data value in the unprojected coverage data
for (int y = 0; y < requestedCoverageHeight; y++) {
for (int x = 0; x < requestedCoverageWidth; x++) {
double longitude = requestBoundingBox.getMinLongitude()
+ (x * requestedWidthUnitsPerPixel);
double latitude = requestBoundingBox.getMaxLatitude()
- (y * requestedHeightUnitsPerPixel);
ProjCoordinate fromCoord = new ProjCoordinate(longitude,
latitude);
ProjCoordinate toCoord = transformRequestToCoverage
.transform(fromCoord);
double projectedLongitude = toCoord.x;
double projectedLatitude = toCoord.y;
int xPixel = (int) Math
.round(((projectedLongitude - coverageBoundingBox
.getMinLongitude()) / tilesDistanceWidth)
* width);
int yPixel = (int) Math
.round(((coverageBoundingBox.getMaxLatitude() - projectedLatitude) / tilesDistanceHeight)
* height);
xPixel = Math.max(0, xPixel);
xPixel = Math.min(width - 1, xPixel);
yPixel = Math.max(0, yPixel);
yPixel = Math.min(height - 1, yPixel);
Double coverageData = values[yPixel][xPixel];
projectedValues[y][x] = coverageData;
}
}
return projectedValues;
}
/**
* Format the unbounded results from coverage data tiles into a single
* double array of coverage data
*
* @param tileMatrix
* tile matrix
* @param rowsMap
* rows map
* @param tileCount
* tile count
* @param minRow
* min row
* @param maxRow
* max row
* @param minColumn
* min column
* @param maxColumn
* max column
* @return coverage data
*/
protected Double[][] formatUnboundedResults(TileMatrix tileMatrix,
Map<Long, Map<Long, Double[][]>> rowsMap, int tileCount,
long minRow, long maxRow, long minColumn, long maxColumn) {
// Handle formatting the results
Double[][] values = null;
if (!rowsMap.isEmpty()) {
// If only one tile result, use the coverage data as the result
if (tileCount == 1) {
values = rowsMap.get(minRow).get(minColumn);
} else {
// Else, combine all results into a single coverage data result
// Get the top left and bottom right coverage data values
Double[][] topLeft = rowsMap.get(minRow).get(minColumn);
Double[][] bottomRight = rowsMap.get(maxRow).get(maxColumn);
// Determine the width and height of the top left coverage data
// results
int firstWidth = topLeft[0].length;
int firstHeight = topLeft.length;
// Determine the final result width and height
int width = firstWidth;
int height = firstHeight;
if (minColumn < maxColumn) {
width += bottomRight[0].length;
long middleColumns = maxColumn - minColumn - 1;
if (middleColumns > 0) {
width += (middleColumns * tileMatrix.getTileWidth());
}
}
if (minRow < maxRow) {
height += bottomRight.length;
long middleRows = maxRow - minRow - 1;
if (middleRows > 0) {
height += (middleRows * tileMatrix.getTileHeight());
}
}
// Create the coverage data result array
values = new Double[height][width];
// Copy the coverage data values from each tile results into the
// final result arrays
for (Map.Entry<Long, Map<Long, Double[][]>> rows : rowsMap
.entrySet()) {
// Determine the starting base row for this tile
long row = rows.getKey();
int baseRow = 0;
if (minRow < row) {
baseRow = firstHeight
+ (int) ((row - minRow - 1) * tileMatrix
.getTileHeight());
}
// Get the row's columns map
Map<Long, Double[][]> columnsMap = rows.getValue();
for (Map.Entry<Long, Double[][]> columns : columnsMap
.entrySet()) {
// Determine the starting base column for this tile
long column = columns.getKey();
int baseColumn = 0;
if (minColumn < column) {
baseColumn = firstWidth
+ (int) ((column - minColumn - 1) * tileMatrix
.getTileWidth());
}
// Get the tiles coverage data values
Double[][] localValues = columns.getValue();
// Copy the columns array at each local coverage data
// row to the global row and column result location
for (int localRow = 0; localRow < localValues.length; localRow++) {
int globalRow = baseRow + localRow;
System.arraycopy(localValues[localRow], 0,
values[globalRow], baseColumn,
localValues[localRow].length);
}
}
}
}
}
return values;
}
/**
* Determine the x source pixel location
*
* @param x
* x pixel
* @param destLeft
* destination left most pixel
* @param srcLeft
* source left most pixel
* @param widthRatio
* source over destination width ratio
* @return x source pixel
*/
protected float getXSource(int x, float destLeft, float srcLeft,
float widthRatio) {
float dest = getXEncodedLocation(x, encoding);
float source = getSource(dest, destLeft, srcLeft, widthRatio);
return source;
}
/**
* Determine the y source pixel location
*
* @param y
* y pixel
* @param destTop
* destination top most pixel
* @param srcTop
* source top most pixel
* @param heightRatio
* source over destination height ratio
* @return y source pixel
*/
protected float getYSource(int y, float destTop, float srcTop,
float heightRatio) {
float dest = getYEncodedLocation(y, encoding);
float source = getSource(dest, destTop, srcTop, heightRatio);
return source;
}
/**
* Determine the source pixel location
*
* @param dest
* destination pixel location
* @param destMin
* destination minimum most pixel
* @param srcMin
* source minimum most pixel
* @param ratio
* source over destination length ratio
* @return source pixel
*/
private float getSource(float dest, float destMin, float srcMin, float ratio) {
float destDistance = dest - destMin;
float srcDistance = destDistance * ratio;
float ySource = srcMin + srcDistance;
return ySource;
}
/**
* Get the X encoded location from the base provided x
*
* @param x
* x location
* @param encodingType
* pixel encoding type
* @return encoded x location
*/
private float getXEncodedLocation(float x,
GriddedCoverageEncodingType encodingType) {
float xLocation = x;
switch (encodingType) {
case CENTER:
case AREA:
xLocation += 0.5f;
break;
case CORNER:
break;
default:
throw new GeoPackageException("Unsupported Encoding Type: "
+ encodingType);
}
return xLocation;
}
/**
* Get the Y encoded location from the base provided y
*
* @param y
* y location
* @param encodingType
* pixel encoding type
* @return encoded y location
*/
private float getYEncodedLocation(float y,
GriddedCoverageEncodingType encodingType) {
float yLocation = y;
switch (encodingType) {
case CENTER:
case AREA:
yLocation += 0.5f;
break;
case CORNER:
yLocation += 1.0f;
break;
default:
throw new GeoPackageException("Unsupported Encoding Type: "
+ encodingType);
}
return yLocation;
}
/**
* Determine the nearest neighbors of the source pixel, sorted by closest to
* farthest neighbor
*
* @param xSource
* x source pixel
* @param ySource
* y source pixel
* @return nearest neighbor pixels
*/
protected List<int[]> getNearestNeighbors(float xSource, float ySource) {
List<int[]> results = new ArrayList<int[]>();
// Get the coverage data source pixels for x and y
CoverageDataSourcePixel xPixel = getXSourceMinAndMax(xSource);
CoverageDataSourcePixel yPixel = getYSourceMinAndMax(ySource);
// Determine which x pixel is the closest, the second closest, and the
// distance to the second pixel
int firstX;
int secondX;
float xDistance;
if (xPixel.getOffset() > .5) {
firstX = xPixel.getMax();
secondX = xPixel.getMin();
xDistance = 1.0f - xPixel.getOffset();
} else {
firstX = xPixel.getMin();
secondX = xPixel.getMax();
xDistance = xPixel.getOffset();
}
// Determine which y pixel is the closest, the second closest, and the
// distance to the second pixel
int firstY;
int secondY;
float yDistance;
if (yPixel.getOffset() > .5) {
firstY = yPixel.getMax();
secondY = yPixel.getMin();
yDistance = 1.0f - yPixel.getOffset();
} else {
firstY = yPixel.getMin();
secondY = yPixel.getMax();
yDistance = yPixel.getOffset();
}
// Add the closest neighbor
results.add(new int[] { firstX, firstY });
// Add the second and third neighbor based upon the x and y distances to
// second coordinates
if (xDistance <= yDistance) {
results.add(new int[] { secondX, firstY });
results.add(new int[] { firstX, secondY });
} else {
results.add(new int[] { firstX, secondY });
results.add(new int[] { secondX, firstY });
}
// Add the farthest neighbor
results.add(new int[] { secondX, secondY });
// If right on the boundary between the forward and backwards pixel, add
// the backwards pixel options
if (xPixel.getOffset() == 0) {
results.add(new int[] { xPixel.getMin() - 1, yPixel.getMin() });
results.add(new int[] { xPixel.getMin() - 1, yPixel.getMax() });
}
if (yPixel.getOffset() == 0) {
results.add(new int[] { xPixel.getMin(), yPixel.getMin() - 1 });
results.add(new int[] { xPixel.getMax(), yPixel.getMin() - 1 });
}
if (xPixel.getOffset() == 0 && yPixel.getOffset() == 0) {
results.add(new int[] { xPixel.getMin() - 1, yPixel.getMin() - 1 });
}
return results;
}
/**
* Get the min, max, and offset of the source X pixel
*
* @param source
* source x pixel
* @return source x pixel information
*/
protected CoverageDataSourcePixel getXSourceMinAndMax(float source) {
int floor = (int) Math.floor(source);
float valueLocation = getXEncodedLocation(floor,
griddedCoverage.getGridCellEncodingType());
CoverageDataSourcePixel pixel = getSourceMinAndMax(source, floor,
valueLocation);
return pixel;
}
/**
* Get the min, max, and offset of the source Y pixel
*
* @param source
* source y pixel
* @return source y pixel information
*/
protected CoverageDataSourcePixel getYSourceMinAndMax(float source) {
int floor = (int) Math.floor(source);
float valueLocation = getYEncodedLocation(floor,
griddedCoverage.getGridCellEncodingType());
CoverageDataSourcePixel pixel = getSourceMinAndMax(source, floor,
valueLocation);
return pixel;
}
/**
* Get the min, max, and offset of the source pixel
*
* @param source
* source pixel
* @param sourceFloor
* source floor value
* @param valueLocation
* value location
* @return source pixel information
*/
private CoverageDataSourcePixel getSourceMinAndMax(float source,
int sourceFloor, float valueLocation) {
int min = sourceFloor;
int max = sourceFloor;
float offset;
if (source < valueLocation) {
min
offset = 1.0f - (valueLocation - source);
} else {
max++;
offset = source - valueLocation;
}
return new CoverageDataSourcePixel(source, min, max, offset);
}
/**
* Get the Bilinear Interpolation coverage data value
*
* @param sourcePixelX
* source pixel x
* @param sourcePixelY
* source pixel y
* @param values
* 2 x 2 coverage data values as [y][x]
* @return coverage data value
*/
protected Double getBilinearInterpolationValue(
CoverageDataSourcePixel sourcePixelX,
CoverageDataSourcePixel sourcePixelY, Double[][] values) {
return getBilinearInterpolationValue(sourcePixelX.getOffset(),
sourcePixelY.getOffset(), sourcePixelX.getMin(),
sourcePixelX.getMax(), sourcePixelY.getMin(),
sourcePixelY.getMax(), values);
}
/**
* Get the Bilinear Interpolation coverage data value
*
* @param offsetX
* x source pixel offset
* @param offsetY
* y source pixel offset
* @param minX
* min x value
* @param maxX
* max x value
* @param minY
* min y value
* @param maxY
* max y value
* @param values
* 2 x 2 coverage data values as [y][x]
* @return coverage data value
*/
protected Double getBilinearInterpolationValue(float offsetX,
float offsetY, float minX, float maxX, float minY, float maxY,
Double[][] values) {
Double value = null;
if (values != null) {
value = getBilinearInterpolationValue(offsetX, offsetY, minX, maxX,
minY, maxY, values[0][0], values[0][1], values[1][0],
values[1][1]);
}
return value;
}
/**
* Get the Bilinear Interpolation coverage data value
*
* @param offsetX
* x source pixel offset
* @param offsetY
* y source pixel offset
* @param minX
* min x value
* @param maxX
* max x value
* @param minY
* min y value
* @param maxY
* max y value
* @param topLeft
* top left coverage value
* @param topRight
* top right coverage value
* @param bottomLeft
* bottom left coverage value
* @param bottomRight
* bottom right coverage value
* @return coverage data value
*/
protected Double getBilinearInterpolationValue(float offsetX,
float offsetY, float minX, float maxX, float minY, float maxY,
Double topLeft, Double topRight, Double bottomLeft,
Double bottomRight) {
Double value = null;
if (topLeft != null && (topRight != null || minX == maxX)
&& (bottomLeft != null || minY == maxY)
&& (bottomRight != null || (minX == maxX && minY == maxY))) {
float diffX = maxX - minX;
double topRow;
Double bottomRow;
if (diffX == 0) {
topRow = topLeft;
bottomRow = bottomLeft;
} else {
float diffLeft = offsetX;
float diffRight = diffX - offsetX;
topRow = ((diffRight / diffX) * topLeft)
+ ((diffLeft / diffX) * topRight);
bottomRow = ((diffRight / diffX) * bottomLeft)
+ ((diffLeft / diffX) * bottomRight);
}
float diffY = maxY - minY;
double result;
if (diffY == 0) {
result = topRow;
} else {
float diffTop = offsetY;
float diffBottom = diffY - offsetY;
result = ((diffBottom / diffY) * topRow)
+ ((diffTop / diffY) * bottomRow);
}
value = result;
}
return value;
}
/**
* Get the bicubic interpolation coverage data value from the 4 x 4 coverage
* data values
*
* @param values
* coverage data values
* @param sourcePixelX
* source pixel x
* @param sourcePixelY
* source pixel y
* @return bicubic coverage data value
*/
protected Double getBicubicInterpolationValue(Double[][] values,
CoverageDataSourcePixel sourcePixelX,
CoverageDataSourcePixel sourcePixelY) {
return getBicubicInterpolationValue(values, sourcePixelX.getOffset(),
sourcePixelY.getOffset());
}
/**
* Get the bicubic interpolation coverage data value from the 4 x 4 coverage
* data values
*
* @param values
* coverage data values
* @param offsetX
* x source pixel offset
* @param offsetY
* y source pixel offset
* @return bicubic coverage data value
*/
protected Double getBicubicInterpolationValue(Double[][] values,
float offsetX, float offsetY) {
Double value = null;
Double[] rowValues = new Double[4];
for (int y = 0; y < 4; y++) {
Double rowValue = getCubicInterpolationValue(values[y][0],
values[y][1], values[y][2], values[y][3], offsetX);
if (rowValue == null) {
rowValues = null;
break;
}
rowValues[y] = rowValue;
}
if (rowValues != null) {
value = getCubicInterpolationValue(rowValues, offsetY);
}
return value;
}
/**
* Interpolate 4 values using the offset between value1 and value2
*
* @param values
* coverage data values
* @param offset
* offset between the middle two pixels
* @return value coverage data value
*/
protected Double getCubicInterpolationValue(Double[] values, double offset) {
Double value = null;
if (values != null) {
value = getCubicInterpolationValue(values[0], values[1], values[2],
values[3], offset);
}
return value;
}
/**
* Interpolate 4 values using the offset between value1 and value2
*
* @param value0
* index 0 value
* @param value1
* index 1 value
* @param value2
* index 2 value
* @param value3
* index 3 value
* @param offset
* offset between the middle two pixels
* @return value coverage data value
*/
protected Double getCubicInterpolationValue(Double value0, Double value1,
Double value2, Double value3, double offset) {
Double value = null;
if (value0 != null && value1 != null && value2 != null
&& value3 != null) {
double coefficient0 = 2 * value1;
double coefficient1 = value2 - value0;
double coefficient2 = 2 * value0 - 5 * value1 + 4 * value2 - value3;
double coefficient3 = -value0 + 3 * value1 - 3 * value2 + value3;
value = (coefficient3 * offset * offset * offset + coefficient2
* offset * offset + coefficient1 * offset + coefficient0) / 2;
}
return value;
}
/**
* Pad the bounding box with extra space for the overlapping pixels
*
* @param tileMatrix
* tile matrix
* @param boundingBox
* bounding box
* @param overlap
* overlapping pixels
* @return padded bounding box
*/
protected BoundingBox padBoundingBox(TileMatrix tileMatrix,
BoundingBox boundingBox, int overlap) {
double lonPixelPadding = tileMatrix.getPixelXSize() * overlap;
double latPixelPadding = tileMatrix.getPixelYSize() * overlap;
BoundingBox paddedBoundingBox = new BoundingBox(
boundingBox.getMinLongitude() - lonPixelPadding,
boundingBox.getMinLatitude() - latPixelPadding,
boundingBox.getMaxLongitude() + lonPixelPadding,
boundingBox.getMaxLatitude() + latPixelPadding);
return paddedBoundingBox;
}
/**
* Get the pixel value as an "unsigned short" at the coordinate from the
* "unsigned short" pixel values
*
* @param pixelValues
* "unsigned short" pixel values
* @param width
* image width
* @param x
* x coordinate
* @param y
* y coordinate
* @return "unsigned short" pixel value
*/
public short getPixelValue(short[] pixelValues, int width, int x, int y) {
return pixelValues[(y * width) + x];
}
/**
* Get the pixel value as a 16 bit unsigned value as an integer
*
* @param pixelValues
* "unsigned short" pixel values
* @param width
* image width
* @param x
* x coordinate
* @param y
* y coordinate
* @return unsigned int pixel value
*/
public int getUnsignedPixelValue(short[] pixelValues, int width, int x,
int y) {
short pixelValue = getPixelValue(pixelValues, width, x, y);
int unsignedPixelValue = getUnsignedPixelValue(pixelValue);
return unsignedPixelValue;
}
/**
* Get the pixel value as a 16 bit unsigned value at the coordinate from the
* 16 bit unsigned pixel values
*
* @param unsignedPixelValues
* unsigned int pixel values
* @param width
* image width
* @param x
* x coordinate
* @param y
* y coordinate
* @return 16 bit unsigned pixel value
*/
public int getUnsignedPixelValue(int[] unsignedPixelValues, int width,
int x, int y) {
return unsignedPixelValues[(y * width) + x];
}
/**
* Get the unsigned pixel value. The value saved as an "unsigned short" in
* the short is returned as an integer which stores the positive 16 bit
* value
*
* @param pixelValue
* "unsigned short" pixel value
* @return unsigned 16 bit pixel value as an integer
*/
public int getUnsignedPixelValue(short pixelValue) {
return pixelValue & 0xffff;
}
/**
* Get the "unsigned short" value from the unsigned 16 bit integer pixel
* value
*
* @param unsignedPixelValue
* unsigned 16 bit integer pixel value
* @return "unsigned short" pixel value
*/
public short getPixelValue(int unsignedPixelValue) {
return (short) unsignedPixelValue;
}
/**
* Get the unsigned pixel values. The values saved as "unsigned shorts" in
* the short array is returned as an integer which stores the positive 16
* bit value
*
* @param pixelValues
* pixel values as "unsigned shorts"
* @return unsigned 16 bit pixel values as an integer array
*/
public int[] getUnsignedPixelValues(short[] pixelValues) {
int[] unsignedValues = new int[pixelValues.length];
for (int i = 0; i < pixelValues.length; i++) {
unsignedValues[i] = getUnsignedPixelValue(pixelValues[i]);
}
return unsignedValues;
}
/**
* Get the coverage data value for the "unsigned short" pixel value
*
* @param griddedTile
* gridded tile
* @param pixelValue
* pixel value as an unsigned short
* @return coverage data value
*/
public Double getValue(GriddedTile griddedTile, short pixelValue) {
int unsignedPixelValue = getUnsignedPixelValue(pixelValue);
Double value = getValue(griddedTile, unsignedPixelValue);
return value;
}
/**
* Get the coverage data value for the unsigned short pixel value
*
* @param griddedTile
* gridded tile
* @param unsignedPixelValue
* pixel value as an unsigned 16 bit integer
* @return coverage data value
*/
public Double getValue(GriddedTile griddedTile, int unsignedPixelValue) {
Double value = null;
if (!isDataNull(unsignedPixelValue)) {
value = pixelValueToValue(griddedTile, new Double(
unsignedPixelValue));
}
return value;
}
/**
* Convert integer coverage typed pixel value to a coverage data value
* through scales and offsets
*
* @param griddedTile
* gridded tile
* @param pixelValue
* pixel value
* @return coverage data value
*/
private Double pixelValueToValue(GriddedTile griddedTile, Double pixelValue) {
Double value = pixelValue;
if (griddedCoverage != null
&& griddedCoverage.getDataType() == GriddedCoverageDataType.INTEGER) {
if (griddedTile != null) {
value *= griddedTile.getScale();
value += griddedTile.getOffset();
}
value *= griddedCoverage.getScale();
value += griddedCoverage.getOffset();
}
return value;
}
/**
* Get the coverage data values from the "unsigned short" pixel values
*
* @param griddedTile
* gridded tile
* @param pixelValues
* pixel values as "unsigned shorts"
* @return coverage data values
*/
public Double[] getValues(GriddedTile griddedTile, short[] pixelValues) {
Double[] values = new Double[pixelValues.length];
for (int i = 0; i < pixelValues.length; i++) {
values[i] = getValue(griddedTile, pixelValues[i]);
}
return values;
}
/**
* Get the coverage data values from the "unsigned short" pixel values
*
* @param griddedTile
* gridded tile
* @param unsignedPixelValues
* pixel values as 16 bit integers
* @return coverage data values
*/
public Double[] getValues(GriddedTile griddedTile, int[] unsignedPixelValues) {
Double[] values = new Double[unsignedPixelValues.length];
for (int i = 0; i < unsignedPixelValues.length; i++) {
values[i] = getValue(griddedTile, unsignedPixelValues[i]);
}
return values;
}
/**
* Create the coverage data tile table with metadata
*
* @param geoPackage
* GeoPackage
* @param tableName
* table name
* @param contentsBoundingBox
* contents bounding box
* @param contentsSrsId
* contents srs id
* @param tileMatrixSetBoundingBox
* tile matrix set bounding box
* @param tileMatrixSetSrsId
* tile matrix set srs id
* @return tile matrix set
*/
public static TileMatrixSet createTileTableWithMetadata(
GeoPackageCore geoPackage, String tableName,
BoundingBox contentsBoundingBox, long contentsSrsId,
BoundingBox tileMatrixSetBoundingBox, long tileMatrixSetSrsId) {
TileMatrixSet tileMatrixSet = geoPackage.createTileTableWithMetadata(
ContentsDataType.GRIDDED_COVERAGE, tableName,
contentsBoundingBox, contentsSrsId, tileMatrixSetBoundingBox,
tileMatrixSetSrsId);
return tileMatrixSet;
}
/**
* Get the unsigned 16 bit integer pixel value of the coverage data value
*
* @param griddedTile
* gridded tile
* @param value
* coverage data value
* @return 16 bit integer pixel value
*/
public int getUnsignedPixelValue(GriddedTile griddedTile, Double value) {
int unsignedPixelValue = 0;
if (value == null) {
if (griddedCoverage != null) {
unsignedPixelValue = griddedCoverage.getDataNull().intValue();
}
} else {
double pixelValue = valueToPixelValue(griddedTile, value);
unsignedPixelValue = (int) Math.round(pixelValue);
}
return unsignedPixelValue;
}
/**
* Convert integer coverage typed coverage data value to a pixel value
* through offsets and scales
*
* @param griddedTile
* gridded tile
* @param value
* coverage data value
* @return pixel value
*/
private double valueToPixelValue(GriddedTile griddedTile, double value) {
double pixelValue = value;
if (griddedCoverage != null
&& griddedCoverage.getDataType() == GriddedCoverageDataType.INTEGER) {
pixelValue -= griddedCoverage.getOffset();
pixelValue /= griddedCoverage.getScale();
if (griddedTile != null) {
pixelValue -= griddedTile.getOffset();
pixelValue /= griddedTile.getScale();
}
}
return pixelValue;
}
/**
* Get the "unsigned short" pixel value of the coverage data value
*
* @param griddedTile
* gridded tile
* @param value
* coverage data value
* @return "unsigned short" pixel value
*/
public short getPixelValue(GriddedTile griddedTile, Double value) {
int unsignedPixelValue = getUnsignedPixelValue(griddedTile, value);
short pixelValue = getPixelValue(unsignedPixelValue);
return pixelValue;
}
/**
* Get the pixel value at the coordinate from the pixel values
*
* @param pixelValues
* pixel values
* @param width
* image width
* @param x
* x coordinate
* @param y
* y coordinate
* @return pixel value
*/
public float getPixelValue(float[] pixelValues, int width, int x, int y) {
return pixelValues[(y * width) + x];
}
/**
* Get the coverage data value for the pixel value
*
* @param griddedTile
* gridded tile
* @param pixelValue
* pixel value
* @return coverage data value
*/
public Double getValue(GriddedTile griddedTile, float pixelValue) {
Double value = null;
if (!isDataNull(pixelValue)) {
value = pixelValueToValue(griddedTile, new Double(pixelValue));
}
return value;
}
/**
* Get the coverage data values from the pixel values
*
* @param griddedTile
* gridded tile
* @param pixelValues
* pixel values
* @return coverage data values
*/
public Double[] getValues(GriddedTile griddedTile, float[] pixelValues) {
Double[] values = new Double[pixelValues.length];
for (int i = 0; i < pixelValues.length; i++) {
values[i] = getValue(griddedTile, pixelValues[i]);
}
return values;
}
/**
* Get the pixel value of the coverage data value
*
* @param griddedTile
* gridded tile
* @param value
* coverage data value
* @return pixel value
*/
public float getFloatPixelValue(GriddedTile griddedTile, Double value) {
double pixel = 0;
if (value == null) {
if (griddedCoverage != null) {
pixel = griddedCoverage.getDataNull();
}
} else {
pixel = valueToPixelValue(griddedTile, value);
}
float pixelValue = (float) pixel;
return pixelValue;
}
/**
* Get the coverage data value at the coordinate
*
* @param latitude
* latitude
* @param longitude
* longitude
* @return coverage data value
*/
public Double getValue(double latitude, double longitude) {
CoverageDataRequest request = new CoverageDataRequest(latitude,
longitude);
CoverageDataResults values = getValues(request, 1, 1);
Double value = null;
if (values != null) {
value = values.getValues()[0][0];
}
return value;
}
/**
* Get the coverage data values within the bounding box
*
* @param requestBoundingBox
* request bounding box
* @return coverage data results
*/
public CoverageDataResults getValues(BoundingBox requestBoundingBox) {
CoverageDataRequest request = new CoverageDataRequest(
requestBoundingBox);
CoverageDataResults values = getValues(request);
return values;
}
/**
* Get the coverage data values within the bounding box with the requested
* width and height result size
*
* @param requestBoundingBox
* request bounding box
* @param width
* coverage data request width
* @param height
* coverage data request height
* @return coverage data results
*/
public CoverageDataResults getValues(BoundingBox requestBoundingBox,
Integer width, Integer height) {
CoverageDataRequest request = new CoverageDataRequest(
requestBoundingBox);
CoverageDataResults values = getValues(request, width, height);
return values;
}
/**
* Get the requested coverage data values
*
* @param request
* coverage data request
* @return coverage data results
*/
public CoverageDataResults getValues(CoverageDataRequest request) {
CoverageDataResults values = getValues(request, width, height);
return values;
}
/**
* Get the unbounded coverage data values within the bounding box. Unbounded
* results retrieves and returns each coverage data pixel. The results size
* equals the width and height of all matching pixels.
*
* @param requestBoundingBox
* request bounding box
* @return coverage data results
*/
public CoverageDataResults getValuesUnbounded(BoundingBox requestBoundingBox) {
CoverageDataRequest request = new CoverageDataRequest(
requestBoundingBox);
return getValuesUnbounded(request);
}
/**
* Get the bilinear interpolation coverage data value
*
* @param griddedTile
* gridded tile
* @param image
* image
* @param leftLastColumns
* last columns in the tile to the left
* @param topLeftRows
* last rows of the tile to the top left
* @param topRows
* last rows of the tile to the top
* @param y
* y coordinate
* @param x
* x coordinate
* @param widthRatio
* width source over destination ratio
* @param heightRatio
* height source over destination ratio
* @param destTop
* destination top most pixel
* @param destLeft
* destination left most pixel
* @param srcTop
* source top most pixel
* @param srcLeft
* source left most pixel
* @return bilinear coverage data value
*/
protected Double getBilinearInterpolationValue(GriddedTile griddedTile,
TImage image, Double[][] leftLastColumns, Double[][] topLeftRows,
Double[][] topRows, int y, int x, float widthRatio,
float heightRatio, float destTop, float destLeft, float srcTop,
float srcLeft) {
// Determine which source pixel to use
float xSource = getXSource(x, destLeft, srcLeft, widthRatio);
float ySource = getYSource(y, destTop, srcTop, heightRatio);
CoverageDataSourcePixel sourcePixelX = getXSourceMinAndMax(xSource);
CoverageDataSourcePixel sourcePixelY = getYSourceMinAndMax(ySource);
Double[][] values = new Double[2][2];
populateValues(griddedTile, image, leftLastColumns, topLeftRows,
topRows, sourcePixelX, sourcePixelY, values);
Double value = null;
if (values != null) {
value = getBilinearInterpolationValue(sourcePixelX, sourcePixelY,
values);
}
return value;
}
/**
* Get the bicubic interpolation coverage data value
*
* @param griddedTile
* gridded tile
* @param image
* image
* @param leftLastColumns
* last columns in the tile to the left
* @param topLeftRows
* last rows of the tile to the top left
* @param topRows
* last rows of the tile to the top
* @param y
* y coordinate
* @param x
* x coordinate
* @param widthRatio
* width source over destination ratio
* @param heightRatio
* height source over destination ratio
* @param destTop
* destination top most pixel
* @param destLeft
* destination left most pixel
* @param srcTop
* source top most pixel
* @param srcLeft
* source left most pixel
* @return bicubic coverage data value
*/
protected Double getBicubicInterpolationValue(GriddedTile griddedTile,
TImage image, Double[][] leftLastColumns, Double[][] topLeftRows,
Double[][] topRows, int y, int x, float widthRatio,
float heightRatio, float destTop, float destLeft, float srcTop,
float srcLeft) {
// Determine which source pixel to use
float xSource = getXSource(x, destLeft, srcLeft, widthRatio);
float ySource = getYSource(y, destTop, srcTop, heightRatio);
CoverageDataSourcePixel sourcePixelX = getXSourceMinAndMax(xSource);
sourcePixelX.setMin(sourcePixelX.getMin() - 1);
sourcePixelX.setMax(sourcePixelX.getMax() + 1);
CoverageDataSourcePixel sourcePixelY = getYSourceMinAndMax(ySource);
sourcePixelY.setMin(sourcePixelY.getMin() - 1);
sourcePixelY.setMax(sourcePixelY.getMax() + 1);
Double[][] values = new Double[4][4];
populateValues(griddedTile, image, leftLastColumns, topLeftRows,
topRows, sourcePixelX, sourcePixelY, values);
Double value = null;
if (values != null) {
value = getBicubicInterpolationValue(values, sourcePixelX,
sourcePixelY);
}
return value;
}
/**
* Populate the coverage data values
*
* @param griddedTile
* gridded tile
* @param image
* image
* @param leftLastColumns
* last columns in the tile to the left
* @param topLeftRows
* last rows of the tile to the top left
* @param topRows
* last rows of the tile to the top
* @param pixelX
* source x pixel
* @param pixelY
* source y pixel
* @param values
* values to populate
*/
private void populateValues(GriddedTile griddedTile, TImage image,
Double[][] leftLastColumns, Double[][] topLeftRows,
Double[][] topRows, CoverageDataSourcePixel pixelX,
CoverageDataSourcePixel pixelY, Double[][] values) {
populateValues(griddedTile, image, leftLastColumns, topLeftRows,
topRows, pixelX.getMin(), pixelX.getMax(), pixelY.getMin(),
pixelY.getMax(), values);
}
/**
* Populate the coverage data values
*
* @param griddedTile
* gridded tile
* @param image
* image
* @param leftLastColumns
* last columns in the tile to the left
* @param topLeftRows
* last rows of the tile to the top left
* @param topRows
* last rows of the tile to the top
* @param minX
* min x coordinate
* @param maxX
* max x coordinate
* @param minY
* min y coordinate
* @param maxY
* max y coordinate
* @param values
* values to populate
*/
private void populateValues(GriddedTile griddedTile, TImage image,
Double[][] leftLastColumns, Double[][] topLeftRows,
Double[][] topRows, int minX, int maxX, int minY, int maxY,
Double[][] values) {
for (int yLocation = maxY; values != null && yLocation >= minY; yLocation
for (int xLocation = maxX; xLocation >= minX; xLocation
Double value = getValueOverBorders(griddedTile, image,
leftLastColumns, topLeftRows, topRows, xLocation,
yLocation);
if (value == null) {
values = null;
break;
} else {
values[yLocation - minY][xLocation - minX] = value;
}
}
}
}
/**
* Get the nearest neighbor coverage data value
*
* @param griddedTile
* gridded tile
* @param image
* image
* @param leftLastColumns
* last columns in the tile to the left
* @param topLeftRows
* last rows of the tile to the top left
* @param topRows
* last rows of the tile to the top
* @param y
* y coordinate
* @param x
* x coordinate
* @param widthRatio
* width source over destination ratio
* @param heightRatio
* height source over destination ratio
* @param destTop
* destination top most pixel
* @param destLeft
* destination left most pixel
* @param srcTop
* source top most pixel
* @param srcLeft
* source left most pixel
* @return nearest neighbor coverage data value
*/
protected Double getNearestNeighborValue(GriddedTile griddedTile,
TImage image, Double[][] leftLastColumns, Double[][] topLeftRows,
Double[][] topRows, int y, int x, float widthRatio,
float heightRatio, float destTop, float destLeft, float srcTop,
float srcLeft) {
// Determine which source pixel to use
float xSource = getXSource(x, destLeft, srcLeft, widthRatio);
float ySource = getYSource(y, destTop, srcTop, heightRatio);
// Get the closest nearest neighbors
List<int[]> nearestNeighbors = getNearestNeighbors(xSource, ySource);
// Get the coverage data value from the source pixel nearest neighbors
// until one is found
Double value = null;
for (int[] nearestNeighbor : nearestNeighbors) {
value = getValueOverBorders(griddedTile, image, leftLastColumns,
topLeftRows, topRows, nearestNeighbor[0],
nearestNeighbor[1]);
if (value != null) {
break;
}
}
return value;
}
/**
* Get the coverage data value from the coordinate location. If the
* coordinate crosses the left, top, or top left tile, attempts to get the
* coverage data value from previously processed border coverage data
* values.
*
* @param griddedTile
* gridded tile
* @param image
* image
* @param leftLastColumns
* last columns in the tile to the left
* @param topLeftRows
* last rows of the tile to the top left
* @param topRows
* last rows of the tile to the top
* @param y
* x coordinate
* @param y
* y coordinate
* @return coverage data value
*/
private Double getValueOverBorders(GriddedTile griddedTile, TImage image,
Double[][] leftLastColumns, Double[][] topLeftRows,
Double[][] topRows, int x, int y) {
Double value = null;
// Only handle locations in the current tile, to the left, top left, or
// top tiles. Tiles are processed sorted by rows and columns, so values
// to the top right, right, or any below tiles will be handled later if
// those tiles exist
if (x < image.getWidth() && y < image.getHeight()) {
if (x >= 0 && y >= 0) {
value = getValue(griddedTile, image, x, y);
} else if (x < 0 && y < 0) {
// Try to get the coverage data value from the top left tile
// values
if (topLeftRows != null) {
int row = (-1 * y) - 1;
if (row < topLeftRows.length) {
int column = x + topLeftRows[row].length;
if (column >= 0) {
value = topLeftRows[row][column];
}
}
}
} else if (x < 0) {
// Try to get the coverage data value from the left tile values
if (leftLastColumns != null) {
int column = (-1 * x) - 1;
if (column < leftLastColumns.length) {
int row = y;
if (row < leftLastColumns[column].length) {
value = leftLastColumns[column][row];
}
}
}
} else {
// Try to get the coverage data value from the top tile values
if (topRows != null) {
int row = (-1 * y) - 1;
if (row < topRows.length) {
int column = x;
if (column < topRows[row].length) {
value = topRows[row][column];
}
}
}
}
}
return value;
}
}
|
package cn.pengh.helper;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gson.Gson;
import cn.pengh.annotation.ExceptField;
import cn.pengh.library.Log;
import cn.pengh.util.CurrencyUtil;
import cn.pengh.util.DateUtil;
import cn.pengh.util.StringUtil;
public class ClazzHelper {
public static final String REGX_GET_METHOD = "^(get|is)(\\w+)";
public static final String REGX_GET_FIELD_TYPE = "(class\\s+?)?(java.lang.)?(java.util.(concurrent.atomic.)?)?";
public static boolean isLog4j2 = true;
private static <T>void thisOut(T obj){
if (isLog4j2)
Log.info(obj);
else
System.out.println(obj);
}
public static <T>void printByOut(T obj){
isLog4j2 = false;
print(obj);
isLog4j2 = true;
}
public static <T>void print(T obj){
print(obj,false);
}
public static <T>void print(T obj, boolean isGson) {
if (obj == null) {
thisOut("
return;
}
if (obj instanceof Map) {
printMap((Map<?,?>)obj);
return;
} else if (obj instanceof Collection) {
printCollection((Collection<?>) obj);
return;
}
//json
if (isGson)
thisOut("print as json: "+new Gson().toJson(obj,obj.getClass()));
thisOut("
printRecursive(obj, obj.getClass(),new HashSet<String>());
thisOut("
}
private static <T>void printRecursive(T obj,Class<?> clazz,HashSet<String> fields){
printInternal(obj, clazz, fields);
if (clazz.getSuperclass() != null && !clazz.getSuperclass().getName().equals("java.lang.Object")) {
thisOut("===================== print super --> "+clazz.getSuperclass().getName());
printRecursive(obj,clazz.getSuperclass(),fields);
}
}
private static <T>void printInternal(T obj,Class<?> clazz,HashSet<String> fields){
String methodName = null,fieldName = null,typeName = null;
for(Method m : clazz.getDeclaredMethods()) {
methodName = m.getName();
if (!methodName.matches(REGX_GET_METHOD))
continue;
if (m.getParameterTypes() != null && m.getParameterTypes().length > 0)
continue;
fieldName = getFieldNameByMethod(methodName);
typeName = getFieldTypeByMethod(m);
try {
m.setAccessible(true);//thisOut(fields+fieldName);
Object v = fields.contains(fieldName) ? "@override" : m.invoke(obj);
pInternal(typeName, fieldName, v);
fields.add(fieldName);
new MFVT(m,v);
} catch (Exception e) {
//e.printStackTrace();
thisOut("ERROR method.invoke(obj), missing arguments: "+fieldName);
pInternal(typeName, fieldName,null);
} finally {
m.setAccessible(false);
}
}
}
public static <T>List<MFVT> MV(T obj){
List<MFVT> mvs = new ArrayList<MFVT>();
if (obj == null)
return mvs;
MVRecursive(obj, obj.getClass(),mvs,new HashSet<String>());
return mvs;
}
private static <T>void MVRecursive(T obj,Class<?> clazz,List<MFVT> mvs,HashSet<String> fields){
MVInternal(obj, clazz, mvs, fields);
if (clazz.getSuperclass() != null && !clazz.getSuperclass().getName().equals("java.lang.Object")) {
MVRecursive(obj,clazz.getSuperclass(),mvs,fields);
}
}
private static <T>void MVInternal(T obj,Class<?> clazz,List<MFVT> mvs,HashSet<String> fields){
String methodName = null,fieldName = null;
for(Method m : clazz.getDeclaredMethods()) {
methodName = m.getName();
if (!methodName.matches(REGX_GET_METHOD))
continue;
if (m.getParameterTypes() != null && m.getParameterTypes().length > 0)
continue;
fieldName = getFieldNameByMethod(methodName);
try {
m.setAccessible(true);//thisOut(fields+fieldName);
Object v = "@override";
if (!fields.contains(fieldName)) {
v = m.invoke(obj);
mvs.add(new MFVT(m,v));
}
fields.add(fieldName);
} catch (Exception e) {
e.printStackTrace();
} finally {
m.setAccessible(false);
}
}
}
public static class MFVT{
private String fieldName;
private String methodName;
private Object value;
private Type type;
public MFVT(Method method,Object value) {
this.methodName = method.getName();
this.fieldName = getFieldNameByMethod(methodName);
type = method.getGenericReturnType();
this.value = value;
}
public String getMethodName() {
return methodName;
}
public String getFieldName() {
return fieldName;
}
public Object getValue() {
return value;
}
public Type getType() {
return type;
}
public Class<?> getTypeClass() {
try {
return Class.forName(type.toString().replaceAll("class", "").trim());
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
public String toShow() {
return "[type] "+getTypeClass().getName()+
" \t-->[key] "+fieldName+
" \t-->[value] "+value;
}
}
private static <T>void pInternal(String typeName,String fieldName,Object value){
String str = "[type] "+typeName+
" \t-->[key] "+fieldName+
" \t-->[value] "+value;
thisOut(str);
}
/*private static <T>void pInternal(T obj,Field f){
String str = "[type] "+f.getType().getName().replace("java.lang.", "").replace("java.util.", "")+
" \t-->[key] "+f.getName()+
" \t-->[value] "+getObjVal(obj,f);
thisOut(str);
}*/
//getFileNamefileName
public static String getFieldNameByMethod(String methodName){
return StringUtil.toLowCaptureName(methodName.replaceAll(REGX_GET_METHOD, "$2"));
}
public static String getFieldTypeByMethod(Method method){
return method.getGenericReturnType().toString().trim().replaceAll(REGX_GET_FIELD_TYPE, "");
}
//getFileNamefileName
public static String getFieldTypeByMethod(Class<?> clazz,String methodName){
//get
methodName = methodName.matches(REGX_GET_METHOD) ? methodName : "get"+StringUtil.toCaptureName(methodName);
return getFieldTypeByMethod(getMethodByName(clazz, methodName));
}
public static Method getMethodByName(Class<?> clazz,String methodName){
for (Method method : getAllMethods(clazz)) {
if (methodName.equals(method.getName()))
return method;
}
return null;
}
public static Field getFieldByName(Class<?> clazz,String fieldName){
for (Field field : getAllFields(clazz)) {
if (fieldName.equals(field.getName()))
return field;
}
return null;
}
private static void printMap(Map<?,?> map) {
for (Entry<?, ?> e : map.entrySet()) {
thisOut("===========[map-key] "+e.getKey()+" \t
print(e.getValue());
thisOut("===========[map-key] "+e.getKey()+" \t
}
}
private static void printCollection(Collection<?> list){
for (Object obj : list) {
thisOut("===========[collection-value] ===========start");
print(obj);
thisOut("===========[collection-value] ===========end");
}
}
/**
*
* @param obj
* @param f
* @return
*/
public static <T> String getObjVal(T obj,Field f) {
String v = "";
try {
f.setAccessible(true);
v = f.get(obj).toString();
f.setAccessible(false);
} catch (Exception e) {
//e.printStackTrace();
v = "null";
}
return v;
}
public static <T> String getObjVal(T obj,String f) {
return getObjVal(obj, getFieldByName(obj.getClass(), getFieldNameByMethod(f)));
}
public static <T> void setRecentUpdate(T obj,String usr) {
try {
Class<?> clazz = obj.getClass();
Method mut = getClassMethod(clazz,"setRecUpdTs");
mut.invoke(obj, new Date());
Method murs = getClassMethod(clazz,"setRecUpdUsr");
Method murg = getClassMethod(clazz,"getRecUpdUsr");
if (murg.invoke(obj) == null || murg.invoke(obj).toString().equals("")) {
murs.invoke(obj, usr == null ? "cron system" : usr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static<T> Method getClassMethod(Class <T> aClazz, String Name) {
Method[] declaredMethods = aClazz.getDeclaredMethods();
for (Method m : declaredMethods) {
if (m.getName().equals(Name))
return m;
}
Class<?> superclass = aClazz.getSuperclass();
if (superclass != null)
return getClassMethod(superclass, Name);
return null;
}
public static Field getClazzFieldByNm(Class<?> clazz,String name) {
Field f = null;
try {
f = clazz.getDeclaredField(name);
} catch (Exception e) {
//e.printStackTrace();
}
if (f == null && clazz.getSuperclass() != null){
f = getClazzFieldByNm(clazz.getSuperclass(),name);
} else {
return f;
}
return f;
}
public static List<String> getValByStrArr(Object bean,String[] validate,String index){
List<String> str = new LinkedList<String>();
if (index != null)
str.add(index);
for (int i = 0; i < validate.length; i++) {
String k = validate[i];//System.out.println("k:"+k);
if (k.equals(""))
continue;
try {
Field fg = getClazzFieldByNm(bean.getClass(), k);
if (fg == null)
continue;
fg.setAccessible(true);
if (fg.get(bean) == null)
continue;
String t = fg.getType().getName();
String v = "";
if (t.equals("java.lang.Double"))
v = new BigDecimal(((Double)fg.get(bean))).divide(new BigDecimal(1.0),2,BigDecimal.ROUND_HALF_UP).toString();
else if (t.equals("int"))
v = Integer.toString((Integer)fg.get(bean));
else if (t.equals("java.util.Date"))
v = DateUtil.Date2Str((Date)fg.get(bean), DateUtil.LOCALE_FORMAT);
else
v = fg.get(bean).toString();
//add...
str.add(v);
fg.setAccessible(false);
} catch (Exception e) {
e.printStackTrace();
}
}
return str;
}
public static List<String> getValByStrExp(Object bean,String[] exp,String index){
List<String> str = new LinkedList<String>();
if (index != null)
str.add(index);
//bean
for (Field f : bean.getClass().getDeclaredFields()) {
String k = f.getName();System.out.println("k:"+k);
String t = f.getType().getName();
String v = "";
if (!Arrays.asList(exp).contains(k)) {
try {
Field fg = bean.getClass().getDeclaredField(k);
fg.setAccessible(true);
if (fg.get(bean) == null)
continue;
if (t.equals("java.lang.Double") || t.equals("double"))
v = new BigDecimal(((Double)fg.get(bean))).divide(new BigDecimal(1.0),2,BigDecimal.ROUND_HALF_UP).toString();
else if (t.equals("int") || t.equals("java.lang.Integer"))
v = Integer.toString((Integer)fg.get(bean));
else if (t.equals("long") || t.equals("java.lang.Long"))
v = Long.toString((Long)fg.get(bean));
else
v = fg.get(bean).toString();
//add...
str.add(v);
fg.setAccessible(false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return str;
}
public static List<String> getValByStrExpNotNull(Object bean,String[] exp,String index){
List<String> str = new LinkedList<String>();
if (index != null)
str.add(index);
//bean
for (Field f : bean.getClass().getDeclaredFields()) {
String k = f.getName();System.out.println("k:"+k);
String t = f.getType().getName();
String v = "";
if (!Arrays.asList(exp).contains(k)) {
try {
Field fg = bean.getClass().getDeclaredField(k);
fg.setAccessible(true);
if (fg.get(bean) == null) {
str.add("");
fg.setAccessible(false);
continue;
}
if (t.equals("java.lang.Double") || t.equals("double"))
v = new BigDecimal(((Double)fg.get(bean))).divide(new BigDecimal(1.0),2,BigDecimal.ROUND_HALF_UP).toString();
else if (t.equals("int") || t.equals("java.lang.Integer"))
v = Integer.toString((Integer)fg.get(bean));
else if (t.equals("long") || t.equals("java.lang.Long"))
v = Long.toString((Long)fg.get(bean));
else
v = fg.get(bean).toString();
//add...
str.add(v);
fg.setAccessible(false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return str;
}
public static HashSet<Method> getAllMethods(Class<?> clazz){
HashSet<Method> methods = new HashSet<Method>();
getAllMethodsRecursive(clazz, methods);
return methods;
}
public static String getSelectStr(Class<?> clazz){
return getSelectStr(clazz, "");
}
public static String getSelectStr(Class<?> clazz,String tblPre,String... except){
StringBuilder sb = new StringBuilder();
HashSet<String> fields = ClazzHelper.getAllFieldStrings(clazz);
List<String> exceptList = (except == null || except.length == 0 ) ? new ArrayList<String>() : Arrays.asList(except);
for (String f : fields) {
if (exceptList.contains(f)) {
continue;
}
sb.append(tblPre).append(StringUtil.toUnderlineCase(f)).append(",");
}
return sb.toString().replaceAll("^(.*),$", "$1");
}
public static HashSet<String> getAllFieldStrings(Class<?> clazz){
HashSet<String> fields = new HashSet<String>();
for (Field f : getAllFields(clazz)) {
fields.add(f.getName());
}
return fields;
}
public static HashSet<Field> getAllFields(Class<?> clazz){
HashSet<Field> fields = new HashSet<Field>();
getAllFieldsRecursive(clazz, fields);
return fields;
}
private static void getAllFieldsRecursive(Class<?> clazz,HashSet<Field> fields){
//getDeclaredFields
for (Field f : clazz.getDeclaredFields()) {
if (f.isSynthetic() || f.isEnumConstant())
continue;
// static
if (Modifier.isStatic(f.getModifiers()))
continue;
//@cn.pengh.annotation.ExceptField
if (f.getAnnotation(ExceptField.class) != null)
continue;
fields.add(f);
}
//getMethod
/*for (Method m : clazz.getDeclaredMethods()) {
if (!m.getName().startsWith("get"))
continue;
fields.add(new Field);
}*/
Class<?> superclass = clazz.getSuperclass();
if (superclass != null){
getAllFieldsRecursive(superclass, fields);
}
}
private static void getAllMethodsRecursive(Class<?> clazz,HashSet<Method> methods){
//getDeclaredFields
for (Method m : clazz.getDeclaredMethods()) {
if (m.isSynthetic() )
continue;
// static
if (Modifier.isStatic(m.getModifiers()))
continue;
//@cn.pengh.annotation.ExceptField
if (m.getAnnotation(ExceptField.class) != null)
continue;
methods.add(m);
}
Class<?> superclass = clazz.getSuperclass();
if (superclass != null){
getAllMethodsRecursive(superclass, methods);
}
}
public static String[] getNullFieldArr(Object obj){
List<String> nullFields = getNullFields(obj);
return nullFields.toArray(new String[nullFields.size()]);
}
public static List<String> getNullFields(Object obj){
List<String> nullFields = new ArrayList<String>();
getNullFieldsIntenal(obj, obj.getClass(), nullFields);
return nullFields;
}
public static void getNullFieldsIntenal(Object obj, Class<?> clazz, List<String> nullFields){
for (Field f : clazz.getDeclaredFields()) {
try {
f.setAccessible(true);
if(f.get(obj) == null)
nullFields.add(f.getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
f.setAccessible(false);
}
}
Class<?> superclass = clazz.getSuperclass();
if (superclass != null){
getNullFieldsIntenal(obj, superclass, nullFields);
}
}
public static void setBatchValue(Object obj,Class<?> clazz,Map<String,Object> map){
List<String> list = new ArrayList<String>();
for (Entry<String,Object> e : map.entrySet()) {
list.add(e.getKey());
}
setBatchValueRecursive(obj, clazz, list, map);
for (String k : list) {
try {
if (getClazzFieldByNm(clazz, k) == null) {
Log.debug("Field == null,"+k);
setStringFieldValue(k, (String)map.get(k), obj);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void setBatchValueRecursive(Object obj,Class<?> clazz,List<String> list,Map<String,Object> map){
setBatchValueRecursiveIntenal(obj, clazz, list, map);
Class<?> superclass = clazz.getSuperclass();
if (superclass != null){
setBatchValueRecursive(obj, superclass, list, map);
}
}
private static void setBatchValueRecursiveIntenal(Object obj,Class<?> clazz,List<String> list,Map<String,Object> map){
for (Field f : clazz.getDeclaredFields()){
String k = f.getName();
if (!list.contains(k)){
continue;
}
String t = f.getType().getName();
try {
if (f == null || "java.lang.String".equals(t)) {
setStringFieldValue(k, (String)map.get(k), obj);
} else {
setFieldValue(k, map.get(k), obj);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static <T> void setStringFieldValue(String k,String v,T obj){
String kf = k.substring(0,1).toUpperCase() + k.substring(1);
try {
Method m = obj.getClass().getMethod("set" + kf,String.class);
m.invoke(obj, v);
} catch (Exception e) {
e.printStackTrace();
}
}
public static <T> void setFieldValue(String f,Object v,T obj){
setFieldValue(getClazzFieldByNm(obj.getClass(), f), v, obj);
}
public static <T> void setFieldValue(Field f,Object v,T obj){
if (f == null)
return;
String t = f.getType().getName();
try {
f.setAccessible(true);
if ("java.lang.Byte".equals(t)){
v = CurrencyUtil.convert(v).byteValue();
} else if ("java.lang.Short".equals(t)){
v = CurrencyUtil.convert(v).shortValue();
} else if ("java.lang.Integer".equals(t)){
v = CurrencyUtil.convert(v).intValue();
} else if ("java.lang.Long".equals(t)){
v = CurrencyUtil.convert(v).longValue();
}
f.set(obj, v);
} catch (Exception e) {
e.printStackTrace();
} finally {
f.setAccessible(false);
}
}
public static void main(String[] args) {
//Log.debug(getSelectStr(Person.class));
//ClazzHelper.print(new Person("",8));
}
}
|
package com.github.chrox.kpvbooklet;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URI;
import java.util.Date;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import com.amazon.kindle.booklet.AbstractBooklet;
public class KPVBooklet extends AbstractBooklet {
//private static final PrintStream log = Log.INSTANCE;
private final String kpdfviewer = "/mnt/us/kindlepdfviewer/kpdf.sh";
private Process kpdfviewerProcess;
private CCAdapter request = CCAdapter.INSTANCE;
private static final PrintStream logger = Log.INSTANCE;
public KPVBooklet() {
log("I: KPVBooklet");
}
public void start(URI contentURI) {
log("I: start()");
String path = contentURI.getPath();
log("I: Opening " + path + " with kindlepdfviewer...");
String[] cmd = new String[] {kpdfviewer, path};
try {
kpdfviewerProcess = Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
log("E: " + e.toString());
}
Thread thread = new kpdfviewerWaitThread(path);
thread.start();
}
public void stop() {
log("I: stop()");
// Stop kpdfviewer
if (kpdfviewerProcess != null) {
try {
killQuitProcess(kpdfviewerProcess);
log("I: kpdf.sh process killed with return value " + kpdfviewerProcess.exitValue());
} catch (Exception e) {
log("E: " + e.toString());
}
}
}
private void killQuitProcess(Process process)
throws InterruptedException, IOException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
if (process.getClass().getName().equals("java.lang.UNIXProcess")) {
Class cl = process.getClass();
Field field = cl.getDeclaredField("pid");
field.setAccessible(true);
Object pidObject = field.get(process);
Runtime.getRuntime().exec("kill -QUIT " + pidObject).waitFor();
} else {
throw new IllegalArgumentException("Needs to be a UNIXProcess");
}
}
/** This thread waits for kpdfviewer to finish and then sends
* a BACKWARD lipc event.
*/
class kpdfviewerWaitThread extends Thread {
private String content_path = "";
public kpdfviewerWaitThread(String path) {
content_path = path;
}
public void run() {
try {
// wait for kpdfviewer to finish
kpdfviewerProcess.waitFor();
} catch (InterruptedException e) {
log("E: " + e.toString());
}
// update content catlog after kpdfviewer exits
updateCC(content_path, extractPercentFinished(content_path));
// kill all kpdfviewer process
try {
Runtime.getRuntime().exec("killall reader.lua");
} catch (IOException e) {
log("E: " + e.toString());
}
// sent go home lipc event after kpdfviewer exits
try {
Runtime.getRuntime().exec("lipc-set-prop com.lab126.appmgrd start app://com.lab126.booklet.home");
} catch (IOException e) {
log("E: " + e.toString());
}
}
}
/**
* Update lastAccess and displayTag fields in ContentCatlog
* @param file path
*/
private void updateCC(String path, float percentFinished) {
long lastAccess = new Date().getTime() / 1000L;
int dot = path.lastIndexOf('.');
String tag = (dot == -1) ? "" : path.substring(dot+1).toUpperCase();
path = JSONObject.escape(path);
String json_query = "{\"filter\":{\"Equals\":{\"value\":\"" + path + "\",\"path\":\"location\"}},\"type\":\"QueryRequest\",\"maxResults\":1,\"sortOrder\":[{\"order\":\"descending\",\"path\":\"lastAccess\"},{\"order\":\"ascending\",\"path\":\"titles[0].collation\"}],\"startIndex\":0,\"id\":1,\"resultType\":\"fast\"}";
JSONObject json = request.perform("query", json_query);
JSONArray values = (JSONArray) json.get("values");
JSONObject value =(JSONObject) values.get(0);
String uuid = (String) value.get("uuid");
String json_change = "{\"commands\":[{\"update\":{\"uuid\":\"" + uuid + "\",\"lastAccess\":" + lastAccess + ",\"percentFinished\":" + percentFinished + ",\"displayTags\":[\"" + tag + "\"]" + "}}],\"type\":\"ChangeRequest\",\"id\":1}";
request.perform("change", json_change);
log("I: UpdateCC:file:" + path + ",lastAccess:" + lastAccess + ",percentFinished:" + percentFinished);
}
/**
* Extract last_percent in document history file
* @param file path
*/
private float extractPercentFinished(String path) {
float percent_finished = 0.0f;
String history_dir = "/mnt/us/kindlepdfviewer/history/";
int slash = path.lastIndexOf('/');
String parentname = (slash == -1) ? "" : path.substring(0, slash+1);
String basename = (slash == -1) ? "" : path.substring(slash+1);
String histroypath = history_dir + "[" + parentname.replace('/','#') + "] " + basename + ".lua";
log("I: found history file: " + histroypath);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(histroypath)));
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf("[\"percent_finished\"]") > -1) {
log("I: found percent_finished line: " + line);
int equal = line.lastIndexOf('=');
int comma = line.lastIndexOf(',');
if (equal != -1 && comma != -1) {
String value = line.substring(equal+1, comma).trim();
percent_finished = Float.parseFloat(value) * 100;
}
}
}
br.close();
} catch (IOException e) {
log("E: " + e.toString());
}
return percent_finished;
}
private void log(String msg) {
logger.println(msg);
}
}
|
package org.catacombae.csjc;
import org.catacombae.csjc.structelements.Signedness;
import org.catacombae.csjc.structelements.Endianness;
import org.catacombae.csjc.structelements.IntegerFieldBits;
import org.catacombae.csjc.structelements.Dictionary;
import org.catacombae.csjc.structelements.FieldType;
import org.catacombae.csjc.structelements.IntegerFieldRepresentation;
public interface StructElements {
/** Shorthand constant. */
public static final Endianness BIG_ENDIAN = Endianness.BIG_ENDIAN;
/** Shorthand constant. */
public static final Endianness LITTLE_ENDIAN = Endianness.LITTLE_ENDIAN;
/** Shorthand constant. */
public static final Signedness SIGNED = Signedness.SIGNED;
/** Shorthand constant. */
public static final Signedness UNSIGNED = Signedness.UNSIGNED;
/** Shorthand constant. */
public static final FieldType BOOLEAN = FieldType.BOOLEAN;
/** Shorthand constant. */
public static final FieldType INTEGER = FieldType.INTEGER;
/** Shorthand constant. */
public static final FieldType BYTEARRAY = FieldType.BYTEARRAY;
/** Shorthand constant. */
public static final FieldType ASCIISTRING = FieldType.ASCIISTRING;
/** Shorthand constant. */
public static final FieldType CUSTOM_CHARSET_STRING = FieldType.CUSTOM_CHARSET_STRING;
/** Shorthand constant. */
public static final FieldType DATE = FieldType.DATE;
/** Shorthand constant. */
public static final IntegerFieldBits BITS_8 = IntegerFieldBits.BITS_8;
/** Shorthand constant. */
public static final IntegerFieldBits BITS_16 = IntegerFieldBits.BITS_16;
/** Shorthand constant. */
public static final IntegerFieldBits BITS_32 = IntegerFieldBits.BITS_32;
/** Shorthand constant. */
public static final IntegerFieldBits BITS_64 = IntegerFieldBits.BITS_64;
/** Shorthand constant. */
public static final IntegerFieldRepresentation DECIMAL = IntegerFieldRepresentation.DECIMAL;
/** Shorthand constant. */
public static final IntegerFieldRepresentation HEXADECIMAL = IntegerFieldRepresentation.HEXADECIMAL;
/** Shorthand constant. */
public static final IntegerFieldRepresentation OCTAL = IntegerFieldRepresentation.OCTAL;
/** Shorthand constant. */
public static final IntegerFieldRepresentation BINARY = IntegerFieldRepresentation.BINARY;
/**
* Shorthand subclass, so the user doesn't have to import DictionaryBuilder in every
* implementation of StructElements.
*/
public class DictionaryBuilder extends org.catacombae.csjc.structelements.DictionaryBuilder {
/**
* @see org.catacombae.csjc.structelements.DictionaryBuilder#DictionaryBuilder(java.lang.String)
*/
public DictionaryBuilder(String typeName) {
super(typeName);
}
/**
* @see org.catacombae.csjc.structelements.DictionaryBuilder#DictionaryBuilder(java.lang.String, java.lang.String)
*/
public DictionaryBuilder(String typeName, String typeDescription) {
super(typeName, typeDescription);
}
}
/**
* Returns a dictionary of the elements of this data structure. The keys in
* the dictionary should be the respective variable names, and the elements
* should provide access to all the fields of the data structure.
*
* @return a dictionary of the elements of this data structure.
*/
public Dictionary getStructElements();
}
|
package net.mabako.steamgifts.fragments;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import net.mabako.steamgifts.R;
import net.mabako.steamgifts.activities.CommonActivity;
import net.mabako.steamgifts.adapters.EndlessAdapter;
/**
* Searchable Discussion or Giveaway List fragment.
*/
public abstract class SearchableListFragment<AdapterType extends EndlessAdapter> extends ListFragment<AdapterType> {
private static final String TAG = SearchableListFragment.class.getSimpleName();
/**
* What are we searching for?
*/
protected String searchQuery = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
setHasOptionsMenu(true);
return view;
}
@Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.main_menu, menu);
final MenuItem searchMenu = menu.findItem(R.id.search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchMenu);
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
query = query.trim();
startSearch(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
// Stop searching on clicking 'back'
MenuItemCompat.setOnActionExpandListener(searchMenu, new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
stopSearch();
return true;
}
});
if (searchQuery != null) {
MenuItemCompat.expandActionView(searchMenu);
searchView.setQuery(searchQuery, false);
searchView.clearFocus();
}
}
protected void startSearch(String query) {
Log.d(TAG, "Starting Search for " + query);
AppCompatActivity activity = ((AppCompatActivity) getActivity());
FragmentManager fragmentManager = activity.getSupportFragmentManager();
if (searchQuery != null)
stopSearch();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, newSearchingInstance(query), CommonActivity.FRAGMENT_TAG);
transaction.addToBackStack(TAG);
transaction.commit();
}
public void stopSearch() {
if (searchQuery != null) {
Log.d(TAG, "Stopping Search");
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.popBackStack(TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
/**
* Creates a new instance of the fragment used exclusively for searching items.
*
* @param query
* @return
*/
public abstract Fragment newSearchingInstance(String query);
}
|
package com.github.miachm.SODS.com.github.miachm.SODS.input;
import com.github.miachm.SODS.com.github.miachm.SODS.exceptions.NotAnOds;
import com.github.miachm.SODS.com.github.miachm.SODS.exceptions.OperationNotSupported;
import com.github.miachm.SODS.com.github.miachm.SODS.spreadsheet.Sheet;
import com.github.miachm.SODS.com.github.miachm.SODS.spreadsheet.SpreadSheet;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Set;
public class OdsReader {
private static final String CORRECT_MIMETYPE = "application/vnd.oasis.opendocument.spreadsheet";
private static final String MANIFEST_PATH = "META-INF/manifest.xml";
private String main_path;
private SpreadSheet spread;
private Map<String,byte[]> files;
private OdsReader(InputStream in,SpreadSheet spread) throws IOException {
/* TODO This code if for ods files in zip. But we could have XML-ONLY FILES */
this.spread = spread;
Uncompressor uncompressor = new Uncompressor(in);
files = uncompressor.getFiles();
checkMimeType(files);
byte[] manifest = getManifest(files);
readManifest(manifest);
readContent();
}
static public void load(InputStream in,SpreadSheet spread) throws IOException {
OdsReader reader = new OdsReader(in,spread);
}
private void checkMimeType(Map<String,byte[]> map){
byte[] mimetype = map.get("mimetype");
if (mimetype == null)
throw new NotAnOds("This file doesn't contain a mimetype");
String mimetype_string = new String(mimetype);
if (!mimetype_string.equals(CORRECT_MIMETYPE))
throw new NotAnOds("This file doesn't look like an ODS file. Mimetype: " + mimetype_string);
}
private byte[] getManifest(Map<String,byte[]> map){
byte[] manifest = map.get(MANIFEST_PATH);
if (manifest == null) {
throw new NotAnOds("Error loading, it doesn't like an ODS file");
}
return manifest;
}
private void readManifest(byte[] manifest) {
try{
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(manifest));
Element root = doc.getDocumentElement();
if (!root.getNodeName().equals("manifest:manifest")) {
throw new NotAnOds("The signature of the manifest is not valid. Is it an ODS file?");
}
NodeList files = doc.getElementsByTagName("manifest:file-entry");
iterateFilesEntryManifest(files);
}catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void iterateFilesEntryManifest(NodeList files){
for (int i = 0;i < files.getLength();i++) {
NamedNodeMap children = files.item(i).getAttributes();
boolean main_path = false;
String path = null;
for (int j = 0;j <children.getLength();j++) {
Node child = children.item(j);
if (child.getNodeName().equals("manifest:encryption-data")) {
throw new OperationNotSupported("This file has encription technology that it's not supported" +
"by this library");
}
else if (child.getNodeName().equals("manifest:full-path")){
path = child.getNodeValue();
}
else if (child.getNodeName().equals("manifest:media-type")){
System.out.println("Manifest media type: " + child.getNodeValue());
main_path = (child.getNodeValue().equals(CORRECT_MIMETYPE));
}
}
if (main_path)
this.main_path = path;
}
}
private void readContent() {
Set<String> names = files.keySet();
for (String name : names){
if (sameFolder(name,main_path)){
processContent(files.get(name));
}
}
}
private boolean sameFolder(String name, String main_path) {
if (!name.startsWith(main_path))
return false;
return name.indexOf('/',main_path.length()+1) < 0;
}
private void processContent(byte[] bytes) {
try{
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(bytes));
Element root = doc.getDocumentElement();
NodeList files = doc.getElementsByTagName("office:body");
if (files != null)
iterateFilesEntries(files);
}catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void iterateFilesEntries(NodeList files) {
for (int i = 0;i < files.getLength();i++){
Node node = files.item(i);
if (node.getNodeName().equals("office:spreadsheet")){
NodeList list = node.getChildNodes();
for (int j = 0;j < list.getLength();j++){
node = list.item(j);
if (node.getNodeName().equals("table:table")){
NamedNodeMap atributes = node.getAttributes();
String name = atributes.getNamedItem("table:name").getNodeValue();
Sheet sheet = new Sheet(name);
NodeList new_list = node.getChildNodes();
for (int k = 0;k < new_list.getLength();k++){
Node n = new_list.item(k);
if (n.getNodeName().equals("table:table-column")){
sheet.insertColumnAfter(sheet.getMaxColumns());
}
else if (n.getNodeName().equals("table:table-row")){
sheet.insertRowAfter(sheet.getMaxRows());
}
}
}
}
}
}
}
}
|
package com.github.forhacks.evolve2048;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Game extends JPanel {
// grid[row][column]
int[][] grid;
private Random random = new Random();
boolean game;
int score = 0;
Game() {
initGame();
}
void initGame() {
grid = new int[4][4];
addTile();
addTile();
score = 0;
game = true;
}
private boolean canMove() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if ((i < 3 && grid[i][j] == grid[i+1][j]) || (j < 3 && grid[i][j] == grid[i][j+1])) {
return true;
}
if (grid[i][j] == 0) {
return true;
}
}
}
return false;
}
boolean canMove(int direction) {
if (direction == 0) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
if ((grid[i][j] == 0 && grid[i+1][j] != 0) || (grid[i][j] == grid[i+1][j])) {
return true;
}
}
}
} else if (direction == 1) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
if ((grid[i][j] == 0 && grid[i][j+1] != 0) || (grid[i][j] == grid[i][j+1])) {
return true;
}
}
}
} else if (direction == 2) {
for (int i = 3; i >= 1; i
for (int j = 0; j < 4; j++) {
if ((grid[i][j] == 0 && grid[i-1][j] != 0) || (grid[i][j] == grid[i-1][j])) {
return true;
}
}
}
} else if (direction == 3) {
for (int i = 0; i < 4; i++) {
for (int j = 3; j >= 1; j
if ((grid[i][j] == 0 && grid[i][j-1] != 0) || (grid[i][j] == grid[i][j-1])) {
return true;
}
}
}
}
return false;
}
int maxTile() {
int max = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
max = Integer.max(grid[i][j], max);
}
}
return max;
}
public int emptyTileCount() {
int count = 0;
for (int[] row : grid) {
for (int tile : row) {
if (tile == 0) {
count++;
}
}
}
return count;
}
private void addTile() {
List<int[]> available = new ArrayList<>();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (grid[i][j] == 0) {
available.add(new int[] {i, j});
}
}
}
int[] add = available.get(random.nextInt(available.size()));
int number = 2;
float chance = random.nextFloat();
if (chance <= 0.10f) {
number = 4;
}
grid[add[0]][add[1]] = number;
}
// 0: up; 1: right; 2: down; 3: left
void move(int direction) {
int tot = 0;
if (direction == 0) {
for (int i = 0; i < 4; i++) {
for (int j = 1; j < 4; j++) {
int moves = 0;
while (j - moves - 1 >= 0 && grid[j - moves - 1][i] == 0) {
moves++;
}
int value = grid[j][i];
grid[j][i] = 0;
grid[j - moves][i] = value;
if (j - moves - 1 >= 0 && grid[j - moves - 1][i] == grid[j - moves][i]) {
grid[j - moves - 1][i] *= 2;
grid[j - moves][i] = 0;
score += grid[j - moves - 1][i];
moves++;
}
tot += moves;
}
}
} else if (direction == 1) {
for (int i = 0; i < 4; i++) {
for (int j = 1; j < 4; j++) {
int moves = 0;
while (j - moves - 1 >= 0 && grid[i][j - moves - 1] == 0) {
moves++;
}
int value = grid[i][j];
grid[i][j] = 0;
grid[i][j - moves] = value;
if (j - moves - 1 >= 0 && grid[i][j - moves - 1] == grid[i][j - moves]) {
grid[i][j - moves - 1] *= 2;
grid[i][j - moves] = 0;
score += grid[j - moves - 1][i];
moves++;
}
tot += moves;
}
}
} else if (direction == 2) {
for (int i = 0; i < 4; i++) {
for (int j = 2; j >= 0; j
int moves = 0;
while (j + moves + 1 <= 3 && grid[j + moves + 1][i] == 0) {
moves++;
}
int value = grid[j][i];
grid[j][i] = 0;
grid[j + moves][i] = value;
if (j + moves + 1 <= 3 && grid[j + moves + 1][i] == grid[j + moves][i]) {
grid[j + moves + 1][i] *= 2;
grid[j + moves][i] = 0;
score += grid[j + moves + 1][i];
moves++;
}
tot += moves;
}
}
} else if (direction == 3) {
for (int i = 0; i < 4; i++) {
for (int j = 2; j >= 0; j
int moves = 0;
while (j + moves + 1 <= 3 && grid[i][j + moves + 1] == 0) {
moves++;
}
int value = grid[i][j];
grid[i][j] = 0;
grid[i][j + moves] = value;
if (j + moves + 1 <= 3 && grid[i][j + moves + 1] == grid[i][j + moves]) {
grid[i][j + moves + 1] *= 2;
grid[i][j + moves] = 0;
score += grid[j + moves + 1][i];
moves++;
}
tot += moves;
}
}
}
if (tot > 0) {
addTile();
}
if (!canMove()) {
game = false;
}
}
}
|
package net.nemerosa.ontrack.jenkins.trigger;
import hudson.model.Result;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
public class TriggerDefinition {
/**
* Success condition for previous result.
*/
public static final String SUCCESS = "SUCCESS";
/**
* Ontrack project name
*/
private final String project;
/**
* Ontrack branch name
*/
private final String branch;
/**
* The Ontrack promotion level to take into account.
*/
private final String promotion;
/**
* Name of the parameter which contains the name of the build
*/
private final String parameterName;
/**
* Minimum result of previous run
*/
private final String minimumResult;
@DataBoundConstructor
public TriggerDefinition(String project, String branch, String promotion, String parameterName, String minimumResult) {
this.project = project;
this.branch = branch;
this.promotion = promotion;
this.parameterName = StringUtils.isBlank(parameterName) ? "VERSION" : parameterName;
// First we parse the given String 'minimumResult'
// Hence 'minimumResult' will be
// - 'SUCCESS' if the input is null or an empty String
// - 'FAILURE' if the input contains an invalid value
this.minimumResult = (minimumResult != null && !minimumResult.isEmpty()) ? Result.fromString(minimumResult).toString() : SUCCESS;
}
public String getProject() {
return project;
}
public String getBranch() {
return branch;
}
public String getPromotion() {
return promotion;
}
public String getParameterName() {
return parameterName;
}
public String getMinimumResult() {
return minimumResult;
}
@Override
public String toString() {
return "TriggerDefinition{" +
"project='" + project + '\'' +
", branch='" + branch + '\'' +
", promotion='" + promotion + '\'' +
", parameterName='" + parameterName + '\'' +
", minimumResult='" + minimumResult + '\'' +
'}';
}
TriggerResult noResult() {
return new TriggerResult(parameterName, null, null);
}
TriggerResult noPrevious(String newValue) {
return new TriggerResult(parameterName, null, newValue);
}
TriggerResult withPrevious(String previousValue, String lastVersion) {
return new TriggerResult(parameterName, previousValue, lastVersion);
}
}
|
package burai.app.project.viewer.result;
import java.io.IOException;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import burai.app.QEFXMain;
import burai.app.project.QEFXProjectController;
import burai.app.project.editor.result.QEFXResultFileTree;
import burai.project.Project;
public class ResultAction {
private Project project;
private QEFXProjectController controller;
private QEFXResultExplorer explorer;
private QEFXResultFileTree fileTree;
public ResultAction(Project project, QEFXProjectController controller) {
if (project == null) {
throw new IllegalArgumentException("project is null.");
}
if (controller == null) {
throw new IllegalArgumentException("controller is null.");
}
this.project = project;
this.controller = controller;
this.explorer = null;
this.fileTree = null;
}
public QEFXProjectController getController() {
return this.controller;
}
public void showResult() {
if (this.project.getDirectoryPath() == null) {
this.showErrorDialog();
return;
}
if (this.explorer == null || this.fileTree == null) {
this.initializeResult();
return;
}
this.controller.setResultExplorerMode();
}
private void showErrorDialog() {
Alert alert = new Alert(AlertType.ERROR);
QEFXMain.initializeDialogOwner(alert);
alert.setHeaderText("This project has not been saved nor run.");
alert.showAndWait();
}
private void initializeResult() {
this.explorer = new QEFXResultExplorer(this.controller, this.project);
try {
this.fileTree = new QEFXResultFileTree(this.controller, this.project);
this.fileTree.setResultExplorer(this.explorer);
} catch (IOException e) {
this.fileTree = null;
e.printStackTrace();
}
if (this.explorer != null && this.fileTree != null) {
this.controller.setResultExplorerMode(controller2 -> {
this.explorer.reload();
this.fileTree.reload();
});
this.controller.clearStackedsOnViewerPane();
Node explorerNode = this.explorer.getNode();
if (explorerNode != null) {
this.controller.stackOnViewerPane(explorerNode);
}
Node fileTreeNode = this.fileTree.getNode();
if (fileTreeNode != null) {
this.controller.setEditorPane(fileTreeNode);
}
}
}
}
|
/*
* generated by Xtext
*/
package org.yakindu.sct.generator.genmodel.formatting;
import org.eclipse.xtext.Group;
import org.eclipse.xtext.Keyword;
import org.eclipse.xtext.formatting.impl.AbstractDeclarativeFormatter;
import org.eclipse.xtext.formatting.impl.FormattingConfig;
import org.eclipse.xtext.util.Pair;
import org.yakindu.sct.generator.genmodel.services.SGenGrammarAccess;
public class SGenFormatter extends AbstractDeclarativeFormatter {
@Override
protected void configureFormatting(FormattingConfig c) {
SGenGrammarAccess g = (SGenGrammarAccess) getGrammarAccess();
// It's usually a good idea to activate the following three statements.
// They will add and preserve newlines around comments
c.setLinewrap(0, 1, 2).before(g.getSL_COMMENTRule());
c.setLinewrap(0, 1, 2).before(g.getML_COMMENTRule());
c.setLinewrap(0, 1, 1).after(g.getML_COMMENTRule());
// Find elements which declare their body in curly brackets.
// - Increment Indentation for the body.
// - Line wrap before opening and after closing element
for (Pair<Keyword, Keyword> pair : grammar.findKeywordPairs("{", "}")) {
c.setIndentation(pair.getFirst(), pair.getSecond());
c.setLinewrap().after(pair.getFirst());
c.setLinewrap().around(pair.getSecond());
Keyword openingBrace = pair.getFirst();
Group containingGroup = (Group) openingBrace.eContainer();
c.setLinewrap(1, 2, 2).before(containingGroup);
c.setLinewrap(1, 1, 2).after(containingGroup);
}
c.setLinewrap().around(g.getFeatureConfigurationRule());
c.setLinewrap().around(g.getFeatureParameterValueRule());
c.setNoLinewrap().after(
g.getGeneratorEntryAccess().getStatechartKeyword_0());
c.setNoLinewrap().after(
g.getFeatureConfigurationAccess().getFeatureKeyword_1());
c.setNoLinewrap().before(
g.getGeneratorModelAccess().getGeneratorModelKeyword_0());
}
}
|
package nl.jqno.equalsverifier.internal.checkers;
import java.util.function.Predicate;
import nl.jqno.equalsverifier.Warning;
import nl.jqno.equalsverifier.internal.checkers.fieldchecks.*;
import nl.jqno.equalsverifier.internal.prefabvalues.PrefabValues;
import nl.jqno.equalsverifier.internal.prefabvalues.TypeTag;
import nl.jqno.equalsverifier.internal.reflection.ClassAccessor;
import nl.jqno.equalsverifier.internal.reflection.FieldAccessor;
import nl.jqno.equalsverifier.internal.reflection.annotations.AnnotationCache;
import nl.jqno.equalsverifier.internal.reflection.annotations.SupportedAnnotations;
import nl.jqno.equalsverifier.internal.util.Configuration;
public class FieldsChecker<T> implements Checker {
private final Configuration<T> config;
private final ArrayFieldCheck<T> arrayFieldCheck;
private final FloatAndDoubleFieldCheck floatAndDoubleFieldCheck;
private final MutableStateFieldCheck mutableStateFieldCheck;
private final ReflexivityFieldCheck<T> reflexivityFieldCheck;
private final SignificantFieldCheck<T> significantFieldCheck;
private final SignificantFieldCheck<T> skippingSignificantFieldCheck;
private final SymmetryFieldCheck symmetryFieldCheck;
private final TransientFieldsCheck<T> transientFieldsCheck;
private final TransitivityFieldCheck transitivityFieldCheck;
public FieldsChecker(Configuration<T> config) {
this.config = config;
PrefabValues prefabValues = config.getPrefabValues();
TypeTag typeTag = config.getTypeTag();
String cachedHashCodeFieldName =
config.getCachedHashCodeInitializer().getCachedHashCodeFieldName();
Predicate<FieldAccessor> isCachedHashCodeField =
a -> a.getFieldName().equals(cachedHashCodeFieldName);
this.arrayFieldCheck = new ArrayFieldCheck<>(config.getCachedHashCodeInitializer());
this.floatAndDoubleFieldCheck = new FloatAndDoubleFieldCheck();
this.mutableStateFieldCheck =
new MutableStateFieldCheck(prefabValues, typeTag, isCachedHashCodeField);
this.reflexivityFieldCheck = new ReflexivityFieldCheck<>(config);
this.significantFieldCheck =
new SignificantFieldCheck<>(config, isCachedHashCodeField, false);
this.skippingSignificantFieldCheck =
new SignificantFieldCheck<>(config, isCachedHashCodeField, true);
this.symmetryFieldCheck = new SymmetryFieldCheck(prefabValues, typeTag);
this.transientFieldsCheck = new TransientFieldsCheck<>(config);
this.transitivityFieldCheck = new TransitivityFieldCheck(prefabValues, typeTag);
}
@Override
public void check() {
ClassAccessor<T> classAccessor = config.getClassAccessor();
FieldInspector<T> inspector = new FieldInspector<>(classAccessor, config.getTypeTag());
if (!classAccessor.isEqualsInheritedFromObject()) {
inspector.check(arrayFieldCheck);
inspector.check(floatAndDoubleFieldCheck);
inspector.check(reflexivityFieldCheck);
}
if (!ignoreMutability(config.getType())) {
inspector.check(mutableStateFieldCheck);
}
if (!config.getWarningsToSuppress().contains(Warning.TRANSIENT_FIELDS)) {
inspector.check(transientFieldsCheck);
}
inspector.check(significantFieldCheck);
inspector.check(symmetryFieldCheck);
inspector.check(transitivityFieldCheck);
if (!config.getWarningsToSuppress().contains(Warning.NULL_FIELDS)) {
inspector.checkWithNull(
config.getNonnullFields(),
config.getAnnotationCache(),
skippingSignificantFieldCheck);
}
}
private boolean ignoreMutability(Class<?> type) {
AnnotationCache cache = config.getAnnotationCache();
return config.getWarningsToSuppress().contains(Warning.NONFINAL_FIELDS)
|| cache.hasClassAnnotation(type, SupportedAnnotations.IMMUTABLE)
|| cache.hasClassAnnotation(type, SupportedAnnotations.ENTITY);
}
}
|
package fredboat;
import com.google.common.base.CharMatcher;
import com.mashape.unirest.http.exceptions.UnirestException;
import fredboat.audio.player.PlayerLimitManager;
import fredboat.command.admin.SentryDsnCommand;
import fredboat.shared.constant.DistributionEnum;
import fredboat.util.DiscordUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
public class Config {
private static final Logger log = LoggerFactory.getLogger(Config.class);
public static Config CONFIG = null;
public static String DEFAULT_PREFIX = ";";
public static int HIKARI_TIMEOUT_MILLISECONDS = 1000;
private final DistributionEnum distribution;
private final String botToken;
private final String jdbcUrl;
private final int hikariPoolSize;
private int numShards;
private String malUser;
private String malPassword;
private String imgurClientId;
private List<String> googleKeys = new ArrayList<>();
private final String[] lavaplayerNodes;
private final boolean lavaplayerNodesEnabled;
private String carbonKey;
private String spotifyId;
private String spotifySecret;
private String prefix = DEFAULT_PREFIX;
private boolean restServerEnabled = true;
private List<String> adminIds = new ArrayList<>();
private boolean useAutoBlacklist = false;
private String game = "";
private List<LavalinkHost> lavalinkHosts = new ArrayList<>();
private String sentryDsn;
//testing related stuff
private String testBotToken;
private String testChannelId;
// SSH tunnel stuff
private final boolean useSshTunnel;
private final String sshHost; //Eg localhost:22
private final String sshUser; //Eg fredboat
private final String sshPrivateKeyFile;
private final int forwardToPort; //port where the remote database is listening, postgres default: 5432
//AudioManager Stuff
private Boolean youtubeAudio;
private Boolean soundcloudAudio;
private Boolean bandcampAudio;
private Boolean twitchAudio;
private Boolean vimeoAudio;
private Boolean mixerAudio;
private Boolean spotifyAudio;
private Boolean httpAudio;
@SuppressWarnings("unchecked")
public Config(File credentialsFile, File configFile) {
try {
Yaml yaml = new Yaml();
String credsFileStr = FileUtils.readFileToString(credentialsFile, "UTF-8");
String configFileStr = FileUtils.readFileToString(configFile, "UTF-8");
//remove those pesky tab characters so a potential json file is YAML conform
credsFileStr = cleanTabs(credsFileStr, "credentials.yaml");
configFileStr = cleanTabs(configFileStr, "config.yaml");
Map<String, Object> creds;
Map<String, Object> config;
try {
creds = (Map<String, Object>) yaml.load(credsFileStr);
config = (Map<String, Object>) yaml.load(configFileStr);
} catch (YAMLException e) {
log.error("Could not parse the credentials and/or config yaml files! There are probably misformatted. " +
"Try using an online yaml format checker.");
throw e;
}
//avoid null values, rather change them to empty strings
creds.keySet().forEach((String key) -> creds.putIfAbsent(key, ""));
config.keySet().forEach((String key) -> config.putIfAbsent(key, ""));
//create the sentry appender as early as possible
sentryDsn = (String) creds.getOrDefault("sentryDsn", "");
if (!sentryDsn.isEmpty()) {
SentryDsnCommand.turnOn(sentryDsn);
} else {
SentryDsnCommand.turnOff();
}
// Determine distribution
if ((boolean) config.getOrDefault("patron", false)) {
distribution = DistributionEnum.PATRON;
} else if ((boolean) config.getOrDefault("development", false)) {//Determine distribution
distribution = DistributionEnum.DEVELOPMENT;
} else {
distribution = DistributionEnum.MUSIC;
}
log.info("Determined distribution: " + distribution);
prefix = (String) config.getOrDefault("prefix", prefix);
restServerEnabled = (boolean) config.getOrDefault("restServerEnabled", restServerEnabled);
Object admins = config.get("admins");
if (admins instanceof List) {
((List) admins).forEach((Object str) -> adminIds.add(str + ""));
} else if (admins instanceof String) {
adminIds.add(admins + "");
}
useAutoBlacklist = (boolean) config.getOrDefault("useAutoBlacklist", useAutoBlacklist);
game = (String) config.getOrDefault("game", "");
log.info("Using prefix: " + prefix);
malUser = (String) creds.getOrDefault("malUser", "");
malPassword = (String) creds.getOrDefault("malPassword", "");
carbonKey = (String) creds.getOrDefault("carbonKey", "");
Map<String, String> token = (Map) creds.get("token");
if (token != null) {
botToken = String.valueOf(System.getenv("TOKEN"));
} else botToken = "";
if (botToken == null || botToken.isEmpty()) {
throw new RuntimeException("No discord bot token provided for the started distribution " + distribution
+ "\nMake sure to put a " + distribution.getId() + " token in your credentials file.");
}
spotifyId = (String) creds.getOrDefault("spotifyId", "");
spotifySecret = (String) creds.getOrDefault("spotifySecret", "");
jdbcUrl = (String) creds.getOrDefault("jdbcUrl", "");
Object gkeys = creds.get("googleServerKeys");
if (gkeys instanceof List) {
((List) gkeys).forEach((Object str) -> googleKeys.add((String) str));
} else if (gkeys instanceof String) {
googleKeys.add((String) gkeys);
} else {
log.warn("No google API keys found. Some commands may not work, check the documentation.");
}
List<String> nodesArray = (List) creds.get("lavaplayerNodes");
if(nodesArray != null) {
lavaplayerNodesEnabled = true;
log.info("Using lavaplayer nodes");
lavaplayerNodes = nodesArray.toArray(new String[nodesArray.size()]);
} else {
lavaplayerNodesEnabled = false;
lavaplayerNodes = new String[0];
//log.info("Not using lavaplayer nodes. Audio playback will be processed locally.");
}
Map<String, String> linkNodes = (Map<String, String>) creds.get("lavalinkHosts");
if (linkNodes != null) {
linkNodes.forEach((s, s2) -> {
try {
lavalinkHosts.add(new LavalinkHost(new URI(s), s2));
log.info("Lavalink node added: " + new URI(s));
} catch (URISyntaxException e) {
throw new RuntimeException("Failed parsing URI", e);
}
});
}
if(getDistribution() == DistributionEnum.DEVELOPMENT) {
log.info("Development distribution; forcing 2 shards");
numShards = 2;
} else {
//this is the first request on start
//it sometimes fails cause network isn'T set up yet. wait 10 sec and try one more time in that case
try {
numShards = DiscordUtil.getRecommendedShardCount(getBotToken());
} catch (Exception e) {
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
//duh
}
numShards = DiscordUtil.getRecommendedShardCount(getBotToken());
}
log.info("Discord recommends " + numShards + " shard(s)");
}
//more database connections don't help with performance, so use a value based on available cores
if (jdbcUrl == null || "".equals(jdbcUrl) || distribution == DistributionEnum.DEVELOPMENT)
//more than one connection for the fallback sqlite db is problematic as there is currently (2017-04-16)
// no supported way in the custom driver and/or dialect to set lock timeouts
hikariPoolSize = 1;
else hikariPoolSize = Runtime.getRuntime().availableProcessors() * 2;
log.info("Hikari max pool size set to " + hikariPoolSize);
imgurClientId = (String) creds.getOrDefault("imgurClientId", "");
testBotToken = (String) creds.getOrDefault("testToken", "");
testChannelId = creds.getOrDefault("testChannelId", "") + "";
PlayerLimitManager.setLimit((Integer) config.getOrDefault("playerLimit", -1));
useSshTunnel = (boolean) creds.getOrDefault("useSshTunnel", false);
sshHost = (String) creds.getOrDefault("sshHost", "localhost:22");
sshUser = (String) creds.getOrDefault("sshUser", "fredboat");
sshPrivateKeyFile = (String) creds.getOrDefault("sshPrivateKeyFile", "database.ppk");
forwardToPort = (int) creds.getOrDefault("forwardToPort", 5432);
//Modularise audiomanagers; load from "config.yaml"
youtubeAudio = (Boolean) config.getOrDefault("enableYouTube", true);
soundcloudAudio = (Boolean) config.getOrDefault("enableSoundCloud", true);
bandcampAudio = (Boolean) config.getOrDefault("enableBandCamp", true);
twitchAudio = (Boolean) config.getOrDefault("enableTwitch", true);
vimeoAudio = (Boolean) config.getOrDefault("enableVimeo", true);
mixerAudio = (Boolean) config.getOrDefault("enableMixer", true);
spotifyAudio = (Boolean) config.getOrDefault("enableSpotify", true);
httpAudio = (Boolean) config.getOrDefault("enableHttp", false);
} catch (IOException | UnirestException e) {
throw new RuntimeException(e);
}
}
static void loadDefaultConfig() throws IOException {
Config.CONFIG = new Config(
loadConfigFile("credentials"),
loadConfigFile("config")
);
}
/**
* Makes sure the requested config file exists in the current format. Will attempt to migrate old formats to new ones
* old files will be renamed to filename.ext.old to preserve any data
*
* @param name relative name of a config file, without the file extension
* @return a handle on the requested file
*/
private static File loadConfigFile(String name) throws IOException {
String yamlPath = "./" + name + ".yaml";
String jsonPath = "./" + name + ".json";
File yamlFile = new File(yamlPath);
if (!yamlFile.exists() || yamlFile.isDirectory()) {
log.warn("Could not find file '" + yamlPath + "', looking for legacy '" + jsonPath + "' to rewrite");
File json = new File(jsonPath);
if (!json.exists() || json.isDirectory()) {
//file is missing
log.error("No " + name + " file is present. Bot cannot run without it. Check the documentation.");
throw new FileNotFoundException("Neither '" + yamlPath + "' nor '" + jsonPath + "' present");
} else {
//rewrite the json to yaml
Yaml yaml = new Yaml();
String fileStr = FileUtils.readFileToString(json, "UTF-8");
//remove tab character from json file to make it a valid YAML file
fileStr = cleanTabs(fileStr, name);
@SuppressWarnings("unchecked")
Map<String, Object> configFile = (Map) yaml.load(fileStr);
yaml.dump(configFile, new FileWriter(yamlFile));
Files.move(Paths.get(jsonPath), Paths.get(jsonPath + ".old"), REPLACE_EXISTING);
log.info("Migrated file '" + jsonPath + "' to '" + yamlPath + "'");
}
}
return yamlFile;
}
private static String cleanTabs(String content, String file) {
CharMatcher tab = CharMatcher.is('\t');
if (tab.matchesAnyOf(content)) {
log.warn("{} contains tab characters! Trying a fix-up.", file);
return tab.replaceFrom(content, " ");
} else {
return content;
}
}
public String getRandomGoogleKey() {
return getGoogleKeys().get((int) Math.floor(Math.random() * getGoogleKeys().size()));
}
public DistributionEnum getDistribution() {
return distribution;
}
public boolean isPatronDistribution() {
return distribution == DistributionEnum.PATRON;
}
public boolean isDevDistribution() {
return distribution == DistributionEnum.DEVELOPMENT;
}
public String getBotToken() {
return botToken;
}
public String getJdbcUrl() {
return jdbcUrl;
}
public int getHikariPoolSize() {
return hikariPoolSize;
}
public int getNumShards() {
return numShards;
}
public String getMalUser() {
return malUser;
}
public String getMalPassword() {
return malPassword;
}
public String getImgurClientId() {
return imgurClientId;
}
public List<String> getGoogleKeys() {
return googleKeys;
}
public String[] getLavaplayerNodes() {
return lavaplayerNodes;
}
public boolean isLavaplayerNodesEnabled() {
return lavaplayerNodesEnabled;
}
public String getCarbonKey() {
return carbonKey;
}
public String getSpotifyId() {
return spotifyId;
}
public String getSpotifySecret() {
return spotifySecret;
}
public String getPrefix() {
return prefix;
}
public boolean isRestServerEnabled() {
return restServerEnabled;
}
public List<String> getAdminIds() {
return adminIds;
}
public boolean useAutoBlacklist() {
return useAutoBlacklist;
}
public String getGame() {
if (game == null || game.isEmpty()) {
return "Say " + getPrefix() + "help";
} else {
return game;
}
}
public String getTestBotToken() {
return testBotToken;
}
public String getTestChannelId() {
return testChannelId;
}
public boolean isUseSshTunnel() {
return useSshTunnel;
}
public String getSshHost() {
return sshHost;
}
public String getSshUser() {
return sshUser;
}
public String getSshPrivateKeyFile() {
return sshPrivateKeyFile;
}
public int getForwardToPort() {
return forwardToPort;
}
public List<LavalinkHost> getLavalinkHosts() {
return lavalinkHosts;
}
public class LavalinkHost {
private final URI uri;
private final String password;
public LavalinkHost(URI uri, String password) {
this.uri = uri;
this.password = password;
}
public URI getUri() {
return uri;
}
public String getPassword() {
return password;
}
}
public boolean isYouTubeEnabled() {
return youtubeAudio;
}
public boolean isSoundCloudEnabled() {
return soundcloudAudio;
}
public boolean isBandCampEnabled() {
return bandcampAudio;
}
public boolean isTwitchEnabled() {
return twitchAudio;
}
public boolean isVimeoEnabled() {
return vimeoAudio;
}
public boolean isMixerEnabled() {
return mixerAudio;
}
public boolean isSpotifyEnabled() {
return spotifyAudio;
}
public boolean isHttpEnabled() {
return httpAudio;
}
}
|
package nom.bdezonia.zorbage.type.real.float128;
import java.math.BigDecimal;
import java.math.BigInteger;
import ch.obermuhlner.math.big.BigDecimalMath;
import nom.bdezonia.zorbage.algebra.Allocatable;
import nom.bdezonia.zorbage.algebra.Duplicatable;
import nom.bdezonia.zorbage.algebra.G;
import nom.bdezonia.zorbage.algebra.GetAsBigDecimal;
import nom.bdezonia.zorbage.algebra.GetAsBigDecimalArray;
import nom.bdezonia.zorbage.algebra.GetReal;
import nom.bdezonia.zorbage.algebra.Gettable;
import nom.bdezonia.zorbage.algebra.HighPrecRepresentation;
import nom.bdezonia.zorbage.algebra.NumberMember;
import nom.bdezonia.zorbage.algebra.SetFromBigDecimal;
import nom.bdezonia.zorbage.algebra.SetFromBigInteger;
import nom.bdezonia.zorbage.algebra.SetFromDouble;
import nom.bdezonia.zorbage.algebra.SetFromLong;
import nom.bdezonia.zorbage.algebra.SetReal;
import nom.bdezonia.zorbage.algebra.Settable;
import nom.bdezonia.zorbage.misc.BigDecimalUtils;
import nom.bdezonia.zorbage.misc.Hasher;
import nom.bdezonia.zorbage.sampling.IntegerIndex;
import nom.bdezonia.zorbage.storage.coder.ByteCoder;
import nom.bdezonia.zorbage.type.real.highprec.HighPrecisionMember;
import nom.bdezonia.zorbage.type.universal.OctonionRepresentation;
import nom.bdezonia.zorbage.type.universal.PrimitiveConversion;
import nom.bdezonia.zorbage.type.universal.PrimitiveRepresentation;
import nom.bdezonia.zorbage.type.universal.TensorOctonionRepresentation;
import nom.bdezonia.zorbage.type.universal.TensorStringRepresentation;
import nom.bdezonia.zorbage.type.universal.UniversalRepresentation;
/**
*
* @author Barry DeZonia
*
*/
public final class Float128Member
implements
NumberMember<Float128Member>,
ByteCoder,
Allocatable<Float128Member>, Duplicatable<Float128Member>,
Settable<Float128Member>, Gettable<Float128Member>,
UniversalRepresentation, PrimitiveConversion,
HighPrecRepresentation, SetReal<Float128Member>, GetReal<Float128Member>,
SetFromBigDecimal, SetFromBigInteger, SetFromDouble, SetFromLong,
GetAsBigDecimal, GetAsBigDecimalArray
{
BigDecimal num;
byte classification;
static final BigDecimal TWO = BigDecimal.valueOf(2);
static final BigDecimal MAX_NORMAL = TWO.pow(16383).multiply(TWO.subtract(TWO.pow(-112, Float128Algebra.CONTEXT)));
static final BigDecimal MIN_NORMAL = MAX_NORMAL.negate();
static final BigDecimal MAX_SUBNORMAL = TWO.pow(-16382, Float128Algebra.CONTEXT).multiply(BigDecimal.ONE.subtract(TWO.pow(-112, Float128Algebra.CONTEXT)));
static final BigDecimal MIN_SUBNORMAL = TWO.pow(-16382, Float128Algebra.CONTEXT).multiply(TWO.pow(-112, Float128Algebra.CONTEXT));
static final BigInteger FULL_RANGE = new BigInteger("10000000000000000000000000000",16);
static final BigDecimal FULL_RANGE_BD = new BigDecimal(FULL_RANGE);
static final BigInteger FULL_FRACTION = new BigInteger("ffffffffffffffffffffffffffff", 16);
static final byte NORMAL = 0;
static final byte POSZERO = 1;
static final byte NEGZERO = -1;
static final byte POSINF = 2;
static final byte NEGINF = -2;
static final byte NAN = 3;
public Float128Member() {
primitiveInit();
}
// Prefer this ctor over the BigDecimal based one since it can propagate
// nan, inf, etc.
public Float128Member(Float128Member other) {
set(other);
}
// Prefer the previous ctor over this one since this cannot represent
// nan, inf, etc.
public Float128Member(BigDecimal v) {
setV(v);
}
public Float128Member(String str) {
TensorStringRepresentation rep = new TensorStringRepresentation(str);
OctonionRepresentation val = rep.firstValue();
setV(val.r());
}
public Float128Member(BigInteger v) {
this(new BigDecimal(v));
}
public Float128Member(long v) {
this(BigDecimal.valueOf(v));
}
public Float128Member(double v) {
this(BigDecimal.valueOf(v));
}
@Override
public long dimension(int d) {
return 0;
}
@Override
public int numDimensions() {
return 0;
}
@Override
public void setR(Float128Member val) {
set(val);
}
@Override
public void getR(Float128Member val) {
get(val);
}
public BigDecimal v() {
if (classification == POSINF || classification == NEGINF || classification == NAN)
throw new java.lang.NumberFormatException("nan/posinf/neginf cannot be converted to big decimal");
return num;
}
public void setV(BigDecimal v) {
if (v == null)
throw new IllegalArgumentException("this class does not allow null values");
if (v.signum() == 0) {
setPosZero();
}
else {
setNormal(v);
clamp();
}
}
@Override
public BigDecimal getAsBigDecimal() {
return v();
}
@Override
public void setFromLong(long... vals) {
setV(BigDecimal.valueOf(vals[0]));
}
@Override
public void setFromDouble(double... vals) {
setV(BigDecimal.valueOf(vals[0]));
}
@Override
public void setFromBigInteger(BigInteger... vals) {
setV(new BigDecimal(vals[0]));
}
@Override
public void setFromBigDecimal(BigDecimal... vals) {
setV(vals[0]);
}
@Override
public void toHighPrec(HighPrecisionMember output) {
if (classification == POSINF || classification == NEGINF || classification == NAN)
throw new java.lang.NumberFormatException("nan/posinf/neginf cannot encode as a high precision decimal");
// can use num with classifications NORMAL, POSZERO, and NEGZERO because they are all accurate
output.setV(num);
}
@Override
public void fromHighPrec(HighPrecisionMember input) {
setV(input.v());
}
@Override
public PrimitiveRepresentation preferredRepresentation() {
return PrimitiveRepresentation.BIGDECIMAL;
}
@Override
public int componentCount() {
return 1;
}
@Override
public void primComponentSetByte(IntegerIndex index, int component, byte v) {
setV(BigDecimal.valueOf(v));
}
@Override
public void primComponentSetShort(IntegerIndex index, int component, short v) {
setV(BigDecimal.valueOf(v));
}
@Override
public void primComponentSetInt(IntegerIndex index, int component, int v) {
setV(BigDecimal.valueOf(v));
}
@Override
public void primComponentSetLong(IntegerIndex index, int component, long v) {
setV(BigDecimal.valueOf(v));
}
@Override
public void primComponentSetFloat(IntegerIndex index, int component, float v) {
setV(BigDecimal.valueOf(v));
}
@Override
public void primComponentSetDouble(IntegerIndex index, int component, double v) {
setV(BigDecimal.valueOf(v));
}
@Override
public void primComponentSetBigInteger(IntegerIndex index, int component, BigInteger v) {
setV(new BigDecimal(v));
}
@Override
public void primComponentSetBigDecimal(IntegerIndex index, int component, BigDecimal v) {
setV(v);
}
@Override
public void primComponentSetByteSafe(IntegerIndex index, int component, byte v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(BigDecimal.valueOf(v));
}
}
@Override
public void primComponentSetShortSafe(IntegerIndex index, int component, short v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(BigDecimal.valueOf(v));
}
}
@Override
public void primComponentSetIntSafe(IntegerIndex index, int component, int v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(BigDecimal.valueOf(v));
}
}
@Override
public void primComponentSetLongSafe(IntegerIndex index, int component, long v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(BigDecimal.valueOf(v));
}
}
@Override
public void primComponentSetFloatSafe(IntegerIndex index, int component, float v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(BigDecimal.valueOf(v));
}
}
@Override
public void primComponentSetDoubleSafe(IntegerIndex index, int component, double v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(BigDecimal.valueOf(v));
}
}
@Override
public void primComponentSetBigIntegerSafe(IntegerIndex index, int component, BigInteger v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v.signum() != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(new BigDecimal(v));
}
}
@Override
public void primComponentSetBigDecimalSafe(IntegerIndex index, int component, BigDecimal v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v.signum() != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(v);
}
}
@Override
public byte primComponentGetAsByte(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().byteValue();
return 0;
}
@Override
public short primComponentGetAsShort(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().shortValue();
return 0;
}
@Override
public int primComponentGetAsInt(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().intValue();
return 0;
}
@Override
public long primComponentGetAsLong(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().longValue();
return 0;
}
@Override
public float primComponentGetAsFloat(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().floatValue();
return 0;
}
@Override
public double primComponentGetAsDouble(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().doubleValue();
return 0;
}
@Override
public BigInteger primComponentGetAsBigInteger(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().toBigInteger();
return BigInteger.ZERO;
}
@Override
public BigDecimal primComponentGetAsBigDecimal(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v();
return BigDecimal.ZERO;
}
@Override
public byte primComponentGetAsByteSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return 0;
}
else {
return v().byteValue();
}
}
@Override
public short primComponentGetAsShortSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return 0;
}
else {
return v().shortValue();
}
}
@Override
public int primComponentGetAsIntSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return 0;
}
else {
return v().intValue();
}
}
@Override
public long primComponentGetAsLongSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return 0;
}
else {
return v().longValue();
}
}
@Override
public float primComponentGetAsFloatSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return 0;
}
else {
return v().floatValue();
}
}
@Override
public double primComponentGetAsDoubleSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return 0;
}
else {
return v().doubleValue();
}
}
@Override
public BigInteger primComponentGetAsBigIntegerSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return BigInteger.ZERO;
}
else {
return v().toBigInteger();
}
}
@Override
public BigDecimal primComponentGetAsBigDecimalSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return BigDecimal.ZERO;
}
else {
return v();
}
}
@Override
public void primitiveInit() {
setPosZero();
}
@Override
public void toRep(TensorOctonionRepresentation rep) {
rep.setValue(new OctonionRepresentation(v()));
}
@Override
public void fromRep(TensorOctonionRepresentation rep) {
setV(rep.getValue().r());
}
@Override
public void get(Float128Member other) {
other.num = this.num;
other.classification = this.classification;
}
@Override
public void set(Float128Member other) {
this.num = other.num;
this.classification = other.classification;
}
@Override
public Float128Member duplicate() {
return new Float128Member(this);
}
@Override
public Float128Member allocate() {
return new Float128Member();
}
@Override
public int byteCount() {
return 16;
}
@Override
public void fromByteArray(byte[] arr, int index) {
decode(arr, index);
}
@Override
public void toByteArray(byte[] arr, int index) {
encode(arr, index);
}
@Override
public void getV(Float128Member value) {
get(value);
}
@Override
public void setV(Float128Member value) {
set(value);
}
@Override
public int hashCode() {
int v = 1;
v = Hasher.PRIME * v + Hasher.hashCode(num);
v = Hasher.PRIME * v + Hasher.hashCode(classification);
return v;
}
@Override
public boolean equals(Object o) {
if (o instanceof Float128Member) {
return G.QUAD.isEqual().call(this, (Float128Member) o);
}
return false;
}
@Override
public String toString() {
switch (classification) {
case NORMAL:
return num.toString();
case POSZERO:
return "0";
case NEGZERO:
return "-0";
case POSINF:
return "Infinity";
case NEGINF:
return "-Infinity";
case NAN:
return "NaN";
default:
throw new IllegalArgumentException("unknown number classification "+classification);
}
}
public boolean isNormal() {
return classification == NORMAL;
}
public boolean isPosZero() {
return classification == POSZERO;
}
public boolean isNegZero() {
return classification == NEGZERO;
}
public boolean isPosInf() {
return classification == POSINF;
}
public boolean isNegInf() {
return classification == NEGINF;
}
public boolean isNan() {
return classification == NAN;
}
public boolean isFinite() {
return classification == NORMAL || classification == POSZERO || classification == NEGZERO;
}
public boolean isInfinite() {
return classification == POSINF || classification == NEGINF;
}
public boolean isZero() {
return classification == POSZERO || classification == NEGZERO;
}
public boolean isPositive() {
return classification == POSINF ||
(classification == NORMAL && num.signum() > 0);
}
public boolean isNegative() {
return classification == NEGINF ||
(classification == NORMAL && num.signum() < 0);
}
public boolean hasPositiveSign() {
return classification == POSZERO || isPositive();
}
public boolean hasNegativeSign() {
return classification == NEGZERO || isNegative();
}
// DO NOT MAKE THIS ONE PUBLIC: use num.setV(BigDecimal)
// because it does some data classification and clamping.
// If people started using this method arbitrarily they
// could violate the internal consistency of how the
// numbers are handled and bad numerical results could
// sneak in.
void setNormal(BigDecimal value) {
num = value;
classification = NORMAL;
}
public void setPosZero() {
num = BigDecimal.ZERO;
classification = POSZERO;
}
public void setNegZero() {
num = BigDecimal.ZERO;
classification = NEGZERO;
}
public void setPosInf() {
num = BigDecimal.ZERO;
classification = POSINF;
}
public void setNegInf() {
num = BigDecimal.ZERO;
classification = NEGINF;
}
public void setNan() {
num = BigDecimal.ZERO;
classification = NAN;
}
// Take my classification and BigDecimal values and encode them as
// an IEEE128 in the 16 bytes of arr starting at offset
void encode(byte[] arr, int offset) {
switch (classification) {
case NORMAL:
BigInteger ff = BigInteger.valueOf(255);
BigDecimal tmp = num.abs();
int signBit = (num.signum() < 0) ? 0x80 : 0;
if (tmp.compareTo(BigDecimal.ONE) == 0) {
arr[offset + 15] = (byte) (signBit | 0x3f);
arr[offset + 14] = (byte) 0xff;
for (int i = 13; i >= 0; i
arr[offset + i] = 0;
}
}
// is it a subnormal?
else if (tmp.compareTo(MIN_SUBNORMAL) >= 0 && tmp.compareTo(MAX_SUBNORMAL) <= 0) {
BigInteger fraction = findFraction(MIN_SUBNORMAL, MAX_SUBNORMAL, tmp);
arr[offset + 15] = (byte) signBit;
arr[offset + 14] = 0;
for (int i = 0; i < 14; i++) {
byte b = fraction.and(ff).byteValue();
fraction = fraction.shiftRight(8);
arr[offset + i] = b;
}
}
// is it between zero and one?
else if (tmp.compareTo(BigDecimal.ZERO) > 0 && tmp.compareTo(BigDecimal.ONE) < 0) {
// it's a number > 0 and < 1
//BigDecimal lg2 = BigDecimalMath.log2(tmp, Float128Algebra.CONTEXT);
//int exponent = lg2.intValue();
int exponent = -(BigDecimal.ONE.divide(tmp, Float128Algebra.CONTEXT).toBigInteger().bitLength()-1);
BigDecimal lowerBound = TWO.pow(exponent-1, Float128Algebra.CONTEXT);
BigDecimal upperBound = TWO.pow(exponent, Float128Algebra.CONTEXT);
BigInteger fraction = findFraction(lowerBound, upperBound, tmp);
exponent += 16382;
int ehi = (exponent & 0xff00) >> 8;
int elo = (exponent & 0x00ff) >> 0;
arr[offset + 15] = (byte) (signBit | ehi);
arr[offset + 14] = (byte) (elo);
for (int i = 0; i < 14; i++) {
byte b = fraction.and(ff).byteValue();
fraction = fraction.shiftRight(8);
arr[offset + i] = b;
}
}
else {
// it's a number > 1 and <= MAXBOUND
BigInteger bi = tmp.toBigInteger();
int exponent = bi.bitLength() - 1;
BigDecimal lowerBound = TWO.pow(exponent, Float128Algebra.CONTEXT);
BigDecimal upperBound = TWO.pow(exponent+1, Float128Algebra.CONTEXT);
BigInteger fraction = findFraction(lowerBound, upperBound, tmp);
exponent += 16383;
int ehi = (exponent & 0xff00) >> 8;
int elo = (exponent & 0x00ff) >> 0;
arr[offset + 15] = (byte) (signBit | ehi);
arr[offset + 14] = (byte) (elo);
for (int i = 0; i < 14; i++) {
byte b = fraction.and(ff).byteValue();
fraction = fraction.shiftRight(8);
arr[offset + i] = b;
}
}
break;
case POSZERO:
// encode a regular (positive) 0
for (int i = 15; i >= 0; i
arr[offset + i] = 0;
}
break;
case NEGZERO:
// encode a negative 0
arr[offset + 15] = (byte) 0x80;
for (int i = 14; i >= 0; i
arr[offset + i] = 0;
}
break;
case POSINF:
// +1 / 0
// encode a positive infinity in the remaining 16 bytes
arr[offset + 15] = (byte) 0x7f;
arr[offset + 14] = (byte) 0xff;
for (int i = 13; i >= 0; i
arr[offset + i] = 0;
}
break;
case NEGINF:
// -1 / 0
// encode a negative infinity in the remaining 16 bytes
arr[offset + 15] = (byte) 0xff;
arr[offset + 14] = (byte) 0xff;
for (int i = 13; i >= 0; i
arr[offset + i] = 0;
}
break;
case NAN:
// 0 / 0
// encode a NaN in the remaining 16 bytes
arr[offset + 15] = (byte) 0x7f;
arr[offset + 14] = (byte) 0xff;
for (int i = 13; i >= 0; i
// Any non zero value tells the OS this is a nan rather than
// an inf.
// TODO : do I have to deal with signaling versus nonsignaling
// or is that only applicable to hardware implementations?
arr[offset + i] = 1;
}
break;
default:
throw new IllegalArgumentException("unknown number classification "+classification);
}
}
// Take the 16 bytes stored in arr starting at offset and decode them
// into my denom and BigDecimal values.
void decode(byte[] buffer, int offset) {
int sign = (buffer[offset + 15] & 0x80);
int exponent = ((buffer[offset + 15] & 0x7f) << 8) + (buffer[offset + 14] & 0xff);
BigInteger fraction = BigInteger.ZERO;
for (int i = 13; i >= 0; i
fraction = fraction.shiftLeft(8).add(BigInteger.valueOf(buffer[offset + i] & 0xff));
}
if (exponent > 0 && exponent < 0x7fff) {
// a regular number
BigDecimal value = new BigDecimal(fraction).divide(FULL_RANGE_BD, Float128Algebra.CONTEXT);
value = value.add(BigDecimal.ONE);
value = value.multiply(TWO.pow(exponent - 16383, Float128Algebra.CONTEXT));
if (sign != 0)
value = value.negate();
setNormal(value);
}
else if (exponent == 0) {
// a special number : zeroes and subnormals
if (fraction.compareTo(BigInteger.ZERO) == 0) {
// a zero
if (sign != 0)
setNegZero();
else
setPosZero();
}
else {
// subnormal number
BigDecimal value = new BigDecimal(fraction).divide(FULL_RANGE_BD, Float128Algebra.CONTEXT);
value = value.multiply(TWO.pow(-16382, Float128Algebra.CONTEXT));
if (sign != 0)
value = value.negate();
// setV() rather than setNormal() to clamp off roundoff issues
setV(value);
}
}
else if (exponent == 0x7fff) {
// a special number; infinities and nan
if (fraction.compareTo(BigInteger.ZERO) == 0) {
// an infinity
if (sign != 0)
setNegInf();
else
setPosInf();
}
else {
// a nan
setNan();
}
}
else
throw new IllegalArgumentException("illegal exponent "+exponent);
}
private BigInteger findFraction(BigDecimal lowerBound, BigDecimal upperBound, BigDecimal value) {
BigDecimal numer = value.subtract(lowerBound);
BigDecimal denom = upperBound.subtract(lowerBound);
BigDecimal ratio = numer.divide(denom, Float128Algebra.CONTEXT);
// adding half to make sure we are correctly rounding
BigInteger fraction = FULL_RANGE_BD.multiply(ratio).add(BigDecimalUtils.ONE_HALF).toBigInteger();
// due to rounding quirks with java you might actually reach or surpass 1.0 so clamp it
if (fraction.compareTo(FULL_FRACTION) > 0)
fraction = FULL_FRACTION;
return fraction;
}
private void clamp() {
if (classification == NORMAL) {
if (num.compareTo(MIN_NORMAL) < 0) {
setNegInf();
}
else if (num.compareTo(MAX_NORMAL) > 0) {
setPosInf();
}
else if (num.abs().compareTo(MIN_SUBNORMAL) < 0) {
if (num.signum() < 0)
setNegZero();
else
setPosZero();
}
}
}
@Override
public BigDecimal[] getAsBigDecimalArray() {
return new BigDecimal[] {v()};
}
}
|
package com.matthewtamlin.spyglass.processors.annotation_utils;
import java.lang.annotation.Annotation;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
import static com.matthewtamlin.spyglass.processors.core.AnnotationRegistry.VALUE_HANDLER_ANNOTATIONS;
public class ValueHandlerAnnotationUtil {
public static Annotation getValueHandlerAnnotation(final ExecutableElement element) {
checkNotNull(element, "Argument \'element\' cannot be null.");
for (final Class<? extends Annotation> a : VALUE_HANDLER_ANNOTATIONS) {
if (element.getAnnotation(a) != null) {
return element.getAnnotation(a);
}
}
return null;
}
public static boolean hasValueAnnotation(final ExecutableElement element) {
return getValueHandlerAnnotation(element) != null;
}
private ValueHandlerAnnotationUtil() {
throw new RuntimeException("Utility class. Do not instantiate.");
}
}
|
package com.jetbrains.idear.asr;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.impl.SimpleDataContext;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.util.Pair;
import com.intellij.util.Consumer;
import com.jetbrains.idear.GoogleHelper;
import com.jetbrains.idear.actions.ExecuteVoiceCommandAction;
import com.jetbrains.idear.recognizer.CustomLiveSpeechRecognizer;
import com.jetbrains.idear.recognizer.CustomMicrophone;
import com.jetbrains.idear.tts.TTSService;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.SpeechResult;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ASRServiceImpl implements ASRService {
public static final double MASTER_GAIN = 0.85;
public static final double CONFIDENCE_LEVEL_THRESHOLD = 0.5;
private final Thread speechThread = new Thread(new ASRControlLoop(), "ASR Thread");
private static final String ACOUSTIC_MODEL = "resource:/edu.cmu.sphinx.models.en-us/en-us";
private static final String DICTIONARY_PATH = "resource:/edu.cmu.sphinx.models.en-us/cmudict-en-us.dict";
private static final String GRAMMAR_PATH = "resource:/com.jetbrains.idear/grammars";
private static final Logger logger = Logger.getLogger(ASRServiceImpl.class.getSimpleName());
private CustomLiveSpeechRecognizer recognizer;
private Robot robot;
private final AtomicReference<Status> status = new AtomicReference<>(Status.INIT);
public void init() {
Configuration configuration = new Configuration();
configuration.setAcousticModelPath(ACOUSTIC_MODEL);
configuration.setDictionaryPath(DICTIONARY_PATH);
configuration.setGrammarPath(GRAMMAR_PATH);
configuration.setUseGrammar(true);
configuration.setGrammarName("command");
try {
recognizer = new CustomLiveSpeechRecognizer(configuration);
// recognizer.setMasterGain(MASTER_GAIN);
} catch (IOException e) {
logger.log(Level.SEVERE, "Couldn't initialize speech recognizer:", e);
}
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
// Start-up recognition facilities
recognizer.startRecognition(true);
// Fire up control-loop
speechThread.start();
}
public void dispose() {
// Deactivate in the first place, therefore actually
// prevent activation upon the user-input
deactivate();
terminate();
}
private void terminate() {
recognizer.stopRecognition();
}
private Status setStatus(Status s) {
return status.getAndSet(s);
}
@Override
public Status getStatus() {
return status.get();
}
@Override
public Status activate() {
if (getStatus() == Status.ACTIVE)
return Status.ACTIVE;
// if (getStatus() == Status.INIT) {
// // Cold start prune cache
// recognizer.startRecognition(true);
return setStatus(Status.ACTIVE);
}
@Override
public Status deactivate() {
return setStatus(Status.STANDBY);
}
private class ASRControlLoop implements Runnable {
public static final String FUCK = "fuck";
public static final String OPEN = "open";
public static final String SETTINGS = "settings";
public static final String RECENT = "recent";
public static final String TERMINAL = "terminal";
public static final String FOCUS = "focus";
public static final String EDITOR = "editor";
public static final String PROJECT = "project";
public static final String SELECTION = "selection";
public static final String EXPAND = "expand";
public static final String SHRINK = "shrink";
public static final String PRESS = "press";
public static final String DELETE = "delete";
public static final String ENTER = "enter";
public static final String ESCAPE = "escape";
public static final String TAB = "tab";
public static final String UNDO = "undo";
public static final String NEXT = "next";
public static final String LINE = "line";
public static final String PAGE = "page";
public static final String METHOD = "method";
public static final String PREVIOUS = "previous";
public static final String INSPECT_CODE = "inspect code";
public static final String OKAY_GOOGLE = "okay google";
public static final String OK_GOOGLE = "ok google";
public static final String OKAY_IDEA = "okay idea";
public static final String OK_IDEA = "ok idea";
public static final String HI_IDEA = "hi idea";
@Override
public void run() {
while (!isTerminated()) {
// This blocks on a recognition result
String result = getResultFromRecognizer();
if (isInit()) {
if (result.equals(HI_IDEA)) {
// Greet invoker
say("Hi");
invokeAction("Idear.Start");
}
} else if (isActive()) {
logger.log(Level.INFO, "Recognized: " + result);
applyAction(result);
}
}
}
private String getResultFromRecognizer() {
SpeechResult result = recognizer.getResult();
logger.info("Recognized: ");
logger.info("\tTop H: " + result.getResult() + " / " + result.getResult().getBestToken() + " / " + result.getResult().getBestPronunciationResult());
logger.info("\tTop 3H: " + result.getNbest(3));
return result.getHypothesis();
}
private void applyAction(String c) {
if (c.equals(HI_IDEA)) {
// Greet some more
say("Hi, again!");
}
else if (c.equals(FUCK)) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_Z);
//invokeAction(IdeActions.ACTION_UNDO);
}
else if (c.startsWith(OPEN)) {
if (c.endsWith(SETTINGS)) {
invokeAction(IdeActions.ACTION_SHOW_SETTINGS);
} else if (c.endsWith(RECENT)) {
invokeAction(IdeActions.ACTION_RECENT_FILES);
} else if (c.endsWith(TERMINAL)) {
pressKeystroke(KeyEvent.VK_ALT, KeyEvent.VK_F12);
}
}
else if (c.startsWith("focus")) {
if (c.endsWith("editor")) {
pressKeystroke(KeyEvent.VK_ESCAPE);
} else if (c.endsWith("project")) {
pressKeystroke(KeyEvent.VK_ALT, KeyEvent.VK_1);
}
}
else if (c.endsWith("selection")) {
if (c.startsWith("expand")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_W);
} else if (c.startsWith("shrink")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_SHIFT, KeyEvent.VK_W);
}
}
else if (c.startsWith("press")) {
if (c.contains("delete")) {
pressKeystroke(KeyEvent.VK_DELETE);
} else if (c.contains("return")) {
pressKeystroke(KeyEvent.VK_ENTER);
} else if (c.contains("escape")) {
pressKeystroke(KeyEvent.VK_ESCAPE);
} else if (c.contains("tab")) {
pressKeystroke(KeyEvent.VK_TAB);
} else if (c.contains("undo")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_Z);
}
}
else if (c.startsWith("following")) {
if (c.endsWith("line")) {
pressKeystroke(KeyEvent.VK_DOWN);
} else if (c.endsWith("page")) {
pressKeystroke(KeyEvent.VK_PAGE_DOWN);
} else if (c.endsWith("method")) {
pressKeystroke(KeyEvent.VK_ALT, KeyEvent.VK_DOWN);
}
}
else if (c.startsWith("previous")) {
if (c.endsWith("line")) {
pressKeystroke(KeyEvent.VK_UP);
} else if (c.endsWith("page")) {
pressKeystroke(KeyEvent.VK_PAGE_UP);
} else if (c.endsWith("method")) {
pressKeystroke(KeyEvent.VK_ALT, KeyEvent.VK_UP);
}
}
else if (c.startsWith("extract this")) {
if (c.endsWith("method")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_ALT, KeyEvent.VK_M);
} else if (c.endsWith("parameter")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_ALT, KeyEvent.VK_P);
}
}
else if (c.startsWith("inspect code")) {
pressKeystroke(KeyEvent.VK_ALT, KeyEvent.VK_SHIFT, KeyEvent.VK_I);
}
else if (c.startsWith("speech pause")) {
pauseSpeech();
}
else if (c.startsWith(OK_IDEA) || c.startsWith(OKAY_IDEA)) {
beep();
fireVoiceCommand();
}
else if (c.startsWith(OKAY_GOOGLE) || c.startsWith(OK_GOOGLE)) {
beep();
fireGoogleSearch();
}
else if(c.contains("break point")) {
if (c.startsWith("toggle")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_F8);
} else if(c.startsWith("view")) {
pressKeystroke(KeyEvent.VK_CONTROL, KeyEvent.VK_SHIFT, KeyEvent.VK_F8);
}
}
else if (c.startsWith("step")) {
if (c.endsWith("over")) {
pressKeystroke(KeyEvent.VK_F8);
} else if (c.endsWith("into")) {
pressKeystroke(KeyEvent.VK_F7);
}
}
else if (c.startsWith("tell me a joke")) {
tellJoke();
}
}
private void tellJoke() {
ServiceManager
.getService(TTSService.class)
.say("knock, knock, knock, knock, knock");
String result = null;
while (!"who is there".equals(result)) {
result = getResultFromRecognizer();
}
ServiceManager
.getService(TTSService.class)
.say("Hang on, I will be right back");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ServiceManager
.getService(TTSService.class)
.say("Jah, jah, jav, jav, jav, a, a, a, va, va, va, va, va");
while (!result.contains("wait who") &&
!result.contains("who are you")) {
result = getResultFromRecognizer();
}
ServiceManager
.getService(TTSService.class)
.say("Did I stutter? It is me, Jah java va va, va, va. Open up already!");
}
private void fireVoiceCommand() {
try {
Pair<String, Double> commandTuple = GoogleHelper.getBestTextForUtterance(CustomMicrophone.recordFromMic());
if (commandTuple == null || commandTuple.first.isEmpty() /* || searchQuery.second < CONFIDENCE_LEVEL_THRESHOLD */)
return;
// Notify of successful proceed
beep();
invokeAction(
"Idear.VoiceAction",
dataContext -> new AnActionEvent(
null,
SimpleDataContext.getSimpleContext(ExecuteVoiceCommandAction.KEY.getName(), commandTuple.first, dataContext),
ActionPlaces.UNKNOWN,
new Presentation(),
ActionManager.getInstance(),
0
)
);
} catch (IOException e) {
logger.log(Level.SEVERE, "Panic! Failed to dump WAV", e);
}
}
private void fireGoogleSearch() {
try {
Pair<String, Double> searchQueryTuple = GoogleHelper.getBestTextForUtterance(CustomMicrophone.recordFromMic());
if (searchQueryTuple == null || searchQueryTuple.first.isEmpty() /* || searchQuery.second < CONFIDENCE_LEVEL_THRESHOLD */)
return;
ServiceManager
.getService(TTSService.class)
.say("I think you said " + searchQueryTuple.first + ", searching Google now");
GoogleHelper.searchGoogle(searchQueryTuple.first);
} catch (IOException e) {
logger.log(Level.SEVERE, "Panic! Failed to dump WAV", e);
}
}
private void pauseSpeech() {
String result;
while (isActive()) {
result = getResultFromRecognizer();
if (result.equals("speech resume")) {
break;
}
}
}
}
private boolean isTerminated() {
return getStatus() == Status.TERMINATED;
}
public boolean isInit() {
return getStatus() == Status.INIT;
}
private boolean isActive() {
return getStatus() == Status.ACTIVE;
}
private void pressKeystroke(final int... keys) {
for (int key : keys) {
robot.keyPress(key);
}
for (int key : keys) {
robot.keyRelease(key);
}
}
private void invokeAction(final String action) {
invokeAction(
action,
dataContext ->
new AnActionEvent(null,
dataContext,
ActionPlaces.UNKNOWN,
new Presentation(),
ActionManager.getInstance(),
0
)
);
}
private void invokeAction(String action, Function<DataContext, AnActionEvent> actionFactory) {
DataManager.getInstance().getDataContextFromFocus().doWhenDone(
(Consumer<DataContext>) dataContext -> EventQueue.invokeLater(() -> {
AnAction anAction = ActionManager.getInstance().getAction(action);
anAction.actionPerformed(actionFactory.apply(dataContext));
})
);
}
// Helpers
public static synchronized void say(String something) {
ServiceManager .getService(TTSService.class)
.say(something);
}
public static synchronized void beep() {
Thread t = new Thread(() -> {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
ASRServiceImpl.class.getResourceAsStream("/com.jetbrains.idear/sounds/beep.wav"));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
});
t.start();
try {
t.join();
} catch (InterruptedException _) {}
}
// This is for testing purposes solely
public static void main(String[] args) {
ASRServiceImpl asrService = new ASRServiceImpl();
asrService.init();
asrService.activate();
}
}
|
package com.hckthn.watchoutserver;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;
public class WatchLink extends Service {
static final String TAG = "WatchLink";
public static final String EOS = "<!EOS!>";
public static final String DISMISS_INTENT = "com.hkthn.slidingwatchscreens.dismiss";
public static final String NOTIFICATION_INTENT = "com.hkthn.slidingwatchscreens.notification";
public static final int NOTIFICATION_ID = 300;
public static final String UUID = "7bcc1440-858a-11e3-baa7-0800200c9a66";
Handler h = new Handler(){
@Override
public void handleMessage(Message msg) {
//Object always going to be a string
log("Handler received message");
String s = (String) msg.obj;
handleInput(s);
}
};
SharedPreferences prefs;
BroadcastReceiver br;
BluetoothAdapter ba;
LocationManager lm;
MediaRecorder mr;
SimpleDateFormat fileNameDate;
SimpleDateFormat locationSdf;
String saveLocation;
ConnectThread ct;
IOThread io;
boolean hasConnected = false;
@Override
public void onCreate(){
super.onCreate();
log("On create");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
br = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(NOTIFICATION_INTENT)){
log("Got notification request");
//Send to phone if possible
}
}
};
IntentFilter intf = new IntentFilter();
intf.addAction(NOTIFICATION_INTENT);
LocalBroadcastManager.getInstance(this).registerReceiver(br, intf);
ba = BluetoothAdapter.getDefaultAdapter();
lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
mr = new MediaRecorder();
mr.setOnErrorListener(new OnErrorListener(){
@Override
public void onError(MediaRecorder arg0, int arg1, int arg2) {
log("Media recorder error: " + arg1);
}
});
mr.setOnInfoListener(new OnInfoListener(){
@Override
public void onInfo(MediaRecorder arg0, int arg1, int arg2) {
log("Media info: " + arg1);
}
});
saveLocation = Environment.getExternalStorageDirectory() + "/WatchOutRecording/";
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Toast.makeText(this, "Storage media unavailalbe! Unable to save recordings (WatchOut)!" , Toast.LENGTH_LONG).show();
}
File saveFile = new File(saveLocation);
if(!saveFile.exists() || !saveFile.isDirectory()){
saveFile.mkdirs();
}
fileNameDate = new SimpleDateFormat("yyyy-mm-dd_HH:mm:ss", Locale.US);
locationSdf = new SimpleDateFormat("h:mm:ss aa EEE MMM dd", Locale.US);
updateNotification("Watch link started...");
attemptToConnect("Watch link waiting...");
}
public void startRecording(){
try {
log("Starting recording");
mr.setAudioSource(MediaRecorder.AudioSource.MIC);
mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mr.setOutputFile(saveLocation + fileNameDate.format(GregorianCalendar.getInstance().getTime()) + ".3gp");
try {
mr.prepare();
mr.start();
log("Recording started");
Timer t = new Timer();
t.schedule(new TimerTask(){
@Override
public void run() {
log("Recording stopped");
mr.stop();
}
}, 120000);
} catch (Exception e) {
log("Error starting recording: " + e.getMessage());
}
} catch (Exception e) {
log("Media recorder in bad state when called upon");
}
}
public void updateNotification(String text){
Intent startSettings = new Intent(this, MainActivity.class);
startSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pi = PendingIntent.getActivity(this, -1, startSettings, 0);
NotificationCompat.Builder n = new NotificationCompat.Builder(this)
.setAutoCancel(false)
.setOngoing(true)
.setContentTitle("Link to watch running")
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pi);
this.startForeground(NOTIFICATION_ID, n.build());
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy(){
super.onDestroy();
if(mr == null) mr.release();
mr = null;
log("On destroy");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
private void log(String text){
Log.d(TAG, text);
}
private void handleSocketConnection(BluetoothSocket socket){
log("New socket to watch found");
updateNotification("Watch link connected!");
io = new IOThread(socket);
io.run();
}
private void handleInput(String dataIn){
log("Data in: " + dataIn);
dataIn = (String) dataIn.subSequence(0, dataIn.indexOf(EOS));
int barPos = dataIn.indexOf("|");
if(barPos != -1){
String requestType = dataIn.substring(0, barPos);
String requestData = dataIn.substring(barPos+1);
log("Request type: " + requestType);
log("Request data: " + requestData);
if(requestType.equals("HELP_REQUEST")){
log("Initializing help actions");
io.write("HELP_ACK|Acknowledged.");
String message = prefs.getString(MainActivity.MESSAGE_PREF, "");
String toSend = "Help! I'm in trouble! My message: " + message + "; My last location: ";
//Get last location
Location gpsL = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location netL = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(gpsL != null){
Date d = new Date(gpsL.getTime());
String formatted = locationSdf.format(d);
if(gpsL.getTime() - System.currentTimeMillis() < 60000){ //If it's less than a minute old, it's recent
toSend += gpsL.getLatitude() + ", " + gpsL.getLongitude() + " at " + formatted + " (GPS)";
} else { //Set listener for better data to send when you get a chance
toSend += gpsL.getLatitude() + ", " + gpsL.getLongitude() + " at " + formatted + " (GPS, old data)";
scheduleLocationUpdates();
}
} else if (netL != null){
Date d = new Date(netL.getTime());
String formatted = locationSdf.format(d);
toSend += netL.getLatitude() + ", " + netL.getLongitude() + " at " + formatted + " (network, old data)";
scheduleLocationUpdates();
}
//Help messages
String allNumbers = prefs.getString(MainActivity.CONTACT_NUMBER_BASE, "");
if(allNumbers.length() > 0){
if(allNumbers.indexOf(",") != 0){
String[] numbers = allNumbers.split(",");
for(int i = 0; i < numbers.length; i++){
SmsManager.getDefault().sendTextMessage(numbers[i], null, toSend, null, null);
}
} else {
SmsManager.getDefault().sendTextMessage(allNumbers, null, toSend, null, null);
}
}
//Start recording
startRecording();
}
} else {
log("Error! Improper formatting");
}
}
private void scheduleLocationUpdates(){
Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.ACCURACY_FINE);
log("Calling for an update");
lm.requestSingleUpdate(locationCriteria, new LocationListener(){
@Override
public void onLocationChanged(Location gpsL) {
String toSend = "More accurate location of person in trouble: ";
if(gpsL != null){
Date d = new Date(gpsL.getTime());
String formatted = locationSdf.format(d);
if(gpsL.getTime() - System.currentTimeMillis() < 60000){ //If it's less than a minute old, it's recent
toSend += gpsL.getLatitude() + ", " + gpsL.getLongitude() + " at " + formatted + " (GPS)";
} else { //CAn't get anything better
toSend += gpsL.getLatitude() + ", " + gpsL.getLongitude() + " at " + formatted + " (GPS, old data)";
}
}
//Send message
//Help messages
String allNumbers = prefs.getString(MainActivity.CONTACT_NUMBER_BASE, "");
if(allNumbers.length() > 0){
if(allNumbers.indexOf(",") != 0){
String[] numbers = allNumbers.split(",");
for(int i = 0; i < numbers.length; i++){
SmsManager.getDefault().sendTextMessage(numbers[i], null, toSend, null, null);
}
} else {
SmsManager.getDefault().sendTextMessage(allNumbers, null, toSend, null, null);
}
}
}
@Override
public void onProviderDisabled(String arg0) {
}
@Override
public void onProviderEnabled(String arg0) {
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}, null);
}
private void attemptToConnect(String newUpdate){
updateNotification(newUpdate);
ct = new ConnectThread();
ct.start();
}
private class IOThread extends Thread {
private final BluetoothSocket bs;
private final InputStream is;
private final OutputStream os;
public IOThread(BluetoothSocket socket){
log("IOThread created");
bs = socket;
InputStream in = null;
OutputStream out = null;
try {
in = bs.getInputStream();
out = bs.getOutputStream();
} catch (IOException e) {}
is = in;
os = out;
}
public void run(){
log("Running IOThread...");
StringBuilder stringToSend = new StringBuilder();
byte[] readBuffer = new byte[1024];
int newBytes;
while(true){
try {
while((newBytes = is.read(readBuffer)) != -1){ //So long as we're not at the end of stream
stringToSend.append(new String(readBuffer, 0, newBytes, Charset.defaultCharset()));
int eosIndex = stringToSend.indexOf(EOS);
if(eosIndex != -1){
String toSend = stringToSend.toString();
Message m = h.obtainMessage(1, toSend);
h.sendMessage(m);
stringToSend = new StringBuilder();
}
}
} catch (Exception e) {
log("Exception:" + e.getMessage());
log("ETOSTring: " + e.toString());
log("IOThread done; connection lost");
this.cancel();
attemptToConnect("Connection lost; trying to rejoin...");
break; //done -- connection lost
}
}
}
public void write(String dataIn){
log("Writing bytes to output streams");
dataIn = dataIn + EOS;
try {
byte[] dataBytes = dataIn.getBytes();
os.write(dataBytes);
} catch (Exception e) {}
}
public void cancel(){
log("Cancelling IOThread...");
try {
bs.close();
} catch (IOException e) {}
}
}
private class ConnectThread extends Thread {
private final BluetoothServerSocket server;
public ConnectThread(){
BluetoothServerSocket tmp = null;
try {
tmp = ba.listenUsingRfcommWithServiceRecord("WatchLink", java.util.UUID.fromString(UUID));
log("Listening worked");
updateNotification("Watch link waiting...");
} catch (Exception e){
log("Listening failed: " + e.getLocalizedMessage());
}
server = tmp;
}
public void run(){
BluetoothSocket socket = null;
while(true){
try {
socket = server.accept();
log("Server accepted");
} catch (Exception e){
log("Server failed");
break;
}
if(socket != null){
handleSocketConnection(socket);
hasConnected = true;
log("Has connected");
try {
server.close();
} catch (Exception e) {
log("Unable to close " + e.getMessage());
}
break;
}
}
}
public void cancel(){
try {
server.close();
} catch (Exception e) {
log("Unable to close " + e.getMessage());
}
}
}
}
|
package com.bota.server.patch.deployer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import org.apache.commons.codec.digest.DigestUtils;
import com.bota.server.patch.util.PathUtil;
import com.bota.server.patch.util.UnzipUtil;
public class PatchDeployer {
public static void hashFolder() throws IOException {
File deployFolder = new File("deploy");
if (!deployFolder.exists()) deployFolder.mkdir();
ArrayList<File> files = new ArrayList<File>();
PathUtil.listf("files", files);
StringBuilder builder = new StringBuilder();
for (File file : files) {
FileInputStream fileInputStream = new FileInputStream(file);
builder.append(file.getPath().replace("\\", "/") + "$" + DigestUtils.md5Hex(fileInputStream) + System.lineSeparator());
}
try (FileWriter fileWriter = new FileWriter("deploy/hash")) {
fileWriter.write(builder.toString());
}
System.out.println("Hash file done");
}
public static void main(String args[]) throws IOException {
if (args.length == 0) {
hashFolder();
return;
}
String zipPath = args[0];
File zipFile = new File(zipPath);
if (zipFile.exists() && zipFile.isFile()) {
File filesDirectory = new File("files");
if (!filesDirectory.exists()) {
filesDirectory.mkdir();
}
UnzipUtil unzipUtil = new UnzipUtil();
unzipUtil.unzip(zipPath, "files");
System.out.println("Unzipped files");
hashFolder();
Path releaseFile = FileSystems.getDefault().getPath(zipPath);
Path serverFile = FileSystems.getDefault().getPath("deploy/patch.zip");
Files.copy(releaseFile, serverFile, StandardCopyOption.REPLACE_EXISTING);
System.out.println("ZIP file copied");
}
else {
System.err.println("Sorry, the path is not valid.");
return;
}
}
}
|
package org.zalando.riptide.httpclient;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.restdriver.clientdriver.ClientDriver;
import com.github.restdriver.clientdriver.ClientDriverFactory;
import com.github.restdriver.clientdriver.ClientDriverRequest;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.StreamingHttpOutputMessage;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.zalando.riptide.Http;
import org.zalando.riptide.capture.Capture;
import org.zalando.riptide.httpclient.ApacheClientHttpRequestFactory.Mode;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executors;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NON_PRIVATE;
import static com.github.restdriver.clientdriver.RestClientDriver.giveResponse;
import static com.github.restdriver.clientdriver.RestClientDriver.giveResponseAsBytes;
import static com.github.restdriver.clientdriver.RestClientDriver.onRequestTo;
import static com.google.common.io.Resources.getResource;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import static org.mockito.Mockito.mock;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpMethod.POST;
import static org.springframework.http.HttpStatus.Series.SUCCESSFUL;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.zalando.riptide.Bindings.on;
import static org.zalando.riptide.Navigators.series;
import static org.zalando.riptide.PassRoute.pass;
import static org.zalando.riptide.Types.listOf;
public abstract class AbstractApacheClientHttpRequestFactoryTest {
private final ClientDriver driver = new ClientDriverFactory().createClientDriver();
private final CloseableHttpClient client = HttpClientBuilder.create()
.setMaxConnTotal(1)
.setMaxConnPerRoute(1)
.build();
private final ApacheClientHttpRequestFactory factory = new ApacheClientHttpRequestFactory(client, getMode());
abstract Mode getMode();
private final Http http = Http.builder()
.executor(Executors.newSingleThreadExecutor())
.requestFactory(factory)
.baseUrl(driver.getBaseUrl())
.converter(new MappingJackson2HttpMessageConverter(createObjectMapper()))
.build();
private static ObjectMapper createObjectMapper() {
return new ObjectMapper().findAndRegisterModules()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
@AfterEach
void tearDown() throws IOException {
factory.destroy();
}
@Test
void shouldReadContributors() throws IOException {
driver.addExpectation(onRequestTo("/repos/zalando/riptide/contributors"),
giveResponseAsBytes(getResource("contributors.json").openStream(), "application/json"));
final RestTemplate template = new RestTemplate(factory);
template.setMessageConverters(singletonList(new MappingJackson2HttpMessageConverter(createObjectMapper())));
final List<User> users = template.exchange(driver.getBaseUrl() + "/repos/zalando/riptide/contributors", GET,
HttpEntity.EMPTY, new ParameterizedTypeReference<List<User>>() {
}).getBody();
Objects.requireNonNull(users);
final List<String> names = users.stream()
.map(User::getLogin)
.collect(toList());
assertThat(names, hasItems("jhorstmann", "lukasniemeier-zalando", "whiskeysierra"));
}
@Test
void shouldReadContributorsAsync() throws IOException {
driver.addExpectation(onRequestTo("/repos/zalando/riptide/contributors"),
giveResponseAsBytes(getResource("contributors.json").openStream(), "application/json"));
final Capture<List<User>> capture = Capture.empty();
final List<User> users = http.get("/repos/{org}/{repo}/contributors", "zalando", "riptide")
.dispatch(series(),
on(SUCCESSFUL).call(listOf(User.class), capture))
.thenApply(capture).join();
final List<String> names = users.stream()
.map(User::getLogin)
.collect(toList());
assertThat(names, hasItems("jhorstmann", "lukasniemeier-zalando", "whiskeysierra"));
}
@Test
void shouldReadContributorsManually() throws IOException {
driver.addExpectation(onRequestTo("/repos/zalando/riptide/contributors").withMethod(ClientDriverRequest.Method.POST),
giveResponseAsBytes(getResource("contributors.json").openStream(), "application/json"));
final URI uri = URI.create(driver.getBaseUrl()).resolve("/repos/zalando/riptide/contributors");
final ClientHttpRequest request = factory.createRequest(uri, POST);
request.getHeaders().setAccept(singletonList(APPLICATION_JSON));
if (request instanceof StreamingHttpOutputMessage) {
((StreamingHttpOutputMessage) request)
.setBody(stream -> stream.write("{}".getBytes(UTF_8)));
} else {
request.getBody().write("{}".getBytes(UTF_8));
}
assertThat(request.getMethod(), is(POST));
assertThat(request.getMethodValue(), is("POST"));
assertThat(request.getURI(), hasToString(endsWith("/repos/zalando/riptide/contributors")));
assertThat(request.getHeaders().getAccept(), hasItem(APPLICATION_JSON));
final ClientHttpResponse response = request.execute();
assertThat(response.getStatusCode(), is(HttpStatus.OK));
assertThat(response.getRawStatusCode(), is(200));
assertThat(response.getStatusText(), is("OK"));
assertThat(response.getHeaders(), is(not(anEmptyMap())));
final InputStream stream = response.getBody();
final ObjectMapper mapper = createObjectMapper();
final List<User> users = mapper.readValue(stream, new TypeReference<List<User>>() {
});
final List<String> names = users.stream()
.map(User::getLogin)
.collect(toList());
assertThat(names, hasItems("jhorstmann", "lukasniemeier-zalando", "whiskeysierra"));
}
@Test
void shouldReleaseConnection() {
driver.addExpectation(onRequestTo("/"), giveResponse("Hello world!", "text/plain"));
driver.addExpectation(onRequestTo("/"), giveResponse("Hello world!", "text/plain"));
assertTimeout(Duration.ofMillis(750), () -> {
http.get("/").call(pass()).join();
http.get("/").call(pass()).join();
});
}
@Test
void shouldDestroyNonCloseableClient() throws IOException {
new ApacheClientHttpRequestFactory(mock(HttpClient.class), getMode()).destroy();
}
@JsonAutoDetect(fieldVisibility = NON_PRIVATE)
static class User {
String login;
String getLogin() {
return login;
}
}
}
|
package com.ecyrd.jspwiki.parser;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.*;
import javax.xml.transform.Result;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.apache.oro.text.GlobCompiler;
import org.apache.oro.text.regex.*;
import org.jdom.Content;
import org.jdom.Element;
import org.jdom.IllegalDataException;
import org.jdom.ProcessingInstruction;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.attachment.Attachment;
import com.ecyrd.jspwiki.attachment.AttachmentManager;
import com.ecyrd.jspwiki.auth.WikiSecurityException;
import com.ecyrd.jspwiki.auth.acl.Acl;
import com.ecyrd.jspwiki.plugin.PluginException;
import com.ecyrd.jspwiki.plugin.PluginManager;
import com.ecyrd.jspwiki.providers.ProviderException;
import com.ecyrd.jspwiki.render.CleanTextRenderer;
/**
* This is a new class which replaces the TranslatorReader at some point.
* It is not yet functional, but it's getting there. The aim is to produce
* a parser class to an internal DOM tree; then cache this tree and only
* evaluate it at output.
*
* @author jalkanen
*
*/
public class JSPWikiMarkupParser
extends MarkupParser
{
private static final int READ = 0;
private static final int EDIT = 1;
private static final int EMPTY = 2; // Empty message
private static final int LOCAL = 3;
private static final int LOCALREF = 4;
private static final int IMAGE = 5;
private static final int EXTERNAL = 6;
private static final int INTERWIKI = 7;
private static final int IMAGELINK = 8;
private static final int IMAGEWIKILINK = 9;
private static final int ATTACHMENT = 10;
// private static final int ATTACHMENTIMAGE = 11;
private static Logger log = Logger.getLogger( JSPWikiMarkupParser.class );
//private boolean m_iscode = false;
private boolean m_isbold = false;
private boolean m_isitalic = false;
private boolean m_istable = false;
private boolean m_isPre = false;
private boolean m_isEscaping = false;
private boolean m_isdefinition = false;
private boolean m_isPreBlock = false;
/** Contains style information, in multiple forms. */
private Stack m_styleStack = new Stack();
// general list handling
private int m_genlistlevel = 0;
private StringBuffer m_genlistBulletBuffer = new StringBuffer(); // stores the # and * pattern
private boolean m_allowPHPWikiStyleLists = true;
private boolean m_isOpenParagraph = false;
/** Keeps image regexp Patterns */
private ArrayList m_inlineImagePatterns;
private PatternMatcher m_inlineMatcher = new Perl5Matcher();
/** Keeps track of any plain text that gets put in the Text nodes */
private StringBuffer m_plainTextBuf = new StringBuffer();
private Element m_currentElement;
/**
* This property defines the inline image pattern. It's current value
* is jspwiki.translatorReader.inlinePattern
*/
public static final String PROP_INLINEIMAGEPTRN = "jspwiki.translatorReader.inlinePattern";
/** If true, consider CamelCase hyperlinks as well. */
public static final String PROP_CAMELCASELINKS = "jspwiki.translatorReader.camelCaseLinks";
/** If true, all hyperlinks are translated as well, regardless whether they
are surrounded by brackets. */
public static final String PROP_PLAINURIS = "jspwiki.translatorReader.plainUris";
/** If true, all outward links (external links) have a small link image appended. */
public static final String PROP_USEOUTLINKIMAGE = "jspwiki.translatorReader.useOutlinkImage";
/** If set to "true", all external links are tagged with 'rel="nofollow"' */
public static final String PROP_USERELNOFOLLOW = "jspwiki.translatorReader.useRelNofollow";
/** If true, then considers CamelCase links as well. */
private boolean m_camelCaseLinks = false;
/** If true, consider URIs that have no brackets as well. */
// FIXME: Currently reserved, but not used.
private boolean m_plainUris = false;
/** If true, all outward links use a small link image. */
private boolean m_useOutlinkImage = true;
/** If true, allows raw HTML. */
private boolean m_allowHTML = false;
private boolean m_useRelNofollow = false;
private PatternCompiler m_compiler = new Perl5Compiler();
static final String WIKIWORD_REGEX = "(^|[[:^alnum:]]+)([[:upper:]]+[[:lower:]]+[[:upper:]]+[[:alnum:]]*|(http://|https://|mailto:)([A-Za-z0-9_/\\.\\+\\?\\
private PatternMatcher m_camelCaseMatcher = new Perl5Matcher();
private Pattern m_camelCasePattern;
/**
* The default inlining pattern. Currently "*.png"
*/
public static final String DEFAULT_INLINEPATTERN = "*.png";
/**
* This list contains all IANA registered URI protocol
* types as of September 2004 + a few well-known extra types.
*
* JSPWiki recognises all of them as external links.
*
* This array is sorted during class load, so you can just dump
* here whatever you want in whatever order you want.
*/
static final String[] c_externalLinks = {
"http:", "ftp:", "https:", "mailto:",
"news:", "file:", "rtsp:", "mms:", "ldap:",
"gopher:", "nntp:", "telnet:", "wais:",
"prospero:", "z39.50s", "z39.50r", "vemmi:",
"imap:", "nfs:", "acap:", "tip:", "pop:",
"dav:", "opaquelocktoken:", "sip:", "sips:",
"tel:", "fax:", "modem:", "soap.beep:", "soap.beeps",
"xmlrpc.beep", "xmlrpc.beeps", "urn:", "go:",
"h323:", "ipp:", "tftp:", "mupdate:", "pres:",
"im:", "mtqp", "smb:" };
/**
* This Comparator is used to find an external link from c_externalLinks. It
* checks if the link starts with the other arraythingie.
*/
private static Comparator c_startingComparator = new StartingComparator();
static
{
Arrays.sort( c_externalLinks );
}
/**
* Creates a markup parser.
*/
public JSPWikiMarkupParser( WikiContext context, Reader in )
{
super( context, in );
initialize();
}
/**
* @param engine The WikiEngine this reader is attached to. Is
* used to figure out of a page exits.
*/
// FIXME: parsers should be pooled for better performance.
private void initialize()
{
PatternCompiler compiler = new GlobCompiler();
ArrayList compiledpatterns = new ArrayList();
Collection ptrns = getImagePatterns( m_engine );
// Make them into Regexp Patterns. Unknown patterns
// are ignored.
for( Iterator i = ptrns.iterator(); i.hasNext(); )
{
try
{
compiledpatterns.add( compiler.compile( (String)i.next() ) );
}
catch( MalformedPatternException e )
{
log.error("Malformed pattern in properties: ", e );
}
}
m_inlineImagePatterns = compiledpatterns;
try
{
m_camelCasePattern = m_compiler.compile( WIKIWORD_REGEX );
}
catch( MalformedPatternException e )
{
log.fatal("Internal error: Someone put in a faulty pattern.",e);
throw new InternalWikiException("Faulty camelcasepattern in TranslatorReader");
}
// Set the properties.
Properties props = m_engine.getWikiProperties();
String cclinks = (String)m_context.getPage().getAttribute( PROP_CAMELCASELINKS );
if( cclinks != null )
{
m_camelCaseLinks = TextUtil.isPositive( cclinks );
}
else
{
m_camelCaseLinks = TextUtil.getBooleanProperty( props,
PROP_CAMELCASELINKS,
m_camelCaseLinks );
}
m_plainUris = TextUtil.getBooleanProperty( props,
PROP_PLAINURIS,
m_plainUris );
m_useOutlinkImage = TextUtil.getBooleanProperty( props,
PROP_USEOUTLINKIMAGE,
m_useOutlinkImage );
m_allowHTML = TextUtil.getBooleanProperty( props,
MarkupParser.PROP_ALLOWHTML,
m_allowHTML );
m_useRelNofollow = TextUtil.getBooleanProperty( props,
PROP_USERELNOFOLLOW,
m_useRelNofollow );
if( m_engine.getUserDatabase() == null || m_engine.getAuthorizationManager() == null )
{
disableAccessRules();
}
m_context.getPage().setHasMetadata();
}
/**
* Figure out which image suffixes should be inlined.
* @return Collection of Strings with patterns.
*/
// FIXME: Does not belong here; should be elsewhere
public static Collection getImagePatterns( WikiEngine engine )
{
Properties props = engine.getWikiProperties();
ArrayList ptrnlist = new ArrayList();
for( Enumeration e = props.propertyNames(); e.hasMoreElements(); )
{
String name = (String) e.nextElement();
if( name.startsWith( PROP_INLINEIMAGEPTRN ) )
{
String ptrn = props.getProperty( name );
ptrnlist.add( ptrn );
}
}
if( ptrnlist.size() == 0 )
{
ptrnlist.add( DEFAULT_INLINEPATTERN );
}
return ptrnlist;
}
/**
* Returns link name, if it exists; otherwise it returns null.
*/
private String linkExists( String page )
{
try
{
if( page == null || page.length() == 0 ) return null;
return m_engine.getFinalPageName( page );
}
catch( ProviderException e )
{
log.warn("TranslatorReader got a faulty page name!",e);
return page; // FIXME: What would be the correct way to go back?
}
}
/**
* Calls a transmutator chain.
*
* @param list Chain to call
* @param text Text that should be passed to the mutate() method
* of each of the mutators in the chain.
* @return The result of the mutation.
*/
private String callMutatorChain( Collection list, String text )
{
if( list == null || list.size() == 0 )
{
return text;
}
for( Iterator i = list.iterator(); i.hasNext(); )
{
StringTransmutator m = (StringTransmutator) i.next();
text = m.mutate( m_context, text );
}
return text;
}
private void callHeadingListenerChain( Heading param )
{
List list = m_headingListenerChain;
for( Iterator i = list.iterator(); i.hasNext(); )
{
HeadingListener h = (HeadingListener) i.next();
h.headingAdded( m_context, param );
}
}
private Element makeLink( int type, String link, String text, String section )
{
Element el = null;
if( text == null ) text = link;
text = callMutatorChain( m_linkMutators, text );
section = (section != null) ? ("#"+section) : "";
// Make sure we make a link name that can be accepted
// as a valid URL.
String encodedlink = m_engine.encodeName( link );
if( encodedlink.length() == 0 )
{
type = EMPTY;
}
switch(type)
{
case READ:
el = new Element("a").setAttribute("class", "wikipage");
el.setAttribute("href",m_context.getURL(WikiContext.VIEW, link)+section);
el.addContent(text);
break;
case EDIT:
el = new Element("a").setAttribute("class", "editpage");
el.setAttribute("title","Create '"+link+"'");
el.setAttribute("href", m_context.getURL(WikiContext.EDIT,link));
el.addContent(text);
break;
case EMPTY:
el = new Element("u").addContent(text);
break;
// These two are for local references - footnotes and
// references to footnotes.
// We embed the page name (or whatever WikiContext gives us)
// to make sure the links are unique across Wiki.
case LOCALREF:
el = new Element("a").setAttribute("class","footnoteref");
el.setAttribute("href","#ref-"+m_context.getPage().getName()+"-"+link);
el.addContent("["+text+"]");
break;
case LOCAL:
el = new Element("a").setAttribute("class","footnote");
el.setAttribute("name", "ref-"+m_context.getPage().getName()+"-"+link.substring(1));
el.addContent("["+text+"]");
break;
// With the image, external and interwiki types we need to
// make sure nobody can put in Javascript or something else
// annoying into the links themselves. We do this by preventing
// a haxor from stopping the link name short with quotes in
// fillBuffer().
case IMAGE:
el = new Element("img").setAttribute("class","inline");
el.setAttribute("src",link);
el.setAttribute("alt",text);
break;
case IMAGELINK:
el = new Element("img").setAttribute("class","inline");
el.setAttribute("src",link);
el.setAttribute("alt",text);
el = new Element("a").setAttribute("href",text).addContent(el);
break;
case IMAGEWIKILINK:
String pagelink = m_context.getURL(WikiContext.VIEW,text);
el = new Element("img").setAttribute("class","inline");
el.setAttribute("src",link);
el.setAttribute("alt",text);
el = new Element("a").setAttribute("class","wikipage").setAttribute("href",pagelink).addContent(el);
break;
case EXTERNAL:
el = new Element("a").setAttribute("class","external");
if( m_useRelNofollow ) el.setAttribute("rel","nofollow");
el.setAttribute("href",link+section);
el.addContent(text);
break;
case INTERWIKI:
el = new Element("a").setAttribute("class","interwiki");
el.setAttribute("href",link+section);
el.addContent(text);
break;
case ATTACHMENT:
String attlink = m_context.getURL( WikiContext.ATTACH,
link );
String infolink = m_context.getURL( WikiContext.INFO,
link );
String imglink = m_context.getURL( WikiContext.NONE,
"images/attachment_small.png" );
el = new Element("a").setAttribute("class","attachment");
el.setAttribute("href",attlink);
el.addContent(text);
pushElement(el);
popElement(el.getName());
el = new Element("img").setAttribute("src",imglink);
el.setAttribute("border","0");
el.setAttribute("alt","(info)");
el = new Element("a").setAttribute("href",infolink).addContent(el);
break;
default:
break;
}
if( el != null )
{
flushPlainText();
m_currentElement.addContent( el );
}
return el;
}
/**
* Figures out if a link is an off-site link. This recognizes
* the most common protocols by checking how it starts.
*/
private boolean isExternalLink( String link )
{
int idx = Arrays.binarySearch( c_externalLinks, link,
c_startingComparator );
// We need to check here once again; otherwise we might
// get a match for something like "h".
if( idx >= 0 && link.startsWith(c_externalLinks[idx]) ) return true;
return false;
}
/**
* Returns true, if the link in question is an access
* rule.
*/
private static boolean isAccessRule( String link )
{
return link.startsWith("{ALLOW") || link.startsWith("{DENY");
}
/**
* Matches the given link to the list of image name patterns
* to determine whether it should be treated as an inline image
* or not.
*/
private boolean isImageLink( String link )
{
if( m_inlineImages )
{
for( Iterator i = m_inlineImagePatterns.iterator(); i.hasNext(); )
{
if( m_inlineMatcher.matches( link, (Pattern) i.next() ) )
return true;
}
}
return false;
}
private static boolean isMetadata( String link )
{
return link.startsWith("{SET");
}
/**
* Returns true, if the argument contains a number, otherwise false.
* In a quick test this is roughly the same speed as Integer.parseInt()
* if the argument is a number, and roughly ten times the speed, if
* the argument is NOT a number.
*/
private boolean isNumber( String s )
{
if( s == null ) return false;
if( s.length() > 1 && s.charAt(0) == '-' )
s = s.substring(1);
for( int i = 0; i < s.length(); i++ )
{
if( !Character.isDigit(s.charAt(i)) )
return false;
}
return true;
}
/**
* This method peeks ahead in the stream until EOL and returns the result.
* It will keep the buffers untouched.
*
* @return The string from the current position to the end of line.
*/
// FIXME: Always returns an empty line, even if the stream is full.
private String peekAheadLine()
throws IOException
{
String s = readUntilEOL().toString();
pushBack( s );
return s;
}
/**
* Writes HTML for error message.
*/
public static Element makeError( String error )
{
return new Element("span").setAttribute("class","error").addContent(error);
}
private void flushPlainText()
{
if( m_plainTextBuf.length() > 0 )
{
// We must first empty the buffer because the side effect of
// calling makeCamelCaseLink() is to call this routine.
String buf = m_plainTextBuf.toString();
m_plainTextBuf = new StringBuffer();
// If there might be HTML in it, disable the output escaping
// process here (yes, this does increase the DOM tree quite a lot,
// if you allow HTML.)
if( m_allowHTML )
{
m_currentElement.addContent( new ProcessingInstruction( Result.PI_DISABLE_OUTPUT_ESCAPING, "" ));
}
if( m_camelCaseLinks && !m_isEscaping )
{
// System.out.println("Buffer="+buf);
while( m_camelCaseMatcher.contains( buf, m_camelCasePattern ) )
{
MatchResult result = m_camelCaseMatcher.getMatch();
String firstPart = buf.substring(0,result.beginOffset(0));
String prefix = result.group(1);
if( prefix == null ) prefix = "";
String camelCase = result.group(2);
String protocol = result.group(3);
String uri = protocol+result.group(4);
buf = buf.substring(result.endOffset(0));
m_currentElement.addContent( firstPart );
// Check if the user does not wish to do URL or WikiWord expansion
if( prefix.endsWith("~") || prefix.indexOf('[') != -1 )
{
if( prefix.endsWith("~") ) prefix = prefix.substring(0,prefix.length()-1);
if( camelCase != null )
{
m_currentElement.addContent( prefix+camelCase );
}
else if( protocol != null )
{
m_currentElement.addContent( prefix+uri );
}
continue;
}
// Fine, then let's check what kind of a link this was
// and emit the proper elements
if( protocol != null )
{
char c = uri.charAt(uri.length()-1);
if( c == '.' || c == ',' )
{
uri = uri.substring(0,uri.length()-1);
buf = c + buf;
}
// System.out.println("URI match "+uri);
m_currentElement.addContent( prefix );
makeDirectURILink( uri );
}
else
{
// System.out.println("Matched: '"+camelCase+"'");
// System.out.println("Split to '"+firstPart+"', and '"+buf+"'");
// System.out.println("prefix="+prefix);
m_currentElement.addContent( prefix );
makeCamelCaseLink( camelCase );
}
}
m_currentElement.addContent( buf );
}
else
{
// No camelcase asked for, just add the elements
m_currentElement.addContent( buf );
}
}
}
private Element pushElement( Element e )
{
flushPlainText();
m_currentElement.addContent( e );
m_currentElement = e;
return e;
}
private Element addElement( Content e )
{
if( e != null )
{
flushPlainText();
m_currentElement.addContent( e );
}
return m_currentElement;
}
private Element popElement( String s )
{
flushPlainText();
Element currEl = m_currentElement;
while( currEl.getParentElement() != null )
{
if( currEl.getName().equals(s) && !currEl.isRootElement() )
{
m_currentElement = currEl.getParentElement();
return m_currentElement;
}
currEl = currEl.getParentElement();
}
return m_currentElement;
}
/**
* Reads the stream until it meets one of the specified
* ending characters, or stream end. The ending character will be left
* in the stream.
*/
private String readUntil( String endChars )
throws IOException
{
StringBuffer sb = new StringBuffer();
int ch = nextToken();
while( ch != -1 )
{
if( ch == '\\' )
{
ch = nextToken();
if( ch == -1 )
{
break;
}
}
else
{
if( endChars.indexOf((char)ch) != -1 )
{
pushBack( ch );
break;
}
}
sb.append( (char) ch );
ch = nextToken();
}
return sb.toString();
}
/**
* Reads the stream while the characters that have been specified are
* in the stream, returning then the result as a String.
*/
private String readWhile( String endChars )
throws IOException
{
StringBuffer sb = new StringBuffer();
int ch = nextToken();
while( ch != -1 )
{
if( endChars.indexOf((char)ch) == -1 )
{
pushBack( ch );
break;
}
sb.append( (char) ch );
ch = nextToken();
}
return sb.toString();
}
private JSPWikiMarkupParser m_cleanTranslator;
/**
* Does a lazy init. Otherwise, we would get into a situation
* where HTMLRenderer would try and boot a TranslatorReader before
* the TranslatorReader it is contained by is up.
*/
private JSPWikiMarkupParser getCleanTranslator()
{
if( m_cleanTranslator == null )
{
WikiContext dummyContext = new WikiContext( m_engine,
m_context.getPage() );
m_cleanTranslator = new JSPWikiMarkupParser( dummyContext, null );
m_cleanTranslator.m_allowHTML = true;
}
return m_cleanTranslator;
}
/**
* Modifies the "hd" parameter to contain proper values. Because
* an "id" tag may only contain [a-zA-Z0-9:_-], we'll replace the
* % after url encoding with '_'.
*/
private String makeHeadingAnchor( String baseName, String title, Heading hd )
{
hd.m_titleText = title;
title = MarkupParser.cleanLink( title );
hd.m_titleSection = m_engine.encodeName(title);
hd.m_titleAnchor = "section-"+m_engine.encodeName(baseName)+
"-"+hd.m_titleSection;
hd.m_titleAnchor = hd.m_titleAnchor.replace( '%', '_' );
return hd.m_titleAnchor;
}
private String makeSectionTitle( String title )
{
title = title.trim();
String outTitle;
try
{
JSPWikiMarkupParser dtr = getCleanTranslator();
dtr.setInputReader( new StringReader(title) );
CleanTextRenderer ctt = new CleanTextRenderer(m_context, dtr.parse());
outTitle = ctt.getString();
}
catch( IOException e )
{
log.fatal("CleanTranslator not working", e);
throw new InternalWikiException("CleanTranslator not working as expected, when cleaning title"+ e.getMessage() );
}
return outTitle;
}
/**
* Returns XHTML for the start of the heading. Also sets the
* line-end emitter.
* @param level
* @param headings A List to which heading should be added.
*/
public Element makeHeading( int level, String title, Heading hd )
{
Element el = null;
String pageName = m_context.getPage().getName();
String outTitle = makeSectionTitle( title );
hd.m_level = level;
switch( level )
{
case Heading.HEADING_SMALL:
el = new Element("h4").setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd ));
break;
case Heading.HEADING_MEDIUM:
el = new Element("h3").setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd ));
break;
case Heading.HEADING_LARGE:
el = new Element("h2").setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd ));
break;
}
return el;
}
/**
* When given a link to a WikiName, we just return
* a proper HTML link for it. The local link mutator
* chain is also called.
*/
private Element makeCamelCaseLink( String wikiname )
{
String matchedLink;
callMutatorChain( m_localLinkMutatorChain, wikiname );
if( (matchedLink = linkExists( wikiname )) != null )
{
makeLink( READ, matchedLink, wikiname, null );
}
else
{
makeLink( EDIT, wikiname, wikiname, null );
}
return m_currentElement;
}
private Element outlinkImage()
{
Element el = null;
if( m_useOutlinkImage )
{
el = new Element("img").setAttribute("class", "outlink");
el.setAttribute( "src", m_context.getURL( WikiContext.NONE,"images/out.png" ) );
el.setAttribute("alt","");
}
return el;
}
private Element makeDirectURILink( String url )
{
Element result;
String last = null;
if( url.endsWith(",") || url.endsWith(".") )
{
last = url.substring( url.length()-1 );
url = url.substring( 0, url.length()-1 );
}
callMutatorChain( m_externalLinkMutatorChain, url );
if( isImageLink( url ) )
{
result = handleImageLink( url, url, false );
}
else
{
result = makeLink( EXTERNAL, url, url,null );
addElement( outlinkImage() );
}
if( last != null )
m_plainTextBuf.append(last);
return result;
}
/**
* Image links are handled differently:
* 1. If the text is a WikiName of an existing page,
* it gets linked.
* 2. If the text is an external link, then it is inlined.
* 3. Otherwise it becomes an ALT text.
*
* @param reallink The link to the image.
* @param link Link text portion, may be a link to somewhere else.
* @param hasLinkText If true, then the defined link had a link text available.
* This means that the link text may be a link to a wiki page,
* or an external resource.
*/
// FIXME: isExternalLink() is called twice.
private Element handleImageLink( String reallink, String link, boolean hasLinkText )
{
String possiblePage = MarkupParser.cleanLink( link );
String matchedLink;
if( isExternalLink( link ) && hasLinkText )
{
return makeLink( IMAGELINK, reallink, link, null );
}
else if( (matchedLink = linkExists( possiblePage )) != null &&
hasLinkText )
{
// System.out.println("Orig="+link+", Matched: "+matchedLink);
callMutatorChain( m_localLinkMutatorChain, possiblePage );
return makeLink( IMAGEWIKILINK, reallink, link, null );
}
else
{
return makeLink( IMAGE, reallink, link, null );
}
}
private Element handleAccessRule( String ruleLine )
{
if( !m_parseAccessRules ) return m_currentElement;
Acl acl;
WikiPage page = m_context.getPage();
// UserDatabase db = m_context.getEngine().getUserDatabase();
if( ruleLine.startsWith( "{" ) )
ruleLine = ruleLine.substring( 1 );
if( ruleLine.endsWith( "}" ) )
ruleLine = ruleLine.substring( 0, ruleLine.length() - 1 );
log.debug("page="+page.getName()+", ACL = "+ruleLine);
try
{
acl = m_engine.getAclManager().parseAcl( page, ruleLine );
page.setAcl( acl );
log.debug( acl.toString() );
}
catch( WikiSecurityException wse )
{
return makeError( wse.getMessage() );
}
return m_currentElement;
}
/**
* Handles metadata setting [{SET foo=bar}]
*/
private Element handleMetadata( String link )
{
try
{
String args = link.substring( link.indexOf(' '), link.length()-1 );
String name = args.substring( 0, args.indexOf('=') );
String val = args.substring( args.indexOf('=')+1, args.length() );
name = name.trim();
val = val.trim();
if( val.startsWith("'") ) val = val.substring( 1 );
if( val.endsWith("'") ) val = val.substring( 0, val.length()-1 );
// log.debug("SET name='"+name+"', value='"+val+"'.");
if( name.length() > 0 && val.length() > 0 )
{
val = m_engine.getVariableManager().expandVariables( m_context,
val );
m_context.getPage().setAttribute( name, val );
}
}
catch( Exception e )
{
return makeError(" Invalid SET found: "+link);
}
return m_currentElement;
}
/**
* Gobbles up all hyperlinks that are encased in square brackets.
*/
private Element handleHyperlinks( String link )
{
StringBuffer sb = new StringBuffer();
String reallink;
int cutpoint;
if( isAccessRule( link ) )
{
return handleAccessRule( link );
}
if( isMetadata( link ) )
{
return handleMetadata( link );
}
if( PluginManager.isPluginLink( link ) )
{
try
{
Content pluginContent = m_engine.getPluginManager().parsePluginLine( m_context, link );
addElement( new ProcessingInstruction(Result.PI_DISABLE_OUTPUT_ESCAPING, "") );
addElement( pluginContent );
addElement( new ProcessingInstruction(Result.PI_ENABLE_OUTPUT_ESCAPING, "") );
}
catch( PluginException e )
{
log.info( "Failed to insert plugin", e );
log.info( "Root cause:",e.getRootThrowable() );
return addElement( makeError("Plugin insertion failed: "+e.getMessage()) );
}
return m_currentElement;
}
// link = TextUtil.replaceEntities( link );
if( (cutpoint = link.indexOf('|')) != -1 )
{
reallink = link.substring( cutpoint+1 ).trim();
link = link.substring( 0, cutpoint );
}
else
{
reallink = link.trim();
}
int interwikipoint = -1;
// Yes, we now have the components separated.
// link = the text the link should have
// reallink = the url or page name.
// In many cases these are the same. [link|reallink].
if( VariableManager.isVariableLink( link ) )
{
Content el = new VariableContent(link);
addElement( new ProcessingInstruction(Result.PI_DISABLE_OUTPUT_ESCAPING, "") );
addElement( el );
addElement( new ProcessingInstruction(Result.PI_ENABLE_OUTPUT_ESCAPING, "") );
}
else if( isExternalLink( reallink ) )
{
// It's an external link, out of this Wiki
callMutatorChain( m_externalLinkMutatorChain, reallink );
if( isImageLink( reallink ) )
{
handleImageLink( reallink, link, (cutpoint != -1) );
}
else
{
makeLink( EXTERNAL, reallink, link, null );
addElement( outlinkImage() );
}
}
else if( (interwikipoint = reallink.indexOf(":")) != -1 )
{
// It's an interwiki link
// InterWiki links also get added to external link chain
// after the links have been resolved.
// FIXME: There is an interesting issue here: We probably should
// URLEncode the wikiPage, but we can't since some of the
// Wikis use slashes (/), which won't survive URLEncoding.
// Besides, we don't know which character set the other Wiki
// is using, so you'll have to write the entire name as it appears
// in the URL. Bugger.
String extWiki = reallink.substring( 0, interwikipoint );
String wikiPage = reallink.substring( interwikipoint+1 );
String urlReference = m_engine.getInterWikiURL( extWiki );
if( urlReference != null )
{
urlReference = TextUtil.replaceString( urlReference, "%s", wikiPage );
callMutatorChain( m_externalLinkMutatorChain, urlReference );
makeLink( INTERWIKI, urlReference, link, null );
if( isExternalLink(urlReference) )
{
addElement( outlinkImage() );
}
}
else
{
addElement( makeError("No InterWiki reference defined in properties for Wiki called '"+extWiki+"'!)") );
}
}
else if( reallink.startsWith("
{
// It defines a local footnote
makeLink( LOCAL, reallink, link, null );
}
else if( isNumber( reallink ) )
{
// It defines a reference to a local footnote
makeLink( LOCALREF, reallink, link, null );
}
else
{
int hashMark = -1;
// Internal wiki link, but is it an attachment link?
String attachment = findAttachment( reallink );
if( attachment != null )
{
callMutatorChain( m_attachmentLinkMutatorChain, attachment );
if( isImageLink( reallink ) )
{
attachment = m_context.getURL( WikiContext.ATTACH, attachment );
sb.append( handleImageLink( attachment, link, (cutpoint != -1) ) );
}
else
{
makeLink( ATTACHMENT, attachment, link, null );
}
}
else if( (hashMark = reallink.indexOf('
{
// It's an internal Wiki link, but to a named section
String namedSection = reallink.substring( hashMark+1 );
reallink = reallink.substring( 0, hashMark );
reallink = MarkupParser.cleanLink( reallink );
callMutatorChain( m_localLinkMutatorChain, reallink );
String matchedLink;
if( (matchedLink = linkExists( reallink )) != null )
{
String sectref = "section-"+m_engine.encodeName(matchedLink)+"-"+namedSection;
sectref = sectref.replace('%', '_');
makeLink( READ, matchedLink, link, sectref );
}
else
{
makeLink( EDIT, reallink, link, null );
}
}
else
{
// It's an internal Wiki link
reallink = MarkupParser.cleanLink( reallink );
callMutatorChain( m_localLinkMutatorChain, reallink );
String matchedLink = linkExists( reallink );
if( matchedLink != null )
{
makeLink( READ, matchedLink, link, null );
}
else
{
makeLink( EDIT, reallink, link, null );
}
}
}
return m_currentElement;
}
private String findAttachment( String link )
{
AttachmentManager mgr = m_engine.getAttachmentManager();
Attachment att = null;
try
{
att = mgr.getAttachmentInfo( m_context, link );
}
catch( ProviderException e )
{
log.warn("Finding attachments failed: ",e);
return null;
}
if( att != null )
{
return att.getName();
}
else if( link.indexOf('/') != -1 )
{
return link;
}
return null;
}
private int nextToken()
throws IOException
{
if( m_in == null ) return -1;
return m_in.read();
}
/**
* Push back any character to the current input. Does not
* push back a read EOF, though.
*/
private void pushBack( int c )
throws IOException
{
if( c != -1 && m_in != null )
{
m_in.unread( c );
}
}
/**
* Pushes back any string that has been read. It will obviously
* be pushed back in a reverse order.
*
* @since 2.1.77
*/
private void pushBack( String s )
throws IOException
{
for( int i = s.length()-1; i >= 0; i
{
pushBack( s.charAt(i) );
}
}
private Element handleBackslash()
throws IOException
{
int ch = nextToken();
if( ch == '\\' )
{
int ch2 = nextToken();
if( ch2 == '\\' )
{
pushElement( new Element("br").setAttribute("clear","all"));
return popElement("br");
}
pushBack( ch2 );
pushElement( new Element("br") );
return popElement("br");
}
pushBack( ch );
return null;
}
private Element handleUnderscore()
throws IOException
{
int ch = nextToken();
Element el = null;
if( ch == '_' )
{
if( m_isbold )
{
el = popElement("b");
}
else
{
el = pushElement( new Element("b") );
}
m_isbold = !m_isbold;
}
else
{
pushBack( ch );
}
return el;
}
/**
* For example: italics.
*/
private Element handleApostrophe()
throws IOException
{
int ch = nextToken();
Element el = null;
if( ch == '\'' )
{
if( m_isitalic )
{
el = popElement("i");
}
else
{
el = pushElement( new Element("i") );
}
m_isitalic = !m_isitalic;
}
else
{
pushBack( ch );
}
return el;
}
private Element handleOpenbrace( boolean isBlock )
throws IOException
{
int ch = nextToken();
if( ch == '{' )
{
int ch2 = nextToken();
if( ch2 == '{' )
{
m_isPre = true;
m_isEscaping = true;
m_isPreBlock = isBlock;
if( isBlock )
{
startBlockLevel();
return pushElement( new Element("pre") );
}
return pushElement( new Element("span").setAttribute("style","font-family:monospace; whitespace:pre;") );
}
pushBack( ch2 );
return pushElement( new Element("tt") );
}
pushBack( ch );
return null;
}
/**
* Handles both }} and }}}
*/
private Element handleClosebrace()
throws IOException
{
int ch2 = nextToken();
if( ch2 == '}' )
{
int ch3 = nextToken();
if( ch3 == '}' )
{
if( m_isPre )
{
if( m_isPreBlock )
{
popElement( "pre" );
}
else
{
popElement( "span" );
}
m_isPre = false;
m_isEscaping = false;
return m_currentElement;
}
m_plainTextBuf.append("}}}");
return m_currentElement;
}
pushBack( ch3 );
if( !m_isEscaping )
{
return popElement("tt");
}
}
pushBack( ch2 );
return null;
}
private Element handleDash()
throws IOException
{
int ch = nextToken();
if( ch == '-' )
{
int ch2 = nextToken();
if( ch2 == '-' )
{
int ch3 = nextToken();
if( ch3 == '-' )
{
// Empty away all the rest of the dashes.
// Do not forget to return the first non-match back.
while( (ch = nextToken()) == '-' );
pushBack(ch);
startBlockLevel();
pushElement( new Element("hr") );
return popElement( "hr" );
}
pushBack( ch3 );
}
pushBack( ch2 );
}
pushBack( ch );
return null;
}
private Element handleHeading()
throws IOException
{
Element el = null;
int ch = nextToken();
Heading hd = new Heading();
if( ch == '!' )
{
int ch2 = nextToken();
if( ch2 == '!' )
{
String title = peekAheadLine();
el = makeHeading( Heading.HEADING_LARGE, title, hd);
}
else
{
pushBack( ch2 );
String title = peekAheadLine();
el = makeHeading( Heading.HEADING_MEDIUM, title, hd );
}
}
else
{
pushBack( ch );
String title = peekAheadLine();
el = makeHeading( Heading.HEADING_SMALL, title, hd );
}
callHeadingListenerChain( hd );
if( el != null ) pushElement(el);
return el;
}
/**
* Reads the stream until the next EOL or EOF. Note that it will also read the
* EOL from the stream.
*/
private StringBuffer readUntilEOL()
throws IOException
{
int ch;
StringBuffer buf = new StringBuffer();
while( true )
{
ch = nextToken();
if( ch == -1 )
break;
buf.append( (char) ch );
if( ch == '\n' )
break;
}
return buf;
}
/**
* Starts a block level element, therefore closing the
* a potential open paragraph tag.
*/
private void startBlockLevel()
{
popElement("i"); m_isitalic = false;
popElement("b"); m_isbold = false;
popElement("tt");
if( m_isOpenParagraph )
{
m_isOpenParagraph = false;
popElement("p");
m_plainTextBuf.append("\n"); // Just small beautification
}
}
private static String getListType( char c )
{
if( c == '*' )
{
return "ul";
}
else if( c == '
{
return "ol";
}
throw new InternalWikiException("Parser got faulty list type: "+c);
}
/**
* Like original handleOrderedList() and handleUnorderedList()
* however handles both ordered ('#') and unordered ('*') mixed together.
*/
// FIXME: Refactor this; it's a bit messy.
private Element handleGeneralList()
throws IOException
{
startBlockLevel();
String strBullets = readWhile( "*
// String strBulletsRaw = strBullets; // to know what was original before phpwiki style substitution
int numBullets = strBullets.length();
// override the beginning portion of bullet pattern to be like the previous
// to simulate PHPWiki style lists
if(m_allowPHPWikiStyleLists)
{
// only substitute if different
if(!( strBullets.substring(0,Math.min(numBullets,m_genlistlevel)).equals
(m_genlistBulletBuffer.substring(0,Math.min(numBullets,m_genlistlevel)) ) ) )
{
if(numBullets <= m_genlistlevel)
{
// Substitute all but the last character (keep the expressed bullet preference)
strBullets = (numBullets > 1 ? m_genlistBulletBuffer.substring(0, numBullets-1) : "")
+ strBullets.substring(numBullets-1, numBullets);
}
else
{
strBullets = m_genlistBulletBuffer + strBullets.substring(m_genlistlevel, numBullets);
}
}
}
// Check if this is still of the same type
if( strBullets.substring(0,Math.min(numBullets,m_genlistlevel)).equals
(m_genlistBulletBuffer.substring(0,Math.min(numBullets,m_genlistlevel)) ) )
{
if( numBullets > m_genlistlevel )
{
pushElement( new Element( getListType(strBullets.charAt(m_genlistlevel++) ) ) );
// buf.append( m_renderer.openList(strBullets.charAt(m_genlistlevel++)) );
for( ; m_genlistlevel < numBullets; m_genlistlevel++ )
{
// bullets are growing, get from new bullet list
pushElement( new Element("li") );
// buf.append( m_renderer.openListItem() );
pushElement( new Element( getListType(strBullets.charAt(m_genlistlevel)) ));
// buf.append( m_renderer.openList(strBullets.charAt(m_genlistlevel)) );
}
}
else if( numBullets < m_genlistlevel )
{
// Close the previous list item.
// buf.append( m_renderer.closeListItem() );
popElement( "li" );
for( ; m_genlistlevel > numBullets; m_genlistlevel
{
// bullets are shrinking, get from old bullet list
// buf.append( m_renderer.closeList(m_genlistBulletBuffer.charAt(m_genlistlevel - 1)) );
popElement( getListType(m_genlistBulletBuffer.charAt(m_genlistlevel-1)) );
if( m_genlistlevel > 0 )
{
// buf.append( m_renderer.closeListItem() );
popElement( "li" );
}
}
}
else
{
if( m_genlistlevel > 0 )
{
popElement( "li" );
// buf.append( m_renderer.closeListItem() );
}
}
}
else
{
// The pattern has changed, unwind and restart
int numEqualBullets;
int numCheckBullets;
// find out how much is the same
numEqualBullets = 0;
numCheckBullets = Math.min(numBullets,m_genlistlevel);
while( numEqualBullets < numCheckBullets )
{
// if the bullets are equal so far, keep going
if( strBullets.charAt(numEqualBullets) == m_genlistBulletBuffer.charAt(numEqualBullets))
numEqualBullets++;
// otherwise giveup, we have found how many are equal
else
break;
}
//unwind
for( ; m_genlistlevel > numEqualBullets; m_genlistlevel
{
popElement( getListType( m_genlistBulletBuffer.charAt(m_genlistlevel-1) ) );
// buf.append( m_renderer.closeList( m_genlistBulletBuffer.charAt(m_genlistlevel - 1) ) );
if( m_genlistlevel > 0 )
{
//buf.append( m_renderer.closeListItem() );
popElement("li");
}
}
//rewind
// buf.append( m_renderer.openList( strBullets.charAt(numEqualBullets++) ) );
pushElement( new Element(getListType( strBullets.charAt(numEqualBullets++) ) ) );
for(int i = numEqualBullets; i < numBullets; i++)
{
pushElement( new Element("li") );
pushElement( new Element( getListType( strBullets.charAt(i) ) ) );
// buf.append( m_renderer.openListItem() );
// buf.append( m_renderer.openList( strBullets.charAt(i) ) );
}
m_genlistlevel = numBullets;
}
//buf.append( m_renderer.openListItem() );
pushElement( new Element("li") );
// work done, remember the new bullet list (in place of old one)
m_genlistBulletBuffer.setLength(0);
m_genlistBulletBuffer.append(strBullets);
return m_currentElement;
}
private Element unwindGeneralList()
{
//unwind
for( ; m_genlistlevel > 0; m_genlistlevel
{
popElement( "li" );
popElement( getListType(m_genlistBulletBuffer.charAt(m_genlistlevel-1)) );
}
m_genlistBulletBuffer.setLength(0);
return null;
}
private Element handleDefinitionList()
throws IOException
{
if( !m_isdefinition )
{
m_isdefinition = true;
startBlockLevel();
pushElement( new Element("dl") );
return pushElement( new Element("dt") );
}
return null;
}
private Element handleOpenbracket()
throws IOException
{
StringBuffer sb = new StringBuffer();
int ch;
boolean isPlugin = false;
while( (ch = nextToken()) == '[' )
{
sb.append( (char)ch );
}
if( ch == '{' )
{
isPlugin = true;
}
pushBack( ch );
if( sb.length() > 0 )
{
m_plainTextBuf.append( sb );
return m_currentElement;
}
// Find end of hyperlink
ch = nextToken();
while( ch != -1 )
{
if( ch == ']' && (!isPlugin || sb.charAt( sb.length()-1 ) == '}' ) )
{
break;
}
sb.append( (char) ch );
ch = nextToken();
}
// If the link is never finished, do some tricks to display the rest of the line
// unchanged.
if( ch == -1 )
{
log.debug("Warning: unterminated link detected!");
m_isEscaping = true;
m_plainTextBuf.append( sb );
flushPlainText();
m_isEscaping = false;
return m_currentElement;
}
return handleHyperlinks( sb.toString() );
}
/**
* Reads the stream until the current brace is closed or stream end.
*/
private String readBraceContent( char opening, char closing )
throws IOException
{
StringBuffer sb = new StringBuffer();
int braceLevel = 1;
int ch;
while(( ch = nextToken() ) != -1 )
{
if( ch == '\\' )
{
continue;
}
else if ( ch == opening )
{
braceLevel++;
}
else if ( ch == closing )
{
braceLevel
if (braceLevel==0)
{
break;
}
}
sb.append( (char)ch );
}
return sb.toString();
}
/**
* Handles constructs of type %%(style) and %%class
* @param newLine
* @return
* @throws IOException
*/
private Element handleDiv( boolean newLine )
throws IOException
{
int ch = nextToken();
Element el = null;
if( ch == '%' )
{
String style = null;
String clazz = null;
ch = nextToken();
// Style or class?
if( ch == '(' )
{
style = readBraceContent('(',')');
}
else if( Character.isLetter( (char) ch ) )
{
pushBack( ch );
clazz = readUntil( " \t\n\r" );
ch = nextToken();
// Pop out only spaces, so that the upcoming EOL check does not check the
// next line.
if( ch == '\n' || ch == '\r' )
{
pushBack(ch);
}
}
else
{
// Anything else stops.
pushBack(ch);
try
{
Boolean isSpan = (Boolean)m_styleStack.pop();
if( isSpan == null )
{
// Fail quietly
}
else if( isSpan.booleanValue() )
{
el = popElement( "span" );
}
else
{
el = popElement( "div" );
}
}
catch( EmptyStackException e )
{
log.debug("Page '"+m_context.getPage().getName()+"' closes a %%-block that has not been opened.");
return m_currentElement;
}
return el;
}
// Check if there is an attempt to do something nasty
style = StringEscapeUtils.unescapeHtml(style);
if( style != null && style.indexOf("javascript:") != -1 )
{
log.debug("Attempt to output javascript within CSS:"+style);
return addElement( makeError("Attempt to output javascript!") );
}
// Decide if we should open a div or a span?
String eol = peekAheadLine();
if( eol.trim().length() > 0 )
{
// There is stuff after the class
el = new Element("span");
m_styleStack.push( Boolean.TRUE );
}
else
{
startBlockLevel();
el = new Element("div");
m_styleStack.push( Boolean.FALSE );
}
if( style != null ) el.setAttribute("style", style);
if( clazz != null ) el.setAttribute("class", clazz );
el = pushElement( el );
return el;
}
pushBack(ch);
return el;
}
private Element handleBar( boolean newLine )
throws IOException
{
Element el = null;
if( !m_istable && !newLine )
{
return null;
}
if( newLine )
{
if( !m_istable )
{
startBlockLevel();
el = pushElement( new Element("table").setAttribute("class","wikitable").setAttribute("border","1") );
m_istable = true;
}
el = pushElement( new Element("tr") );
// m_closeTag = m_renderer.closeTableItem()+m_renderer.closeTableRow();
}
int ch = nextToken();
if( ch == '|' )
{
if( !newLine )
{
el = popElement("th");
}
el = pushElement( new Element("th") );
}
else
{
if( !newLine )
{
el = popElement("td");
}
el = pushElement( new Element("td") );
pushBack( ch );
}
return el;
}
/**
* Generic escape of next character or entity.
*/
private Element handleTilde()
throws IOException
{
int ch = nextToken();
if( ch == '|' || ch == '~' || ch == '\\' || ch == '*' || ch == '
ch == '-' || ch == '!' || ch == '\'' || ch == '_' || ch == '[' ||
ch == '{' || ch == ']' || ch == '}' || ch == '%' )
{
m_plainTextBuf.append( (char)ch );
m_plainTextBuf.append(readWhile( ""+(char)ch ));
return m_currentElement;
}
// No escape.
pushBack( ch );
return null;
}
private void fillBuffer( Element startElement )
throws IOException
{
m_currentElement = startElement;
boolean quitReading = false;
boolean newLine = true; // FIXME: not true if reading starts in middle of buffer
while(!quitReading)
{
int ch = nextToken();
String s = null;
Element el = null;
// Check if we're actually ending the preformatted mode.
// We still must do an entity transformation here.
if( m_isEscaping )
{
if( ch == '}' )
{
if( handleClosebrace() == null ) m_plainTextBuf.append( (char) ch );
}
else if( ch == -1 )
{
quitReading = true;
}
else if( ch == '\r' )
{
// DOS line feeds we ignore.
}
else
{
m_plainTextBuf.append( (char) ch );
}
continue;
}
// An empty line stops a list
if( newLine && ch != '*' && ch != '#' && ch != ' ' && m_genlistlevel > 0 )
{
m_plainTextBuf.append(unwindGeneralList());
}
if( newLine && ch != '|' && m_istable )
{
el = popElement("table");
m_istable = false;
}
// Now, check the incoming token.
switch( ch )
{
case '\r':
// DOS linefeeds we forget
continue;
case '\n':
// Close things like headings, etc.
// FIXME: This is not really very fast
popElement("dl"); // Close definition lists.
popElement("h2");
popElement("h3");
popElement("h4");
if( m_istable )
{
popElement("tr");
}
m_isdefinition = false;
if( newLine )
{
// Paragraph change.
startBlockLevel();
// Figure out which elements cannot be enclosed inside
// a <p></p> pair according to XHTML rules.
String nextLine = peekAheadLine();
if( nextLine.length() == 0 ||
(nextLine.length() > 0 &&
!nextLine.startsWith("{{{") &&
!nextLine.startsWith("
!nextLine.startsWith("%%") &&
"*#!;".indexOf( nextLine.charAt(0) ) == -1) )
{
pushElement( new Element("p") );
m_isOpenParagraph = true;
}
}
else
{
m_plainTextBuf.append("\n");
newLine = true;
}
continue;
case '\\':
el = handleBackslash();
break;
case '_':
el = handleUnderscore();
break;
case '\'':
el = handleApostrophe();
break;
case '{':
el = handleOpenbrace( newLine );
break;
case '}':
el = handleClosebrace();
break;
case '-':
if( newLine )
el = handleDash();
break;
case '!':
if( newLine )
{
el = handleHeading();
}
else
{
s = "!";
}
break;
case ';':
if( newLine )
{
el = handleDefinitionList();
}
break;
case ':':
if( m_isdefinition )
{
popElement("dt");
el = pushElement( new Element("dd") );
m_isdefinition = false;
}
break;
case '[':
el = handleOpenbracket();
break;
case '*':
if( newLine )
{
pushBack('*');
el = handleGeneralList();
}
break;
case '
if( newLine )
{
pushBack('
el = handleGeneralList();
}
break;
case '|':
el = handleBar( newLine );
break;
case '~':
el = handleTilde();
break;
case '%':
el = handleDiv( newLine );
break;
case -1:
quitReading = true;
continue;
}
// The idea is as follows: If the handler method returns
// an element (el != null), it is assumed that it has been
// added in the stack. Otherwise the character is added
// as is to the plaintext buffer.
// For the transition phase, if s != null, it also gets
// added in the plaintext buffer.
if( el != null )
{
newLine = false;
}
else
{
m_plainTextBuf.append( (char) ch );
newLine = false;
}
if( s != null )
{
m_plainTextBuf.append( s );
newLine = false;
}
}
popElement("domroot");
}
public WikiDocument parse()
throws IOException
{
WikiDocument d = new WikiDocument( m_context.getPage() );
Element rootElement = new Element("domroot");
d.setRootElement( rootElement );
try
{
fillBuffer( rootElement );
}
catch( IllegalDataException e )
{
log.error("Page "+m_context.getPage().getName()+" contained something that cannot be added in the DOM tree",e);
throw new IOException("Illegal page data: "+e.getMessage());
}
return d;
}
/**
* Compares two Strings, and if one starts with the other, then
* returns null. Otherwise just like the normal Comparator
* for strings.
*
* @author jalkanen
*
* @since
*/
private static class StartingComparator implements Comparator
{
public int compare( Object arg0, Object arg1 )
{
String s1 = (String)arg0;
String s2 = (String)arg1;
if( s1.length() > s2.length() )
{
if( s1.startsWith(s2) && s2.length() > 1 ) return 0;
}
else
{
if( s2.startsWith(s1) && s1.length() > 1 ) return 0;
}
return s1.compareTo( s2 );
}
}
}
|
package com.myleshosford.mysqlshell;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
/**
*
* @author Myles Hosford
*/
public class MySqlShell extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent t) {
Platform.exit();
System.exit(0);
}
});
stage.show();
}
}
|
package org.amc.game.chessserver;
import org.amc.game.chess.Player;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
import javax.annotation.Resource;
@Controller
@SessionAttributes({ "GAME_UUID", "PLAYER" })
@RequestMapping("/joinGame")
public class ServerJoinChessGameController {
private static final Logger logger = Logger.getLogger(ServerJoinChessGameController.class);
private Map<Long, ServerChessGame> gameMap;
@RequestMapping(method = RequestMethod.POST)
public ModelAndView joinGame(
@ModelAttribute("PLAYER") Player player, @RequestParam long gameUUID) {
ServerChessGame chessGame = gameMap.get(gameUUID);
ModelAndView mav = new ModelAndView();
if (canPlayerJoinGame(chessGame, player)) {
addPlayerToGame(chessGame, player);
setupModelForChessGameScreen(mav, gameUUID);
} else {
setModelErrorMessage(chessGame, player, mav);
}
return mav;
}
private boolean canPlayerJoinGame(ServerChessGame chessGame, Player player) {
return inAwaitingPlayerState(chessGame) && !isPlayerJoiningOwnGame(chessGame, player);
}
private void addPlayerToGame(ServerChessGame chessGame, Player player) {
chessGame.addOpponent(player);
}
private void setupModelForChessGameScreen(ModelAndView mav, long gameUUID) {
mav.getModel().put("GAME_UUID", gameUUID);
logger.info(String.format("Chess Game(%d): has been started", gameUUID));
mav.setViewName("chessGamePortal");
}
private void setModelErrorMessage(ServerChessGame chessGame, Player player, ModelAndView mav) {
if (!inAwaitingPlayerState(chessGame)) {
setErrorPageAndMessage(mav, "Can't join chess game");
} else if (isPlayerJoiningOwnGame(chessGame, player)) {
setErrorPageAndMessage(mav, "Player can't join a game they started");
}
}
private boolean inAwaitingPlayerState(ServerChessGame chessGame) {
return chessGame.getCurrentStatus().equals(ServerChessGame.status.AWAITING_PLAYER);
}
private boolean isPlayerJoiningOwnGame(ServerChessGame chessGame, Player player) {
return player.equals(chessGame.getPlayer());
}
private void setErrorPageAndMessage(ModelAndView mav, String errorMessage) {
mav.setViewName("forward:/app/chessgame/chessapplication");
mav.getModel().put("ERRORS", errorMessage);
}
/**
* Dependency Injection of Map containing current ChessGames
* @param gameMap Map<Log,ServerChessGame>
*/
@Resource(name="gameMap")
public void setGameMap(Map<Long, ServerChessGame> gameMap){
this.gameMap=gameMap;
}
/**
* Handles Exception raised when the required parameters are missing form the html response
* @param be MissingServletRequestParameterException
* @return ModelAndView redirect main page
*/
@ExceptionHandler(MissingServletRequestParameterException.class)
public ModelAndView handleMissingRequestParameter(MissingServletRequestParameterException be){
ModelAndView mav=new ModelAndView();
logger.error("MissingServletRequestParameterException:"+be.getMessage());
mav.getModel().put("ERRORS","Missing GAME Id");
mav.setViewName("redirect:/app/chessgame/chessapplication");
return mav;
}
/**
* Intercept HttpSessionRequiredExceptions and cause a redirect to chessGameApplication handler
*
* @param hsre HttpSessionRequiredException
* @return String redirect url
*/
@ExceptionHandler(HttpSessionRequiredException.class)
public String handleMissingSessionAttributes(HttpSessionRequiredException hsre){
logger.error("HttpSessionRequiredException:"+hsre.getMessage());
return "redirect:/app/chessgame/chessapplication";
}
}
|
package com.opencms.workplace;
import com.opencms.file.*;
import com.opencms.core.*;
import com.opencms.util.*;
import com.opencms.template.*;
import java.util.*;
import javax.servlet.http.*;
public class CmsTaskAction implements I_CmsConstants, I_CmsWpConstants, I_CmsLogChannels {
/**
* Constant for generating user javascriptlist
*/
private final static String C_ALL_ROLES = "___all";
/**
* Accepts a task.
* @param cms The cms-object.
* @param int taskid The id of the task.
* @exception CmsException Throws CmsExceptions, that are be
* thrown in calling methods.
*/
public static void accept(A_CmsObject cms, int taskid)
throws CmsException {
cms.acceptTask(taskid);
String comment = "";
cms.writeTaskLog(taskid, comment, C_TASKLOGTYPE_ACCEPTED);
// send an email if "Benachrichtigung bei Annahme" was selected.
CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms);
A_CmsTask task = cms.readTask(taskid);
if (cms.getTaskPar(task.getId(),C_TASKPARA_ACCEPTATION)!=null) {
StringBuffer contentBuf = new StringBuffer(lang.getLanguageValue("task.email.accept.content"));
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.project"));
contentBuf.append(": ");
String projectname = "?";
try {
projectname = cms.readTask(task.getRoot()).getName();
} catch(Exception exc) {
// no root?!
}
contentBuf.append(projectname);
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.task"));
contentBuf.append(": ");
contentBuf.append(task.getName());
int projectid=cms.readProject(task).getId();
String servletPath=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath();
String serverName=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServerName();
CmsXmlWpConfigFile conf=new CmsXmlWpConfigFile(cms);
String actionPath=conf.getWorkplaceActionPath();
contentBuf.append("\n\n\nhttp://"+serverName+servletPath+actionPath+"login.html?startTaskId="+taskid+"&startProjectId="+projectid);
String subject=lang.getLanguageValue("task.email.accept.subject");
A_CmsUser[] users={cms.readOwner(task)};
try {
CmsMail mail=new CmsMail(cms,cms.readAgent(task),users,subject,contentBuf.toString());
mail.start();
} catch( Exception exc ) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsTaskAction] error while sending mail " + exc.getMessage());
}
}
}
}
/**
* Takes a task. The calling user is now the agent for this task.
* @param cms The cms-object.
* @param int taskid The id of the task.
* @exception CmsException Throws CmsExceptions, that are be
* thrown in calling methods.
*/
public static void take(A_CmsObject cms, int taskid)
throws CmsException {
CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms);
A_CmsRequestContext context = cms.getRequestContext();
A_CmsTask task = cms.readTask(taskid);
A_CmsUser newEditor = context.currentUser();
A_CmsGroup oldRole = cms.readGroup(task);
// has the user the correct role?
if(cms.userInGroup(newEditor.getName(), oldRole.getName())) {
cms.forwardTask(taskid, oldRole.getName(), newEditor.getName());
String comment = lang.getLanguageValue("task.dialog.take.logmessage");
comment += " " + Utils.getFullName(newEditor);
cms.writeTaskLog(taskid, comment, C_TASKLOGTYPE_TAKE);
}
// send an email
StringBuffer contentBuf = new StringBuffer(lang.getLanguageValue("task.email.take.content"));
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.project"));
contentBuf.append(": ");
String projectname = "?";
try {
projectname = cms.readTask(task.getRoot()).getName();
} catch(Exception exc) {
// no root?!
}
contentBuf.append(projectname);
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.task"));
contentBuf.append(": ");
contentBuf.append(task.getName());
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.taskfor"));
contentBuf.append(": ");
contentBuf.append(Utils.getFullName(cms.readAgent(task)));
int projectid=cms.readProject(task).getId();
String servletPath=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath();
String serverName=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServerName();
CmsXmlWpConfigFile conf=new CmsXmlWpConfigFile(cms);
String actionPath=conf.getWorkplaceActionPath();
contentBuf.append("\n\n\nhttp://"+serverName+servletPath+actionPath+"login.html?startTaskId="+taskid+"&startProjectId="+projectid);
String subject=lang.getLanguageValue("task.email.take.subject");
A_CmsUser[] users={cms.readAgent(task)};
try {
CmsMail mail=new CmsMail(cms,cms.readOwner(task),users,subject,contentBuf.toString());
mail.start();
} catch( Exception exc ) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsTaskAction] error while sending mail " + exc.getMessage());
}
}
}
/**
* Forwards a task. The task is forwarded to a new editor in a new role.
* @param cms The cms-object.
* @param int taskid The id of the task.
* @param newEditorName The name of the new editor for this task.
* @param newRoleName The name of the new role for the user.
* @exception CmsException Throws CmsExceptions, that are be
* thrown in calling methods.
*/
public static void forward(A_CmsObject cms, int taskid,
String newEditorName, String newRoleName)
throws CmsException {
CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms);
A_CmsUser newEditor = cms.readUser(newEditorName);
A_CmsGroup oldRole = cms.readGroup(newRoleName);
cms.forwardTask(taskid, oldRole.getName(), newEditor.getName());
String comment = lang.getLanguageValue("task.dialog.forward.logmessage");
comment += " " + Utils.getFullName(newEditor);
cms.writeTaskLog(taskid, comment, C_TASKLOGTYPE_FORWARDED);
// send an email if "Benachrichtigung bei Weiterleitung" was selected.
A_CmsTask task = cms.readTask(taskid);
if (cms.getTaskPar(task.getId(),C_TASKPARA_DELIVERY)!=null) {
StringBuffer contentBuf = new StringBuffer(lang.getLanguageValue("task.email.forward.content"));
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.project"));
contentBuf.append(": ");
String projectname = "?";
try {
projectname = cms.readTask(task.getRoot()).getName();
} catch(Exception exc) {
// no root?!
}
contentBuf.append(projectname);
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.task"));
contentBuf.append(": ");
contentBuf.append(task.getName());
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.actuator"));
contentBuf.append(": ");
contentBuf.append(Utils.getFullName(cms.readOwner(task)));
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.taskfor"));
contentBuf.append(": ");
contentBuf.append(Utils.getFullName(cms.readOriginalAgent(task)));
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.editor"));
contentBuf.append(": ");
contentBuf.append(Utils.getFullName(cms.readAgent(task)));
int projectid=cms.readProject(task).getId();
String servletPath=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath();
String serverName=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServerName();
CmsXmlWpConfigFile conf=new CmsXmlWpConfigFile(cms);
String actionPath=conf.getWorkplaceActionPath();
contentBuf.append("\n\n\nhttp://"+serverName+servletPath+actionPath+"login.html?startTaskId="+taskid+"&startProjectId="+projectid);
String subject=lang.getLanguageValue("task.email.forward.subject");
// if "Alle Rollenmitglieder von Aufgabe Benachrichtigen" checkbox is selected.
if (cms.getTaskPar(task.getId(),C_TASKPARA_ALL)!=null) {
try {
CmsMail mail=new CmsMail(cms,cms.getRequestContext().currentUser(),cms.readGroup(task),subject,contentBuf.toString());
mail.start();
} catch( Exception exc ) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsTaskAction] error while sending mail " + exc.getMessage());
}
}
} else {
// send a mail to user
A_CmsUser[] user={cms.readAgent(task)};
try {
CmsMail mail1=new CmsMail(cms,cms.getRequestContext().currentUser(),user,subject,contentBuf.toString());
mail1.start();
} catch( Exception exc ) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsTaskAction] error while sending mail " + exc.getMessage());
}
}
// send a mail to owner
A_CmsUser[] owner={cms.readOwner(task)};
try {
CmsMail mail2=new CmsMail(cms,cms.getRequestContext().currentUser(),owner,subject,contentBuf.toString());
mail2.start();
} catch( Exception exc ) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsTaskAction] error while sending mail " + exc.getMessage());
}
}
}
}
}
/**
* Changes the timeou-date of the task.
* @param cms The cms-object.
* @param int taskid The id of the task.
* @param timeoutString The new timeout-date as a string in the following format:
* "dd.mm.yyyy"
* @exception CmsException Throws CmsExceptions, that are be
* thrown in calling methods.
*/
public static void due(A_CmsObject cms, int taskid,
String timeoutString)
throws CmsException {
CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms);
A_CmsTask task = cms.readTask(taskid);
String splittetDate[] = Utils.split(timeoutString, ".");
GregorianCalendar cal = new GregorianCalendar(Integer.parseInt(splittetDate[2]),
Integer.parseInt(splittetDate[1]) - 1,
Integer.parseInt(splittetDate[0]), 0, 0, 0);
long timeout = cal.getTime().getTime();
cms.setTimeout(taskid, timeout);
// add comment
String comment = "";
comment += lang.getLanguageValue("task.dialog.due.logmessage1") + " ";
comment += Utils.getNiceShortDate(task.getTimeOut().getTime()) + " ";
comment += lang.getLanguageValue("task.dialog.due.logmessage2") + " ";
comment += Utils.getNiceShortDate(timeout);
cms.writeTaskLog(taskid, comment, C_TASKLOGTYPE_DUECHANGED);
}
/**
* Changes the priority of a task.
* @param cms The cms-object.
* @param int taskid The id of the task.
* @param priorityString the new priority as String ("1" = high,
* "2" = normal or "3" = low)
* @exception CmsException Throws CmsExceptions, that are be
* thrown in calling methods.
*/
public static void priority(A_CmsObject cms, int taskid,
String priorityString)
throws CmsException {
CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms);
A_CmsTask task = cms.readTask(taskid);
int priority = Integer.parseInt(priorityString);
cms.setPriority(taskid, priority);
// add comment
String comment = "";
comment += lang.getLanguageValue("task.dialog.priority.logmessage1") + " ";
comment += lang.getLanguageValue("task.dialog.priority.logmessageprio" + task.getPriority() ) + " ";
comment += lang.getLanguageValue("task.dialog.priority.logmessage2") + " ";
comment += lang.getLanguageValue("task.dialog.priority.logmessageprio" + priority ) + " ";
cms.writeTaskLog(taskid, comment, C_TASKLOGTYPE_PRIORITYCHANGED);
}
/**
* Reaktivates a task.
* @param cms The cms-object.
* @param int taskid The id of the task.
* @param agentName The name of the new editor for this task.
* @param roleName The name of the new role for the user.
* @param taskName The new name of the task.
* @param taskcomment The new comment for this task.
* @param timeoutString The new timeout-date as a string in the following format:
* "dd.mm.yyyy"
* @param priorityString the new priority as String ("1" = high,
* "2" = normal or "3" = low)
* @param paraAcceptation controls if a message should be send by acceptation. ("checked" | "")
* @param paraAll controls if a message should be send to all users in a role. ("checked" | "")
* @param paraCompletion controls if a message should be send by completing this task. ("checked" | "")
* @param paraDelivery controls if a message should be send by delivering a task. ("checked" | "")
* @exception CmsException Throws CmsExceptions, that are be
* thrown in calling methods.
*/
public static void reakt(A_CmsObject cms, int taskid,
String agentName, String roleName, String taskName,
String taskcomment, String timeoutString,
String priorityString, String paraAcceptation,
String paraAll, String paraCompletion, String paraDelivery)
throws CmsException {
CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms);
A_CmsTask task = cms.readTask(taskid);
if( roleName.equals(C_ALL_ROLES) ) {
roleName = cms.readUser(agentName).getDefaultGroup().getName();
}
cms.setName(taskid, taskName);
// try to reaktivate the task
cms.reaktivateTask(taskid);
int priority = Integer.parseInt(priorityString);
cms.setPriority(taskid, priority);
// create a long from the overgiven date.
String splittetDate[] = Utils.split(timeoutString, ".");
GregorianCalendar cal = new GregorianCalendar(Integer.parseInt(splittetDate[2]),
Integer.parseInt(splittetDate[1]) - 1,
Integer.parseInt(splittetDate[0]), 0, 0, 0);
long timeout = cal.getTime().getTime();
cms.setTimeout(taskid, timeout);
cms.setTaskPar(taskid,C_TASKPARA_ACCEPTATION, paraAcceptation);
cms.setTaskPar(taskid,C_TASKPARA_ALL, paraAll);
cms.setTaskPar(taskid,C_TASKPARA_COMPLETION, paraCompletion);
cms.setTaskPar(taskid,C_TASKPARA_DELIVERY, paraDelivery);
cms.forwardTask(taskid, roleName, agentName);
String comment = lang.getLanguageValue("task.label.forrole") + ": " + roleName + "\n";
comment += lang.getLanguageValue("task.label.editor") + ": " + Utils.getFullName(cms.readUser(agentName)) + "\n";
comment += taskcomment;
cms.writeTaskLog(task.getId(), comment, C_TASKLOGTYPE_REACTIVATED);
// send an email
StringBuffer contentBuf = new StringBuffer(lang.getLanguageValue("task.email.reakt.content"));
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.project"));
contentBuf.append(": ");
String projectname = "?";
try {
projectname = cms.readTask(task.getRoot()).getName();
} catch(Exception exc) {
// no root?!
}
contentBuf.append(projectname);
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.task"));
contentBuf.append(": ");
contentBuf.append(task.getName());
int projectid=cms.readProject(task).getId();
String servletPath=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath();
String serverName=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServerName();
CmsXmlWpConfigFile conf=new CmsXmlWpConfigFile(cms);
String actionPath=conf.getWorkplaceActionPath();
contentBuf.append("\n\n\nhttp://"+serverName+servletPath+actionPath+"login.html?startTaskId="+taskid+"&startProjectId="+projectid);
String subject=lang.getLanguageValue("task.email.reakt.subject");
A_CmsUser[] users={cms.readAgent(task)};
CmsMail mail;
mail=new CmsMail(cms,cms.readOwner(task),users,subject,contentBuf.toString());
// if "Alle Rollenmitglieder von Aufgabe Benachrichtigen" checkbox is selected.
if (cms.getTaskPar(task.getId(),C_TASKPARA_ALL)!=null) {
mail=new CmsMail(cms,cms.readOwner(task),cms.readGroup(task),subject,contentBuf.toString());
}
try {
mail.start();
} catch( Exception exc ) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsTaskAction] error while sending mail " + exc.getMessage());
}
}
}
/**
* Ends a task.
* @param cms The cms-object.
* @param int taskid The id of the task.
* @exception CmsException Throws CmsExceptions, that are be
* thrown in calling methods.
*/
public static void end(A_CmsObject cms, int taskid)
throws CmsException {
cms.endTask(taskid);
String comment = "";
cms.writeTaskLog(taskid, comment, C_TASKLOGTYPE_OK);
// send an email if "Benachrichtigung bei Abhacken" was selected.
CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms);
A_CmsTask task = cms.readTask(taskid);
if (cms.getTaskPar(task.getId(),C_TASKPARA_COMPLETION)!=null) {
StringBuffer contentBuf = new StringBuffer(lang.getLanguageValue("task.email.end.content"));
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.project"));
contentBuf.append(": ");
String projectname = "?";
try {
projectname = cms.readTask(task.getRoot()).getName();
} catch(Exception exc) {
// no root?!
}
contentBuf.append(projectname);
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.task"));
contentBuf.append(": ");
contentBuf.append(task.getName());
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.taskfor"));
contentBuf.append(": ");
contentBuf.append(Utils.getFullName(cms.readOriginalAgent(task)));
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.editor"));
contentBuf.append(": ");
contentBuf.append(Utils.getFullName(cms.readAgent(task)));
int projectid=cms.readProject(task).getId();
String servletPath=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath();
String serverName=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServerName();
CmsXmlWpConfigFile conf=new CmsXmlWpConfigFile(cms);
String actionPath=conf.getWorkplaceActionPath();
contentBuf.append("\n\n\nhttp://"+serverName+servletPath+actionPath+"login.html?startTaskId="+taskid+"&startProjectId="+projectid);
String subject=lang.getLanguageValue("task.email.end.subject");
A_CmsUser[] users={cms.readOwner(task)};
try {
CmsMail mail=new CmsMail(cms,cms.readAgent(task),users,subject,contentBuf.toString());
mail.start();
} catch( Exception exc ) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsTaskAction] error while sending mail " + exc.getMessage());
}
}
}
}
/**
* Sends a message to the editor of the task.
* @param cms The cms-object.
* @param int taskid The id of the task.
* @param message The text of the message.
* @exception CmsException Throws CmsExceptions, that are be
* thrown in calling methods.
*/
public static void message(A_CmsObject cms, int taskid, String message)
throws CmsException {
CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms);
A_CmsTask task = cms.readTask(taskid);
String comment = lang.getLanguageValue("task.dialog.message.head") + " ";
if( (message != null) && (message.length() != 0)) {
comment += Utils.getFullName(cms.readAgent(task)) + "\n";
comment += message;
cms.writeTaskLog(taskid, comment, C_TASKLOGTYPE_CALL);
}
// send an email
StringBuffer contentBuf = new StringBuffer(lang.getLanguageValue("task.email.message.content"));
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.project"));
contentBuf.append(": ");
String projectname = "?";
try {
projectname = cms.readTask(task.getRoot()).getName();
} catch(Exception exc) {
// no root?!
}
contentBuf.append(projectname);
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.task"));
contentBuf.append(": ");
contentBuf.append(task.getName());
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.actuator"));
contentBuf.append(": ");
contentBuf.append(Utils.getFullName(cms.readOwner(task)));
int projectid=cms.readProject(task).getId();
String servletPath=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath();
String serverName=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServerName();
CmsXmlWpConfigFile conf=new CmsXmlWpConfigFile(cms);
String actionPath=conf.getWorkplaceActionPath();
contentBuf.append("\n\n\nhttp://"+serverName+servletPath+actionPath+"login.html?startTaskId="+taskid+"&startProjectId="+projectid);
String subject=lang.getLanguageValue("task.email.message.subject");
A_CmsUser[] users={cms.readAgent(task)};
try {
CmsMail mail=new CmsMail(cms,cms.readOwner(task),users,subject,contentBuf.toString());
mail.start();
} catch( Exception exc ) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsTaskAction] error while sending mail " + exc.getMessage());
}
}
}
/**
* Sends a message to the initiator (owner) of the task.
* @param cms The cms-object.
* @param int taskid The id of the task.
* @param message The text of the message.
* @exception CmsException Throws CmsExceptions, that are be
* thrown in calling methods.
*/
public static void query(A_CmsObject cms, int taskid, String message)
throws CmsException {
CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms);
A_CmsTask task = cms.readTask(taskid);
String comment = lang.getLanguageValue("task.dialog.query.head") + " ";
if( (message != null) && (message.length() != 0)) {
comment += Utils.getFullName(cms.readOwner(task)) + "\n";
comment += message;
cms.writeTaskLog(taskid, comment, C_TASKLOGTYPE_CALL);
}
// send an email.
StringBuffer contentBuf = new StringBuffer(lang.getLanguageValue("task.email.query.content"));
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.project"));
contentBuf.append(": ");
String projectname = "?";
try {
projectname = cms.readTask(task.getRoot()).getName();
} catch(Exception exc) {
// no root?!
}
contentBuf.append(projectname);
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.task"));
contentBuf.append(": ");
contentBuf.append(task.getName());
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.editor"));
contentBuf.append(": ");
contentBuf.append(Utils.getFullName(cms.readAgent(task)));
int projectid=cms.readProject(task).getId();
String servletPath=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath();
String serverName=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServerName();
CmsXmlWpConfigFile conf=new CmsXmlWpConfigFile(cms);
String actionPath=conf.getWorkplaceActionPath();
contentBuf.append("\n\n\nhttp://"+serverName+servletPath+actionPath+"login.html?startTaskId="+taskid+"&startProjectId="+projectid);
String subject=lang.getLanguageValue("task.email.query.subject");
A_CmsUser[] users={cms.readOwner(task)};
try {
CmsMail mail=new CmsMail(cms,cms.readAgent(task),users,subject,contentBuf.toString());
mail.start();
} catch( Exception exc ) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsTaskAction] error while sending mail " + exc.getMessage());
}
}
}
/**
* Creates a new task.
* @param cms The cms-object.
* @param agentName The name of the new editor for this task.
* @param roleName The name of the new role for the user.
* @param taskName The new name of the task.
* @param taskcomment The new comment for this task.
* @param timeoutString The new timeout-date as a string in the following format:
* "dd.mm.yyyy"
* @param priorityString the new priority as String ("1" = high,
* "2" = normal or "3" = low)
* @param paraAcceptation controls if a message should be send by acceptation. ("checked" | "")
* @param paraAll controls if a message should be send to all users in a role. ("checked" | "")
* @param paraCompletion controls if a message should be send by completing this task. ("checked" | "")
* @param paraDelivery controls if a message should be send by delivering a task. ("checked" | "")
* @exception CmsException Throws CmsExceptions, that are be
* thrown in calling methods.
*/
public static void create(A_CmsObject cms,
String agentName, String roleName, String taskName,
String taskcomment, String timeoutString,
String priorityString, String paraAcceptation,
String paraAll, String paraCompletion, String paraDelivery)
throws CmsException {
CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms);
if( roleName.equals(C_ALL_ROLES) ) {
roleName = cms.readUser(agentName).getDefaultGroup().getName();
}
// try to create the task
int priority = Integer.parseInt(priorityString);
// create a long from the overgiven date.
String splittetDate[] = Utils.split(timeoutString, ".");
GregorianCalendar cal = new GregorianCalendar(Integer.parseInt(splittetDate[2]),
Integer.parseInt(splittetDate[1]) - 1,
Integer.parseInt(splittetDate[0]), 0, 0, 0);
long timeout = cal.getTime().getTime();
A_CmsTask task = cms.createTask(agentName, roleName, taskName,
taskcomment, timeout, priority);
cms.setTaskPar(task.getId(),C_TASKPARA_ACCEPTATION, paraAcceptation);
cms.setTaskPar(task.getId(),C_TASKPARA_ALL, paraAll);
cms.setTaskPar(task.getId(),C_TASKPARA_COMPLETION, paraCompletion);
cms.setTaskPar(task.getId(),C_TASKPARA_DELIVERY, paraDelivery);
String comment = lang.getLanguageValue("task.label.forrole") + ": " + roleName + "\n";
comment += lang.getLanguageValue("task.label.editor") + ": " + Utils.getFullName(cms.readUser(agentName)) + "\n";
comment += taskcomment;
cms.writeTaskLog(task.getId(), comment, C_TASKLOGTYPE_CREATED);
// send an email
// per default send a mail from task's organizer to task's recipient.
StringBuffer contentBuf = new StringBuffer(lang.getLanguageValue("task.email.create.content"));
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.project"));
contentBuf.append(": ");
String projectname = "?";
try {
projectname = cms.readTask(task.getRoot()).getName();
} catch(Exception exc) {
// no root?!
}
contentBuf.append(projectname);
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.task"));
contentBuf.append(": ");
contentBuf.append(task.getName());
contentBuf.append("\n");
contentBuf.append(lang.getLanguageValue("task.label.actuator"));
contentBuf.append(": ");
contentBuf.append(Utils.getFullName(cms.readOwner(task)));
int projectid=cms.readProject(task).getId();
String servletPath=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath();
String serverName=((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getServerName();
CmsXmlWpConfigFile conf=new CmsXmlWpConfigFile(cms);
String actionPath=conf.getWorkplaceActionPath();
contentBuf.append("\n\n\nhttp://"+serverName+servletPath+actionPath+"login.html?startTaskId="+task.getId()+"&startProjectId="+projectid);
String subject=lang.getLanguageValue("task.email.create.subject");
A_CmsUser[] users={cms.readAgent(task)};
CmsMail mail = null;
try {
mail=new CmsMail(cms,cms.readOwner(task),users,subject,contentBuf.toString());
} catch(CmsException e) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_INFO, "[CmsTaskAction] Could not generate mail while creating task for " + cms.readOwner(task).getName() + ". ");
A_OpenCms.log(C_OPENCMS_INFO, "[CmsTaskAction] " + e);
}
}
// if "Alle Rollenmitglieder von Aufgabe Benachrichtigen" checkbox is selected.
if (cms.getTaskPar(task.getId(),C_TASKPARA_ALL)!=null) {
// the news deliver always "checked" or ""
if (cms.getTaskPar(task.getId(),C_TASKPARA_ALL).equals("checked")) {
try {
mail=new CmsMail(cms,cms.readOwner(task),cms.readGroup(task),subject,contentBuf.toString());
} catch(CmsException e) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_INFO, "[CmsTaskAction] Could not generate mail while creating task for " + cms.readOwner(task).getName() + ". ");
A_OpenCms.log(C_OPENCMS_INFO, "[CmsTaskAction] " + e);
}
}
}
}
if(mail != null) {
mail.start();
}
}
/**
* Gets the description of a task.
* The description is stored in the task-log.
* @param cms The cms-object.
* @param int taskid The id of the task.
* @return String the comment-string.
* @exception CmsException Throws CmsExceptions, that are be
* thrown in calling methods.
*/
public static String getDescription(A_CmsObject cms, int taskid)
throws CmsException {
StringBuffer retValue = new StringBuffer("");
CmsTaskLog tasklog;
Vector taskdocs=cms.readTaskLogs(taskid);
// go through all tasklogs to find the comment
for (int i=1;i<=taskdocs.size();i++) {
tasklog = (CmsTaskLog)taskdocs.elementAt(taskdocs.size()-i);
int type=tasklog.getType();
// check if this is a type "created" or "new"
if ( (type == C_TASKLOGTYPE_CREATED) || (type == C_TASKLOGTYPE_REACTIVATED)) {
String comment[] = Utils.split(tasklog.getComment(), "\n");
for(int j = 2; j < comment.length; j++) {
retValue.append(comment[j] + "\n");
}
break;
}
}
return retValue.toString();
}
}
|
package com.namelessmc.java_api;
import com.google.common.base.Preconditions;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.namelessmc.java_api.exception.ApiDisabledException;
import com.namelessmc.java_api.logger.ApiLogger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class RequestHandler {
private final @NotNull URL baseUrl;
private final @NotNull String apiKey;
private final @NotNull String userAgent;
private final @Nullable ApiLogger debugLogger;
private final int timeout;
RequestHandler(final @NotNull URL baseUrl, final @NotNull String apiKey, final @NotNull String userAgent, @Nullable ApiLogger debugLogger, final int timeout) {
this.baseUrl = Objects.requireNonNull(baseUrl, "Base URL is null");
this.apiKey = Objects.requireNonNull(apiKey, "Api key is null");
this.userAgent = Objects.requireNonNull(userAgent, "User agent is null");
this.debugLogger = debugLogger;
this.timeout = timeout;
}
public @NotNull URL getApiUrl() {
return this.baseUrl;
}
public @NotNull String getApiKey() {
return this.apiKey;
}
public @NotNull JsonObject post(final @NotNull String route, final @Nullable JsonObject postData) throws NamelessException {
Preconditions.checkArgument(!route.startsWith("/"), "Route must not start with a slash");
URL url;
try {
url = new URL(this.baseUrl + "/" + route);
} catch (final MalformedURLException e) {
throw new NamelessException("Invalid URL or parameter string");
}
return makeConnection(url, postData);
}
public @NotNull JsonObject get(final @NotNull String route, final @NotNull Object @NotNull... parameters) throws NamelessException {
Preconditions.checkArgument(!route.startsWith("/"), "Route must not start with a slash");
final StringBuilder urlBuilder = new StringBuilder(this.baseUrl.toString());
urlBuilder.append("/");
urlBuilder.append(route);
if (parameters.length > 0) {
if (parameters.length % 2 != 0) {
final String paramString = Arrays.stream(parameters).map(Object::toString).collect(Collectors.joining("|"));
throw new IllegalArgumentException(String.format("Parameter string varargs array length must be even (length is %s - %s)", parameters.length, paramString));
}
for (int i = 0; i < parameters.length; i++) {
if (i % 2 == 0) {
urlBuilder.append("&");
urlBuilder.append(parameters[i]);
} else {
urlBuilder.append("=");
try {
urlBuilder.append(URLEncoder.encode(parameters[i].toString(), StandardCharsets.UTF_8.toString()));
} catch (final UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
}
final @NotNull URL url;
try {
url = new URL(urlBuilder.toString());
} catch (final MalformedURLException e) {
throw new NamelessException("Error while building request URL: " + urlBuilder, e);
}
return makeConnection(url, null);
}
private void debug(final @NotNull String message, @NotNull Supplier<Object[]> argsSupplier) {
if (this.debugLogger != null) {
this.debugLogger.log(String.format(message, argsSupplier.get()));
}
}
private @NotNull JsonObject makeConnection(final URL url, final @Nullable JsonObject postBody) throws NamelessException {
final HttpURLConnection connection;
final byte[] bytes;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(this.timeout);
connection.setConnectTimeout(this.timeout);
debug("Making connection %s to url %s", () -> new Object[]{ postBody != null ? "POST" : "GET", url});
connection.addRequestProperty("User-Agent", this.userAgent);
connection.addRequestProperty("X-API-Key", this.apiKey);
debug("Using User-Agent '%s'", () -> new Object[]{ this.userAgent });
if (postBody != null) {
debug("Post body below\n
connection.setRequestMethod("POST");
final byte[] encodedMessage = postBody.toString().getBytes(StandardCharsets.UTF_8);
connection.setRequestProperty("Content-Length", encodedMessage.length + "");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
try (OutputStream out = connection.getOutputStream()) {
out.write(encodedMessage);
}
}
if (connection.getResponseCode() >= 400) {
try (final InputStream in = connection.getErrorStream()) {
if (in == null) {
throw new NamelessException("Website sent empty response with code " + connection.getResponseCode());
} else {
bytes = getBytesFromInputStream(in);
}
}
} else {
try (final InputStream in = connection.getInputStream()) {
bytes = getBytesFromInputStream(in);
}
}
} catch (final IOException e) {
final StringBuilder message = new StringBuilder("Network connection error (not a Nameless issue).");
if (e.getMessage().contains("unable to find valid certification path to requested target")) {
message.append("\n HINT: Your certificate is invalid or incomplete. Ensure your website uses a valid *full chain* SSL/TLS certificate.");
}
message.append(" IOException: ");
message.append(e.getMessage());
throw new NamelessException(message.toString(), e);
}
final String response = new String(bytes, StandardCharsets.UTF_8);
if (response.equals("API is disabled")) {
throw new ApiDisabledException();
}
debug("Website response below\n
JsonObject json;
try {
json = JsonParser.parseString(response).getAsJsonObject();
} catch (final JsonSyntaxException | IllegalStateException e) {
final StringBuilder printableResponseBuilder = new StringBuilder();
if (response.length() > 5_000) {
printableResponseBuilder.append(response, 0, 5_000);
printableResponseBuilder.append("\n[response truncated to 5k characters]\n");
} else {
printableResponseBuilder.append(response);
if (!response.endsWith("\n")) {
printableResponseBuilder.append('\n');
}
}
String printableResponse = regularAsciiOnly(printableResponseBuilder.toString());
int code;
try {
code = connection.getResponseCode();
} catch (final IOException e1) {
throw new IllegalStateException("We've already made a connection, getting an IOException now is impossible", e1);
}
String message = e.getMessage() + "\n"
+ "Unable to parse json. Received response code " + code + ". Website response:\n"
+ "
+ printableResponse
+ "
if (code == 301 || code == 302 || code == 303) {
message += "HINT: The URL results in a redirect. If your URL uses http:
} else if (code == 520 || code == 521) {
message += "HINT: Status code 520/521 is sent by CloudFlare when the backend webserver is down or having issues.";
} else if (printableResponse.contains("/aes.js")) {
message += "HINT: It looks like requests are being blocked by your web server or a proxy. " +
"This is a common occurrence with free web hosting services; they usually don't allow API access.";
} else if (printableResponse.contains("<title>Please Wait... | Cloudflare</title>")) {
|
package com.github.florent37.singledateandtimepicker;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.github.florent37.singledateandtimepicker.widget.WheelAmPmPicker;
import com.github.florent37.singledateandtimepicker.widget.WheelDayPicker;
import com.github.florent37.singledateandtimepicker.widget.WheelHourPicker;
import com.github.florent37.singledateandtimepicker.widget.WheelMinutePicker;
import com.github.florent37.singledateandtimepicker.widget.WheelMonthPicker;
import com.github.florent37.singledateandtimepicker.widget.WheelPicker;
import com.github.florent37.singledateandtimepicker.widget.WheelYearPicker;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static com.github.florent37.singledateandtimepicker.DateHelper.getCalendarOfDate;
public class SingleDateAndTimePicker extends LinearLayout {
public static final boolean IS_CYCLIC_DEFAULT = true;
public static final boolean IS_CURVED_DEFAULT = false;
public static final boolean MUST_BE_ON_FUTUR_DEFAULT = false;
public static final int DELAY_BEFORE_CHECK_PAST = 200;
private static final int VISIBLE_ITEM_COUNT_DEFAULT = 7;
private static final int PM_HOUR_ADDITION = 12;
private static final CharSequence FORMAT_24_HOUR = "EEE d MMM H:mm";
private static final CharSequence FORMAT_12_HOUR = "EEE d MMM h:mm a";
@NonNull
private WheelYearPicker yearsPicker;
@NonNull
private WheelMonthPicker monthPicker;
@NonNull
private final WheelDayPicker daysPicker;
@NonNull
private final WheelMinutePicker minutesPicker;
@NonNull
private final WheelHourPicker hoursPicker;
@NonNull
private final WheelAmPmPicker amPmPicker;
private List<WheelPicker> pickers = new ArrayList<>();
private List<OnDateChangedListener> listeners = new ArrayList<>();
private View dtSelector;
private boolean mustBeOnFuture;
@Nullable
private Date minDate;
@Nullable
private Date maxDate;
@NonNull
private Date defaultDate;
private boolean displayYears = false;
private boolean displayMonth = false;
private boolean displayDays = true;
private boolean displayMinutes = true;
private boolean displayHours = true;
private boolean isAmPm;
private int selectorHeight;
public SingleDateAndTimePicker(Context context) {
this(context, null);
}
public SingleDateAndTimePicker(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SingleDateAndTimePicker(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
defaultDate = new Date();
isAmPm = !(DateFormat.is24HourFormat(context));
inflate(context, R.layout.single_day_picker, this);
yearsPicker = (WheelYearPicker) findViewById(R.id.yearPicker);
monthPicker = (WheelMonthPicker) findViewById(R.id.monthPicker);
daysPicker = (WheelDayPicker) findViewById(R.id.daysPicker);
minutesPicker = (WheelMinutePicker) findViewById(R.id.minutesPicker);
hoursPicker = (WheelHourPicker) findViewById(R.id.hoursPicker);
amPmPicker = (WheelAmPmPicker) findViewById(R.id.amPmPicker);
dtSelector = findViewById(R.id.dtSelector);
pickers.addAll(Arrays.asList(
daysPicker,
minutesPicker,
hoursPicker,
amPmPicker,
monthPicker,
yearsPicker
));
init(context, attrs);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
yearsPicker.setOnYearSelectedListener(new WheelYearPicker.OnYearSelectedListener() {
@Override
public void onYearSelected(WheelYearPicker picker, int position, int year) {
updateListener();
checkMinMaxDate(picker);
}
});
monthPicker.setOnMonthSelectedListener(new WheelMonthPicker.MonthSelectedListener() {
@Override
public void onMonthSelected(WheelMonthPicker picker, int monthIndex, String monthName) {
updateListener();
checkMinMaxDate(picker);
}
});
daysPicker
.setOnDaySelectedListener(new WheelDayPicker.OnDaySelectedListener() {
@Override
public void onDaySelected(WheelDayPicker picker, int position, String name, Date date) {
updateListener();
checkMinMaxDate(picker);
}
});
minutesPicker
.setOnMinuteChangedListener(new WheelMinutePicker.OnMinuteChangedListener() {
@Override
public void onMinuteChanged(WheelMinutePicker picker, int minutes) {
updateListener();
checkMinMaxDate(picker);
}
})
.setOnFinishedLoopListener(new WheelMinutePicker.OnFinishedLoopListener() {
@Override
public void onFinishedLoop(WheelMinutePicker picker) {
hoursPicker.scrollTo(hoursPicker.getCurrentItemPosition() + 1);
}
});
hoursPicker
.setOnFinishedLoopListener(new WheelHourPicker.FinishedLoopListener() {
@Override
public void onFinishedLoop(WheelHourPicker picker) {
daysPicker.scrollTo(daysPicker.getCurrentItemPosition() + 1);
}
})
.setHourChangedListener(new WheelHourPicker.OnHourChangedListener() {
@Override
public void onHourChanged(WheelHourPicker picker, int hour) {
updateListener();
checkMinMaxDate(picker);
}
});
amPmPicker
.setAmPmListener(new WheelAmPmPicker.AmPmListener() {
@Override
public void onAmPmChanged(WheelAmPmPicker picker, boolean isAm) {
updateListener();
checkMinMaxDate(picker);
}
});
setDefaultDate(this.defaultDate); //update displayed date
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
for (WheelPicker picker : pickers) {
picker.setEnabled(enabled);
}
}
public void setDisplayYears(boolean displayYears) {
this.displayYears = displayYears;
yearsPicker.setVisibility(displayYears ? VISIBLE : GONE);
}
public void setDisplayMonths(boolean displayMonths) {
this.displayMonth = displayMonths;
monthPicker.setVisibility(displayMonths ? VISIBLE : GONE);
}
public void setDisplayDays(boolean displayDays) {
this.displayDays = displayDays;
daysPicker.setVisibility(displayDays ? VISIBLE : GONE);
}
public void setDisplayMinutes(boolean displayMinutes) {
this.displayMinutes = displayMinutes;
minutesPicker.setVisibility(displayMinutes ? VISIBLE : GONE);
}
public void setDisplayHours(boolean displayHours) {
this.displayHours = displayHours;
hoursPicker.setVisibility(displayHours ? VISIBLE : GONE);
setIsAmPm(this.isAmPm);
hoursPicker.setIsAmPm(isAmPm);
}
public void setTodayText(String todayText) {
if (todayText != null && !todayText.isEmpty()) {
daysPicker.setTodayText(todayText);
}
}
public void setCurved(boolean curved) {
for (WheelPicker picker : pickers) {
picker.setCurved(curved);
}
}
public void setCyclic(boolean cyclic) {
for (WheelPicker picker : pickers) {
picker.setCyclic(cyclic);
}
}
public void setTextSize(int textSize) {
for (WheelPicker picker : pickers) {
picker.setItemTextSize(textSize);
}
}
public void setSelectedTextColor(int selectedTextColor) {
for (WheelPicker picker : pickers) {
picker.setSelectedItemTextColor(selectedTextColor);
}
}
public void setTextColor(int textColor) {
for (WheelPicker picker : pickers) {
picker.setItemTextColor(textColor);
}
}
public void setSelectorColor(int selectorColor) {
dtSelector.setBackgroundColor(selectorColor);
}
public void setSelectorHeight(int selectorHeight) {
final ViewGroup.LayoutParams dtSelectorLayoutParams = dtSelector.getLayoutParams();
dtSelectorLayoutParams.height = selectorHeight;
dtSelector.setLayoutParams(dtSelectorLayoutParams);
}
public void setVisibleItemCount(int visibleItemCount) {
for (WheelPicker picker : pickers) {
picker.setVisibleItemCount(visibleItemCount);
}
}
public void setIsAmPm(boolean isAmPm) {
this.isAmPm = isAmPm;
amPmPicker.setVisibility((isAmPm && displayHours) ? VISIBLE : GONE);
hoursPicker.setIsAmPm(isAmPm);
}
public void setDayFormatter(SimpleDateFormat simpleDateFormat) {
if (simpleDateFormat != null) {
this.daysPicker.setDayFormatter(simpleDateFormat);
}
}
public boolean isAmPm() {
return isAmPm;
}
public Date getMinDate() {
return minDate;
}
public void setMinDate(Date minDate) {
this.minDate = minDate;
setMinYear();
}
public Date getMaxDate() {
return maxDate;
}
public void setMaxDate(Date maxDate) {
this.maxDate = maxDate;
setMinYear();
}
private void checkMinMaxDate(final WheelPicker picker) {
checkBeforeMinDate(picker);
checkAfterMaxDate(picker);
}
private void checkBeforeMinDate(final WheelPicker picker) {
picker.postDelayed(new Runnable() {
@Override
public void run() {
if (minDate != null && isBeforeMinDate(getDate())) {
for (WheelPicker p : pickers) {
p.scrollTo(p.findIndexOfDate(minDate));
}
}
}
}, DELAY_BEFORE_CHECK_PAST);
}
private void checkAfterMaxDate(final WheelPicker picker) {
picker.postDelayed(new Runnable() {
@Override
public void run() {
if (maxDate != null && isAfterMaxDate(getDate())) {
for (WheelPicker p : pickers) {
p.scrollTo(p.findIndexOfDate(maxDate));
}
}
}
}, DELAY_BEFORE_CHECK_PAST);
}
private boolean isBeforeMinDate(Date date) {
return getCalendarOfDate(date).before(getCalendarOfDate(minDate));
}
private boolean isAfterMaxDate(Date date) {
return getCalendarOfDate(date).after(getCalendarOfDate(maxDate));
}
public void addOnDateChangedListener(OnDateChangedListener listener) {
this.listeners.add(listener);
}
public void removeOnDateChangedListener(OnDateChangedListener listener) {
this.listeners.remove(listener);
}
public void checkPickersMinMax() {
for (WheelPicker picker : pickers) {
checkMinMaxDate(picker);
}
}
public Date getDate() {
int hour = hoursPicker.getCurrentHour();
if (isAmPm && amPmPicker.isPm()) {
hour += PM_HOUR_ADDITION;
}
final int minute = minutesPicker.getCurrentMinute();
final Calendar calendar = Calendar.getInstance();
if (displayDays) {
final Date dayDate = daysPicker.getCurrentDate();
calendar.setTime(dayDate);
} else {
if (displayMonth) {
calendar.set(Calendar.MONTH, monthPicker.getCurrentMonth());
}
if (displayYears) {
calendar.set(Calendar.YEAR, yearsPicker.getCurrentYear());
}
}
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
return calendar.getTime();
}
public void setStepMinutes(int minutesStep) {
minutesPicker.setStepMinutes(minutesStep);
}
public void setHoursStep(int hoursStep) {
hoursPicker.setHoursStep(hoursStep);
}
public void setDefaultDate(Date date) {
if (date != null) {
this.defaultDate = date;
for (WheelPicker picker : pickers) {
picker.setDefaultDate(defaultDate);
}
}
}
public void selectDate(Calendar calendar) {
if (calendar == null) {
return;
}
final Date date = calendar.getTime();
for (WheelPicker picker : pickers) {
picker.selectDate(date);
}
}
private void updateListener() {
final Date date = getDate();
final CharSequence format = isAmPm ? FORMAT_12_HOUR : FORMAT_24_HOUR;
final String displayed = DateFormat.format(format, date).toString();
for (OnDateChangedListener listener : listeners) {
listener.onDateChanged(displayed, date);
}
}
public void setMustBeOnFuture(boolean mustBeOnFuture) {
this.mustBeOnFuture = mustBeOnFuture;
if (mustBeOnFuture) {
minDate = Calendar.getInstance().getTime(); //minDate is Today
}
}
public boolean mustBeOnFuture() {
return mustBeOnFuture;
}
private void setMinYear() {
if (displayYears && this.minDate != null && this.maxDate != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(this.minDate);
yearsPicker.setMinYear(calendar.get(Calendar.YEAR));
calendar.setTime(this.maxDate);
yearsPicker.setMaxYear(calendar.get(Calendar.YEAR));
}
}
private void init(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SingleDateAndTimePicker);
final Resources resources = getResources();
setTodayText(a.getString(R.styleable.SingleDateAndTimePicker_picker_todayText));
setTextColor(a.getColor(R.styleable.SingleDateAndTimePicker_picker_textColor, ContextCompat.getColor(context, R.color.picker_default_text_color)));
setSelectedTextColor(a.getColor(R.styleable.SingleDateAndTimePicker_picker_selectedTextColor, ContextCompat.getColor(context, R.color.picker_default_selected_text_color)));
setSelectorColor(a.getColor(R.styleable.SingleDateAndTimePicker_picker_selectorColor, ContextCompat.getColor(context, R.color.picker_default_selector_color)));
setSelectorHeight(a.getDimensionPixelSize(R.styleable.SingleDateAndTimePicker_picker_selectorHeight, resources.getDimensionPixelSize(R.dimen.wheelSelectorHeight)));
setTextSize(a.getDimensionPixelSize(R.styleable.SingleDateAndTimePicker_picker_textSize, resources.getDimensionPixelSize(R.dimen.WheelItemTextSize)));
setCurved(a.getBoolean(R.styleable.SingleDateAndTimePicker_picker_curved, IS_CURVED_DEFAULT));
setCyclic(a.getBoolean(R.styleable.SingleDateAndTimePicker_picker_cyclic, IS_CYCLIC_DEFAULT));
setMustBeOnFuture(a.getBoolean(R.styleable.SingleDateAndTimePicker_picker_mustBeOnFuture, MUST_BE_ON_FUTUR_DEFAULT));
setVisibleItemCount(a.getInt(R.styleable.SingleDateAndTimePicker_picker_visibleItemCount, VISIBLE_ITEM_COUNT_DEFAULT));
setDisplayDays(a.getBoolean(R.styleable.SingleDateAndTimePicker_picker_displayYears, displayYears));
setDisplayDays(a.getBoolean(R.styleable.SingleDateAndTimePicker_picker_displayDays, displayDays));
setDisplayMinutes(a.getBoolean(R.styleable.SingleDateAndTimePicker_picker_displayMinutes, displayMinutes));
setDisplayHours(a.getBoolean(R.styleable.SingleDateAndTimePicker_picker_displayHours, displayHours));
setDisplayMonths(a.getBoolean(R.styleable.SingleDateAndTimePicker_picker_displayMonth, displayMonth));
setDisplayYears(a.getBoolean(R.styleable.SingleDateAndTimePicker_picker_displayYears, displayYears));
setMinYear();
a.recycle();
}
public interface OnDateChangedListener {
void onDateChanged(String displayed, Date date);
}
}
|
package com.essiembre.eclipse.rbe.model.tree;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import com.essiembre.eclipse.rbe.model.DeltaEvent;
import com.essiembre.eclipse.rbe.model.IDeltaListener;
import com.essiembre.eclipse.rbe.model.Model;
import com.essiembre.eclipse.rbe.model.bundle.Bundle;
import com.essiembre.eclipse.rbe.model.bundle.BundleEntry;
import com.essiembre.eclipse.rbe.model.bundle.BundleGroup;
import com.essiembre.eclipse.rbe.model.tree.updater.KeyTreeUpdater;
/**
* Tree representation of a bundle group.
* @author Pascal Essiembre (essiembre@users.sourceforge.net)
* @version $Author$ $Revision$ $Date$
*/
public class KeyTree extends Model implements IKeyTreeVisitable {
/** Caching of key tree items (key=ID; value=KeyTreeItem). **/
private final Map keyItemsCache = new TreeMap();
/** Items found at root level. */
private final Set rootKeyItems = new TreeSet();
/** Updater responsible for tree changes. */
private KeyTreeUpdater updater;
/** Bundle group used to build the tree. */
private BundleGroup bundleGroup;
/** the currently selected key. */
private String selectedKey;
/**
* Constructor.
* @param bundleGroup bundle group used to build this tree
* @param updater updater used to handle tree modifications
*/
public KeyTree(BundleGroup bundleGroup, KeyTreeUpdater updater) {
super();
this.bundleGroup = bundleGroup;
this.updater = updater;
// Set listeners
bundleGroup.addListener(new IDeltaListener() {
public void add(DeltaEvent event) {
initBundle((Bundle) event.receiver());
}
public void remove(DeltaEvent event) {
// do nothing
}
public void modify(DeltaEvent event) {
// do nothing
}
public void select(DeltaEvent event) {
// do nothing
}
});
for (Iterator iter = bundleGroup.iterator(); iter.hasNext();) {
initBundle((Bundle) iter.next());
}
// Initial tree creation
load();
}
/**
* Initializes the given bundle by adding propser listeners on it.
* @param bundle the bundle to initialize
*/
protected void initBundle(Bundle bundle) {
bundle.addListener(new IDeltaListener() {
public void add(DeltaEvent event) {
addKey(((BundleEntry) event.receiver()).getKey());
}
public void remove(DeltaEvent event) {
removeKey(((BundleEntry) event.receiver()).getKey());
}
public void modify(DeltaEvent event) {
modifyKey(((BundleEntry) event.receiver()).getKey());
}
public void select(DeltaEvent event) {
}
});
}
/**
* Gets a key tree item.
* @param key key of item to get
* @return a key tree item
*/
public KeyTreeItem getKeyTreeItem(String key) {
return (KeyTreeItem) keyItemsCache.get(key);
}
/**
* Returns the currently selected key.
*
* @return The currently selected key. null = no selection.
*/
public String getSelectedKey() {
return (selectedKey);
}
/**
* Gets the key tree item cache.
* @return key tree item cache.
*/
public Map getKeyItemsCache() {
return keyItemsCache;
}
/**
* Gets all items contained a the root level of this tree.
* @return a collection of <code>KeyTreeItem</code> objects.
*/
public Set getRootKeyItems() {
return rootKeyItems;
}
/**
* Adds a key to this tree.
* @param key key to add
*/
public void addKey(String key) {
updater.addKey(this, key);
fireAdd(keyItemsCache.get(key));
}
/**
* Removes a key from this tree.
* @param key key to remove
*/
public void removeKey(String key) {
Object item = keyItemsCache.get(key);
updater.removeKey(this, key);
fireRemove(item);
}
/**
* Modifies a key on this tree.
* @param key key to modify
*/
public void modifyKey(String key) {
Object item = keyItemsCache.get(key);
fireModify(item);
}
/**
* Marks a key as selected on this tree.
* @param key key to select.
*/
public void selectKey(String key) {
Object item = keyItemsCache.get(key);
if ((selectedKey == null) || (!selectedKey.equals(key))) {
selectedKey = key;
fireSelect(item);
}
}
/**
* Gets the key tree updater.
* @return key tree updater
*/
public KeyTreeUpdater getUpdater() {
return updater;
}
/**
* Sets the key tree updater. Doing so will automatically refresh the tree,
* which means, recreating it entirely.
* @param updater key tree updater
*/
public void setUpdater(KeyTreeUpdater updater) {
this.updater = updater;
keyItemsCache.clear();
rootKeyItems.clear();
load();
}
/**
* @see com.essiembre.eclipse.rbe.model.tree.IKeyTreeVisitable#accept(
* com.essiembre.eclipse.rbe.model.tree.IKeyTreeVisitor,
* java.lang.Object)
*/
public void accept(IKeyTreeVisitor visitor, Object passAlongArgument) {
for (Iterator iter = keyItemsCache.values().iterator(); iter.hasNext();) {
visitor.visitKeyTreeItem(
(KeyTreeItem) iter.next(), passAlongArgument);
}
visitor.visitKeyTree(this, passAlongArgument);
}
/**
* Gets the bundle group associated with this tree.
* @return bundle group
*/
public BundleGroup getBundleGroup() {
return bundleGroup;
}
/**
* Loads all key tree items, base on bundle group.
*/
private final void load() {
for (Iterator iter = bundleGroup.getKeys().iterator();
iter.hasNext();) {
/*
* Do not call "fireAdd" method from here for extreme performance
* improvement. This is not an addition in the sense that we are
* laying out existing keys, not adding any new ones. We will
* refresh the whole tree after we are done looping.
*/
updater.addKey(this, (String) iter.next());
}
fireAdd(this);
}
}
|
package com.redpois0n.gitj.ui.graph;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import com.redpois0n.git.Commit;
public class GraphEntry {
public static final int BALL_DIAMETER = 8;
public static final int SPACE = 10;
public static final Color[] COLORS = new Color[] { Color.blue, Color.red, Color.green, Color.magenta };
private String graphData;
private List<String> additional = new ArrayList<String>();
private Commit commit;
public GraphEntry(String graphData, Commit c) {
this.graphData = graphData;
this.commit = c;
}
public BufferedImage render(int height) {
BufferedImage image = new BufferedImage(100, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.createGraphics();
int location = SPACE;
List<String> list = new ArrayList<String>();
list.addAll(additional);
list.add(0, graphData);
for (int i = 0; i < list.size(); i++) {
String str = list.get(i);
for (int s = 0; s < str.length(); s++) {
char c = str.charAt(s);
g.setColor(COLORS[s]);
if (c == '*') {
g.fillOval(location - BALL_DIAMETER / 2, height / 2 - BALL_DIAMETER / 2, BALL_DIAMETER, BALL_DIAMETER);
}
if (c == '*' || c == '|') {
g.drawLine(location, 0, location, height);
} else if (c == '/') {
g.drawLine(location, height / 2, location - SPACE, height);
} else if (c == '\\') {
g.drawLine(location - SPACE, height / 2, location, height);
}
location += SPACE;
}
location = SPACE;
}
for (int i = 0; i < list.size(); i++) {
String str = list.get(i);
for (int s = 0; s < str.length(); s++) {
char c = str.charAt(s);
g.setColor(COLORS[s]);
if (c == '*') {
g.fillOval(location - BALL_DIAMETER / 2, height / 2 - BALL_DIAMETER / 2, BALL_DIAMETER, BALL_DIAMETER);
}
location += SPACE;
}
location = SPACE;
}
return image;
}
public ImageIcon renderIcon(int height) {
return new ImageIcon(render(height));
}
public Commit getCommit() {
return this.commit;
}
public void addData(String graphData) {
additional.add(graphData);
}
}
|
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// persons to whom the Software is furnished to do so, subject to the
// notice shall be included in all copies or substantial portions of the
// Software.
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
package phasereditor.canvas.ui.editors.edithandlers;
import javafx.geometry.Point2D;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.ClosePath;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import phasereditor.canvas.core.BaseSpriteModel;
import phasereditor.canvas.ui.editors.operations.ChangePropertyOperation;
import phasereditor.canvas.ui.editors.operations.CompositeOperation;
import phasereditor.canvas.ui.shapes.IObjectNode;
/**
* @author arian
*
*/
public class MoveHandlerNode extends PathHandlerNode {
private Axis _axis;
private double _initX;
private double _initY;
private double _initModelX;
private double _initModelY;
public MoveHandlerNode(Axis axis, IObjectNode object) {
super(object);
Paint color = axis == Axis.CENTER ? Color.WHITE : (axis.changeW() ? Color.RED.brighter() : Color.LIGHTGREEN);
setFill(color);
setStroke(Color.BLACK);
_axis = axis;
}
@Override
public void handleSceneStart(double x, double y, MouseEvent e) {
_initModelX = _model.getX();
_initModelY = _model.getY();
Point2D p = _object.getNode().getParent().localToScene(_initModelX, _initModelY);
_initX = p.getX();
_initY = p.getY();
}
@Override
public void handleSceneDrag(double dx, double dy, MouseEvent e) {
Point2D p = _canvas.getDragBehavior().adjustPositionToStep(_initX + dx, _initY + dy);
boolean changeBoth = _axis == Axis.CENTER;
if (_axis.changeW() || changeBoth) {
p = _canvas.getDragBehavior().adjustPositionToStep(_initX + dx, _initY);
}
if (_axis.changeH() || changeBoth) {
p = _canvas.getDragBehavior().adjustPositionToStep(_initX, _initY + dy);
}
Node node = _object.getNode();
Parent parent = node.getParent();
p = parent.sceneToLocal(p);
_model.setX(p.getX());
_model.setY(p.getY());
}
@Override
public void handleDone() {
double x = _model.getX();
double y = _model.getY();
_model.setX(_initModelX);
_model.setY(_initModelY);
String id = _model.getId();
_canvas.getUpdateBehavior().executeOperations(
new CompositeOperation(
new ChangePropertyOperation<Number>(id, "x", Double.valueOf(x)),
new ChangePropertyOperation<Number>(id, "y", Double.valueOf(y))
));
}
@Override
public void updateHandler() {
double centerX = _model.getPivotX();
double centerY = _model.getPivotY();
if (_model instanceof BaseSpriteModel) {
BaseSpriteModel spriteModel = (BaseSpriteModel) _model;
double x2 = spriteModel.getAnchorX() * _control.getTextureWidth();
double y2 = spriteModel.getAnchorY() * _control.getTextureHeight();
centerX = centerX + x2;
centerY = centerY + y2;
}
Point2D p = _node.localToScene(centerX, centerY);
centerX = p.getX();
centerY = p.getY();
double x = centerX;
double y = centerY;
int N = 150;
if (_axis == Axis.CENTER) {
relocate(x - 5, y - 5);
} else if (_axis.changeW()) {
//@formatter:off
getElements().setAll(
new MoveTo(0, -1),
new LineTo(N, -1),
new LineTo(N, -5),
new LineTo(N + 10, 0),
new LineTo(N, 5),
new LineTo(N, 1),
new LineTo(0, 1),
new ClosePath()
);
//@formatter:on
relocate(x, y - 5);
} else {
//@formatter:off
getElements().setAll(
new MoveTo(-1, 0),
new LineTo(-1, N),
new LineTo(-5, N),
new LineTo(0, N + 10),
new LineTo(5, N),
new LineTo(1, N),
new LineTo(1, 0),
new ClosePath()
);
//@formatter:on
relocate(x - 5, y);
}
// setCursor(_axis.getResizeCursor(_object));
setCursor(Cursor.MOVE);
}
}
|
package com.example.FlowFree.activities;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.example.FlowFree.R;
import com.example.FlowFree.database.FlowAdapter;
import com.example.FlowFree.objects.parser.Flow;
import com.example.FlowFree.objects.parser.XmlParser;
import java.util.List;
public class MainActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getActionBar().setTitle("Menu");
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
//if the app is running on your phone for the first time, then we will write to the database
if (settings.getBoolean("is_first_time", true)) {
FlowAdapter fa = new FlowAdapter( this );
XmlParser myParser = new XmlParser();
List<Flow> insertFlows;
insertFlows = myParser.parseXML();
int i = 1;
for(Flow f : insertFlows)
{
fa.insertFlows(i,f.getSize(),0 ,f.getFlow1(),f.getFlow2(),f.getFlow3(),
f.getFlow4(),f.getFlow5(),f.getFlow6());
i++;
}
settings.edit().putBoolean("is_first_time", false).commit();
}
setImageSize();
}
/**
* When the play or options button is pressed
* @param view
*/
public void buttonClick(View view){
Button button = (Button) view;
int id = button.getId();
if(id == R.id.button_play){
startActivity(new Intent(this, GameChooserActivity.class));
}
else{
startActivity(new Intent(this, OptionsActivity.class));
}
}
public void setImageSize(){
ImageView theImage = (ImageView)findViewById(R.id.titleImage);
Display theDisplay = getWindowManager().getDefaultDisplay();
Point dimensions = new Point();
theDisplay.getSize(dimensions);
int sideMargins = (int)(dimensions.x * 0.2);
int imageSize = (int)(dimensions.y * 0.75);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, imageSize);
lp.setMargins(sideMargins,-sideMargins,sideMargins,-sideMargins);
theImage.setLayoutParams(lp);
}
}
|
package net.safedata.spring.intro.service;
import net.safedata.spring.intro.data.dao.UserDAO;
import net.safedata.spring.intro.data.entities.User;
import net.safedata.spring.intro.transport.UserTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.ExecutionException;
@Service
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public class UserServiceImpl implements UserService {
private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
private UserDAO usersDAO;
@Override
public Collection<UserTO> getAll() throws InterruptedException, ExecutionException {
Collection<UserTO> userTOs = new LinkedList<>();
Collection<User> allUsers = usersDAO.getAll();
for (User user : allUsers) {
userTOs.add(buildUserTO(user));
}
return userTOs;
}
@Override
public UserTO get(Integer id) {
LOGGER.info("Retrieving the user with the ID '{}'...", id);
User user = usersDAO.get(id);
return buildUserTO(user);
}
@Override
public User get(String name) {
return usersDAO.get(name);
}
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void save(User user) {
LOGGER.info("Saving the user '{}'...", user.getUserName());
usersDAO.save(user);
}
private UserTO buildUserTO(User user) {
UserTO userTO = new UserTO();
userTO.setId(user.getId());
userTO.setUserName(user.getUserName());
userTO.setFirstName(user.getFirstName());
userTO.setLastName(user.getLastName());
return userTO;
}
}
|
package com.yidianhulian.framework;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
/**
*
*
* @author leeboo
*
*/
public class ImageLoader {
private Context mContext;
private static HashMap<String, Object> mMemoryCache = new HashMap<String, Object>();
MyHandler mHandler = new MyHandler();
private static final int LOAD_IMAGE = 0;
private static final int LOAD_FILE = 1;
private int width=0;
private int height=0;
public ImageLoader(Context context) {
mContext = context;
}
private File cachedFile(final String url){
File existFile = new File(url);
if (existFile.exists()){
return existFile;
}
File dir = mContext.getExternalCacheDir();
if(dir == null)return null;
if(! dir.exists()){
return null;
}
File[] files = dir.listFiles(new FilenameFilter(){
@Override
public boolean accept(File dir, String filename) {
return filename.equals(Util.MD5(url));
}
});
if (files==null || files.length==0) return null;
return files[0];
}
public void loadImage(ImageView imageView, String imageUrl, int width, int height){
this.width = width;
this.height = height;
loadImage(imageView, imageUrl, new ImageLoaded() {
@Override
public void imageLoaded(ImageView imageView, Drawable imageDrawable) {
if(imageDrawable!=null){
imageView.setImageDrawable(imageDrawable);
}
}
});
}
public void loadImage(ImageView imageView, String imageUrl){
loadImage(imageView, imageUrl, new ImageLoaded() {
@Override
public void imageLoaded(ImageView imageView, Drawable imageDrawable) {
if(imageDrawable!=null){
imageView.setImageDrawable(imageDrawable);
}
}
});
}
public void loadImage(final ImageView imageView, final String imageUrl, final ImageLoaded imageCallback) {
if(mMemoryCache.containsKey(imageUrl)){
mHandler.obtainMessage(LOAD_IMAGE, new Object[]{imageView, mMemoryCache.get(imageUrl), imageCallback}).sendToTarget();
return;
}
new Thread("loadDrawable"){
public void run(){
File cachedFile = cachedFile(imageUrl);
if (cachedFile != null) {
Bitmap bm = BitmapFactory.decodeFile(cachedFile.getAbsolutePath());
if(width>0 && height>0){
bm = ImageUtils.extractMiniThumb(bm, width, height, true);
}
BitmapDrawable cached = new BitmapDrawable(mContext.getResources(), bm);
mMemoryCache.put(imageUrl, cached);
mHandler.obtainMessage(LOAD_IMAGE, new Object[]{imageView, cached, imageCallback}).sendToTarget();
return;
}
new Thread("loadImageFromUrl") {
@Override
public void run() {
BitmapDrawable drawable = loadImageFromUrl(imageUrl);
mHandler.obtainMessage(LOAD_IMAGE, new Object[]{imageView, drawable, imageCallback}).sendToTarget();
if(drawable!=null){
mMemoryCache.put(imageUrl, (BitmapDrawable)drawable);
try {
File dirFile = mContext.getExternalCacheDir();
if(dirFile != null){
if( ! dirFile.exists()){
dirFile.mkdir();
}
File cacheFile = new File(dirFile.getAbsolutePath() + "/" + Util.MD5(imageUrl));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(cacheFile));
drawable.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
}.start();
}
private BitmapDrawable loadImageFromUrl(String url) {
if(url==null || "".equals(url.trim()))return null;
URL u;
InputStream i = null;
BitmapDrawable d = null;
try {
u = new URL(url);
i = (InputStream) u.getContent();
d = new BitmapDrawable(mContext.getResources(), i);
d.setTargetDensity(mContext.getResources().getDisplayMetrics());
i.close();
if(width>0 && height>0){
Bitmap bm = ImageUtils.extractMiniThumb(d.getBitmap(), width, height, true);
d = new BitmapDrawable(mContext.getResources(), bm);
}
} catch (Exception e) {
Log.d("loadImageFromUrl", url+":"+e.getMessage());
}catch (Error e) {
}
Log.d("loading images", url+": "+(d!=null ? "ok" : "fail"));
return d;
}
public void loadFile(final String fileUrl, final FileLoaded fileCallback) {
if(mMemoryCache.containsKey(fileUrl)){
mHandler.obtainMessage(LOAD_FILE, new Object[]{mMemoryCache.get(fileUrl), fileCallback}).sendToTarget();
return;
}
new Thread("loadFile"){
public void run(){
File cachedFile = cachedFile(fileUrl);
if (cachedFile != null) {
String file_path = cachedFile.getAbsolutePath();
mMemoryCache.put(fileUrl, file_path);
mHandler.obtainMessage(LOAD_FILE, new Object[]{file_path, fileCallback}).sendToTarget();
return;
}
new Thread("loadFileFromUrl") {
@Override
public void run() {
try {
File dirFile = mContext.getExternalCacheDir();
if (dirFile == null) {
mHandler.obtainMessage(LOAD_FILE, new Object[]{"", fileCallback}).sendToTarget();
return;
}
if( ! dirFile.exists()){
dirFile.mkdir();
}
String[] splitUrl = fileUrl.split("\\?");
int pos = splitUrl[0].lastIndexOf(".");
String extName = "";
if (pos != -1) extName = splitUrl[0].substring(pos);
InputStream inputStream = null;
FileOutputStream outStream = null;
try {
URL u = new URL(fileUrl);
URLConnection conn = u.openConnection();
inputStream = conn.getInputStream();
File cacheFile = new File(dirFile.getAbsolutePath() + "/" + Util.MD5(fileUrl) + extName);
outStream = new FileOutputStream(cacheFile);
int byteread = 0;
byte[] buffer = new byte[1024];
while ((byteread = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, byteread);
}
String file_path = cacheFile.getAbsolutePath();
mHandler.obtainMessage(LOAD_FILE, new Object[]{file_path, fileCallback}).sendToTarget();
mMemoryCache.put(fileUrl, file_path);
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
inputStream.close();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
mHandler.obtainMessage(LOAD_FILE, new Object[]{"", fileCallback}).sendToTarget();
}
} catch (Exception e) {
e.printStackTrace();
mHandler.obtainMessage(LOAD_FILE, new Object[]{"", fileCallback}).sendToTarget();
}
}
}.start();
}
}.start();
}
public interface ImageLoaded {
/**
*
* @param imageView
* @param imageDrawable null
*/
public void imageLoaded(ImageView imageView, Drawable imageDrawable);
}
public interface FileLoaded {
/**
* ,,
* @param localFilePath ,null
*/
public void fileLoaded(String localFilePath);
}
static class MyHandler extends Handler{
public void handleMessage(Message message) {
Object[] datas = (Object[])message.obj;
if (message.what == LOAD_IMAGE) {
ImageView imageView = (ImageView)datas[0];
Drawable drawable = (Drawable)datas[1];
ImageLoaded callback = (ImageLoaded)datas[2];
if(callback == null)return;
callback.imageLoaded(imageView, drawable);
} else {
String file_path = datas[0].toString();
FileLoaded callback = (FileLoaded)datas[1];
if(callback == null)return;
callback.fileLoaded(file_path);
}
}
};
}
|
package org.jabref.gui.externalfiletype;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import org.jabref.Globals;
import org.jabref.gui.IconTheme;
import org.jabref.gui.JabRefDialog;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.JabRefIcon;
import org.jabref.gui.actions.MnemonicAwareAction;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.logic.l10n.Localization;
import com.jgoodies.forms.builder.ButtonBarBuilder;
import com.jgoodies.forms.builder.ButtonStackBuilder;
/**
* Editor for external file types.
*/
public class ExternalFileTypeEditor extends JabRefDialog {
private JFrame frame;
private JDialog dialog;
private List<ExternalFileType> fileTypes;
private JTable table;
private ExternalFileTypeEntryEditor entryEditor;
private FileTypeTableModel tableModel;
private final JButton ok = new JButton(Localization.lang("OK"));
private final JButton cancel = new JButton(Localization.lang("Cancel"));
private final JButton add = new JButton(IconTheme.JabRefIcons.ADD_NOBOX.getIcon());
private final JButton remove = new JButton(IconTheme.JabRefIcons.REMOVE_NOBOX.getIcon());
private final JButton edit = new JButton(IconTheme.JabRefIcons.EDIT.getIcon());
private final JButton toDefaults = new JButton(Localization.lang("Default"));
private final EditListener editListener = new EditListener();
private ExternalFileTypeEditor(JFrame frame) {
super(frame, Localization.lang("Manage external file types"), true, ExternalFileTypeEditor.class);
this.frame = frame;
init();
}
private ExternalFileTypeEditor(JDialog dialog) {
super(dialog, Localization.lang("Manage external file types"), true, ExternalFileTypeEditor.class);
this.dialog = dialog;
init();
}
/**
* Update the editor to show the current settings in Preferences.
*/
private void setValues() {
fileTypes.clear();
Collection<ExternalFileType> types = ExternalFileTypes.getInstance().getExternalFileTypeSelection();
for (ExternalFileType type : types) {
fileTypes.add(type.copy());
}
Collections.sort(fileTypes);
}
/**
* Store the list of external entry types to Preferences.
*/
private void storeSettings() {
ExternalFileTypes.getInstance().setExternalFileTypes(fileTypes);
}
private void init() {
ok.addActionListener(e -> {
storeSettings();
dispose();
});
Action cancelAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
};
cancel.addActionListener(cancelAction);
// The toDefaults resets the entire list to its default values.
toDefaults.addActionListener(e -> {
/*int reply = JOptionPane.showConfirmDialog(ExternalFileTypeEditor.this,
Globals.lang("All custom file types will be lost. Proceed?"),
Globals.lang("Reset file type definitions"), JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);*/
//if (reply == JOptionPane.YES_OPTION) {
List<ExternalFileType> list = ExternalFileTypes.getDefaultExternalFileTypes();
fileTypes.clear();
fileTypes.addAll(list);
Collections.sort(fileTypes);
//Globals.prefs.resetExternalFileTypesToDefault();
//setValues();
tableModel.fireTableDataChanged();
});
add.addActionListener(e -> {
// Generate a new file type:
ExternalFileType type = new ExternalFileType("", "", "", "", "new",
IconTheme.JabRefIcons.FILE);
// Show the file type editor:
getEditor(type).setVisible(true);
if (entryEditor.okPressed()) {
// Ok was pressed. Add the new file type and update the table:
fileTypes.add(type);
tableModel.fireTableDataChanged();
}
});
remove.addActionListener(e -> {
int[] rows = table.getSelectedRows();
if (rows.length == 0) {
return;
}
for (int i = rows.length - 1; i >= 0; i
fileTypes.remove(rows[i]);
}
tableModel.fireTableDataChanged();
if (!fileTypes.isEmpty()) {
int row = Math.min(rows[0], fileTypes.size() - 1);
table.setRowSelectionInterval(row, row);
}
});
edit.addActionListener(editListener);
fileTypes = new ArrayList<>();
setValues();
tableModel = new FileTypeTableModel();
table = new JTable(tableModel);
table.setDefaultRenderer(ImageIcon.class, new IconRenderer());
table.addMouseListener(new TableClickListener());
table.getColumnModel().getColumn(0).setMaxWidth(24);
table.getColumnModel().getColumn(0).setMinWidth(24);
table.getColumnModel().getColumn(1).setMinWidth(170);
table.getColumnModel().getColumn(2).setMinWidth(60);
table.getColumnModel().getColumn(3).setMinWidth(100);
table.getColumnModel().getColumn(0).setResizable(false);
JScrollPane sp = new JScrollPane(table);
JPanel upper = new JPanel();
upper.setLayout(new BorderLayout());
upper.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
upper.add(sp, BorderLayout.CENTER);
getContentPane().add(upper, BorderLayout.CENTER);
ButtonStackBuilder bs = new ButtonStackBuilder();
bs.addButton(add);
bs.addButton(remove);
bs.addButton(edit);
bs.addRelatedGap();
bs.addButton(toDefaults);
upper.add(bs.getPanel(), BorderLayout.EAST);
ButtonBarBuilder bb = new ButtonBarBuilder();
bb.addGlue();
bb.addButton(ok);
bb.addButton(cancel);
bb.addGlue();
bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
pack();
// Key bindings:
ActionMap am = upper.getActionMap();
InputMap im = upper.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
am.put("close", cancelAction);
am = bb.getPanel().getActionMap();
im = bb.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
am.put("close", cancelAction);
if (frame == null) {
setLocationRelativeTo(dialog);
} else {
setLocationRelativeTo(frame);
}
}
private ExternalFileTypeEntryEditor getEditor(ExternalFileType type) {
if (entryEditor == null) {
entryEditor = new ExternalFileTypeEntryEditor(ExternalFileTypeEditor.this, type);
} else {
entryEditor.setEntry(type);
}
return entryEditor;
}
/**
* Get an AbstractAction for opening the external file types editor.
* @param frame The JFrame used as parent window for the dialog.
* @return An Action for opening the editor.
*/
public static AbstractAction getAction(JabRefFrame frame) {
return new EditExternalFileTypesAction(frame);
}
/**
* Get an AbstractAction for opening the external file types editor.
* @param dialog The JDialog used as parent window for the dialog.
* @return An Action for opening the editor.
*/
public static AbstractAction getAction(JDialog dialog) {
return new EditExternalFileTypesAction(dialog);
}
class EditListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int[] rows = table.getSelectedRows();
if (rows.length != 1) {
return;
}
getEditor(fileTypes.get(rows[0])).setVisible(true);
if (entryEditor.okPressed()) {
tableModel.fireTableDataChanged();
}
}
}
static class IconRenderer implements TableCellRenderer {
private final JLabel lab = new JLabel();
@Override
public Component getTableCellRendererComponent(JTable tab, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
lab.setText(null);
lab.setIcon(((JabRefIcon) value).getIcon());
return lab;
}
}
private class FileTypeTableModel extends AbstractTableModel {
@Override
public int getColumnCount() {
return 5;
}
@Override
public int getRowCount() {
return fileTypes.size();
}
@Override
public String getColumnName(int column) {
switch (column) {
case 0:
return " ";
case 1:
return Localization.lang("Name");
case 2:
return Localization.lang("Extension");
case 3:
return Localization.lang("MIME type");
default: // Five columns
return Localization.lang("Application");
}
}
@Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == 0) {
return ImageIcon.class;
} else {
return String.class;
}
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
ExternalFileType type = fileTypes.get(rowIndex);
switch (columnIndex) {
case 0:
return type.getIcon();
case 1:
return type.getName();
case 2:
return type.getExtension();
case 3:
return type.getMimeType();
default:
return type.getOpenWithApplication();
}
}
}
class TableClickListener extends MouseAdapter {
private void handleClick(MouseEvent e) {
if (e.getClickCount() == 2) {
editListener.actionPerformed(null);
}
}
@Override
public void mouseClicked(MouseEvent e) {
handleClick(e);
}
@Override
public void mousePressed(MouseEvent e) {
handleClick(e);
}
@Override
public void mouseReleased(MouseEvent e) {
handleClick(e);
}
}
public static class EditExternalFileTypesAction extends MnemonicAwareAction {
private JabRefFrame frame;
private JDialog dialog;
private ExternalFileTypeEditor editor;
public EditExternalFileTypesAction(JabRefFrame frame) {
super();
putValue(Action.NAME, Localization.menuTitle("Manage external file types"));
this.frame = frame;
}
public EditExternalFileTypesAction(JDialog dialog) {
super();
putValue(Action.NAME, Localization.menuTitle("Manage external file types"));
this.dialog = dialog;
}
@Override
public void actionPerformed(ActionEvent e) {
if (editor == null) {
if (frame == null) {
editor = new ExternalFileTypeEditor(dialog);
} else {
editor = new ExternalFileTypeEditor(frame);
}
}
editor.setValues();
editor.setVisible(true);
}
}
}
|
package com.github.nutomic.controldlna.upnp;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Random;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.RemoteException;
import android.support.v7.media.MediaControlIntent;
import android.support.v7.media.MediaRouteDescriptor;
import android.support.v7.media.MediaRouteDiscoveryRequest;
import android.support.v7.media.MediaRouteProvider;
import android.support.v7.media.MediaRouteProviderDescriptor.Builder;
import android.support.v7.media.MediaRouter;
import android.support.v7.media.MediaRouter.ControlRequestCallback;
import android.util.Pair;
import android.util.SparseArray;
import android.widget.Toast;
/**
* Allows playing to a DLNA renderer from a remote app.
*
* @author Felix Ableitner
*/
final class Provider extends MediaRouteProvider {
// Device has been added.
// param: Device device
public static final int MSG_RENDERER_ADDED = 1;
// Device has been removed.
// param: int id
public static final int MSG_RENDERER_REMOVED = 2;
// Playback status information, retrieved after RemotePlayService.MSG_GET_STATUS.
// param: bundle media_item_status
// param: int hash
public static final int MSG_STATUS_INFO = 3;
// Indicates an error in communication between RemotePlayService and renderer.
// param: String error
public static final int MSG_ERROR = 4;
/**
* Allows passing and storing basic information about a device.
*/
static public class Device implements Parcelable {
public String id;
public String name;
public String description;
public int volume;
public int volumeMax;
public static final Parcelable.Creator<Device> CREATOR
= new Parcelable.Creator<Device>() {
public Device createFromParcel(Parcel in) {
return new Device(in);
}
public Device[] newArray(int size) {
return new Device[size];
}
};
private Device(Parcel in) {
id = in.readString();
name = in.readString();
description = in.readString();
volume = in.readInt();
volumeMax = in.readInt();
}
public Device(String id, String name, String description, int volume, int volumeMax) {
this.id = id;
this.name = name;
this.description = description;
this.volume = volume;
this.volumeMax = volumeMax;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(name);
dest.writeString(description);
dest.writeInt(volume);
dest.writeInt(volumeMax);
}
}
private HashMap<String, Device> mDevices = new HashMap<String, Device>();
private SparseArray<Pair<Intent, ControlRequestCallback>> mRequests =
new SparseArray<Pair<Intent, ControlRequestCallback>>();
IRemotePlayService mIRemotePlayService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mIRemotePlayService = IRemotePlayService.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName className) {
mIRemotePlayService = null;
}
};
private static final ArrayList<IntentFilter> CONTROL_FILTERS;
static {
IntentFilter f = new IntentFilter();
f.addCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK);
f.addAction(MediaControlIntent.ACTION_PLAY);
f.addAction(MediaControlIntent.ACTION_PAUSE);
f.addAction(MediaControlIntent.ACTION_SEEK);
f.addAction(MediaControlIntent.ACTION_STOP);
f.addDataScheme("http");
f.addDataScheme("https");
try {
/**
* Listens for messages about devices.
*/
static private class DeviceListener extends Handler {
private final WeakReference<Provider> mService;
DeviceListener(Provider provider) {
mService = new WeakReference<Provider>(provider);
}
@Override
public void handleMessage(Message msg) {
if (mService.get() != null)
mService.get().handleMessage(msg);
}
}
final Messenger mListener = new Messenger(new DeviceListener(this));
public Provider(Context context) {
super(context);
context.bindService(
new Intent(context, RemotePlayService.class),
mConnection,
Context.BIND_AUTO_CREATE
);
}
public void close() {
getContext().unbindService(mConnection);
}
@Override
public void onDiscoveryRequestChanged(MediaRouteDiscoveryRequest request) {
try {
if (request != null && request.isActiveScan() && mIRemotePlayService != null)
mIRemotePlayService.startSearch(mListener);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public RouteController onCreateRouteController(String routeId) {
return new RouteController(routeId);
}
private void updateRoutes() {
Builder builder = new Builder();
for (Entry<String, Device> d : mDevices.entrySet()) {
MediaRouteDescriptor routeDescriptor = new MediaRouteDescriptor.Builder(
d.getValue().id, d.getValue().name)
.setDescription(d.getValue().description)
.addControlFilters(CONTROL_FILTERS)
.setPlaybackType(MediaRouter.RouteInfo.PLAYBACK_TYPE_REMOTE)
.setVolumeHandling(MediaRouter.RouteInfo.PLAYBACK_VOLUME_VARIABLE)
.setVolumeMax(d.getValue().volumeMax)
.setVolume(d.getValue().volume)
.build();
builder.addRoute(routeDescriptor);
}
setDescriptor(builder.build());
}
/**
* Receives and forwards device selections, volume change
* requests and control requests.
*/
private final class RouteController extends MediaRouteProvider.RouteController {
private final String mRouteId;
public RouteController(String routeId) {
mRouteId = routeId;
}
@Override
public void onRelease() {
}
@Override
public void onSelect() {
try {
mIRemotePlayService.selectRenderer(mRouteId);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onUnselect() {
try {
mIRemotePlayService.unselectRenderer(mRouteId);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onSetVolume(int volume) {
if (volume < 0 || volume > mDevices.get(mRouteId).volumeMax)
return;
try {
mIRemotePlayService.setVolume(volume);
} catch (RemoteException e) {
e.printStackTrace();
}
mDevices.get(mRouteId).volume = volume;
updateRoutes();
}
@Override
public void onUpdateVolume(int delta) {
onSetVolume(mDevices.get(mRouteId).volume + delta);
}
/**
* Handles play, pause, resume, stop, seek and get_status requests for this route.
*/
@Override
public boolean onControlRequest(Intent intent, ControlRequestCallback callback) {
try {
if (intent.getAction().equals(MediaControlIntent.ACTION_PLAY)) {
String metadata = (intent.hasExtra(MediaControlIntent.EXTRA_ITEM_METADATA))
? intent.getExtras().getString(MediaControlIntent.EXTRA_ITEM_METADATA)
: null;
mIRemotePlayService.play(intent.getDataString(), metadata);
// Store in intent extras for later.
intent.putExtra(MediaControlIntent.EXTRA_SESSION_ID, mRouteId);
intent.putExtra(MediaControlIntent.EXTRA_ITEM_ID, intent.getDataString());
getItemStatus(intent, callback);
return true;
}
else if (intent.getAction().equals(MediaControlIntent.ACTION_PAUSE)) {
mIRemotePlayService.pause(mRouteId);
return true;
}
else if (intent.getAction().equals(MediaControlIntent.ACTION_RESUME)) {
mIRemotePlayService.resume(mRouteId);
return true;
}
else if (intent.getAction().equals(MediaControlIntent.ACTION_STOP)) {
mIRemotePlayService.stop(mRouteId);
return true;
}
else if (intent.getAction().equals(MediaControlIntent.ACTION_SEEK)) {
mIRemotePlayService.seek(mRouteId,
intent.getStringExtra(
MediaControlIntent.EXTRA_ITEM_ID),
intent.getLongExtra(
MediaControlIntent.EXTRA_ITEM_CONTENT_POSITION, 0));
getItemStatus(intent, callback);
return true;
}
else if(intent.getAction().equals(MediaControlIntent.ACTION_GET_STATUS)) {
getItemStatus(intent, callback);
return true;
}
} catch (RemoteException e) {
e.printStackTrace();
}
return false;
}
}
/**
* Requests status info via RemotePlayService, stores intent and callback to
* access later in handleMessage.
*/
private void getItemStatus(Intent intent, ControlRequestCallback callback)
throws RemoteException {
if (callback == null)
return;
Pair<Intent, ControlRequestCallback> pair =
new Pair<Intent, ControlRequestCallback>(intent, callback);
int r = new Random().nextInt();
mRequests.put(r, pair);
mIRemotePlayService.getItemStatus(
intent.getStringExtra(MediaControlIntent.EXTRA_SESSION_ID),
intent.getStringExtra(MediaControlIntent.EXTRA_ITEM_ID),
r);
}
/**
* Handles device add and remove as well as sending status info requested earlier.
*/
public void handleMessage(Message msg) {
Bundle data = msg.getData();
switch (msg.what) {
case MSG_RENDERER_ADDED:
msg.getData().setClassLoader(Device.class.getClassLoader());
Device device = (Device) data.getParcelable("device");
mDevices.put(device.id, device);
updateRoutes();
break;
case MSG_RENDERER_REMOVED:
mDevices.remove(data.getString("id"));
updateRoutes();
break;
case MSG_STATUS_INFO:
Pair<Intent, ControlRequestCallback> pair =
mRequests.get(data.getInt("hash"));
Bundle status = data.getBundle("media_item_status");
if (pair.first.hasExtra(MediaControlIntent.EXTRA_SESSION_ID))
status.putString(MediaControlIntent.EXTRA_SESSION_ID,
pair.first.getStringExtra(MediaControlIntent.EXTRA_SESSION_ID));
if (pair.first.hasExtra(MediaControlIntent.EXTRA_ITEM_ID))
status.putString(MediaControlIntent.EXTRA_ITEM_ID,
pair.first.getStringExtra(MediaControlIntent.EXTRA_ITEM_ID));
pair.second.onResult(status);
break;
case MSG_ERROR:
Toast.makeText(getContext(), data.getString("error"), Toast.LENGTH_SHORT).show();
break;
}
}
}
|
package org.jboss.msc.registry;
import java.util.Collection;
/**
* A batch builder for installing service definitions in a single action.
*/
public interface ServiceRegistrationBatchBuilder {
/**
* Install all the defined services into the container.
*
* @throws org.jboss.msc.registry.ServiceRegistryException
*/
void install() throws ServiceRegistryException;
/**
* Add a service definition to the batch.
*
* @param definition
* @return this batch
*/
ServiceRegistrationBatchBuilder add(ServiceDefinition definition);
/**
* Add a list of service batchEntries to the batch, in the order of the list.
*
* @param definitions add a list of service batchEntries to the batch, in the
* order of the list
* @return this batch
*/
ServiceRegistrationBatchBuilder add(ServiceDefinition<?>... definitions);
/**
* Add a collection of service batchEntries to the batch, in the order of the
* collection (if ordered).
*
* @param definitions add a list of service batchEntries to the batch, in the
* order of the list
* @return this batch
*/
ServiceRegistrationBatchBuilder add(Collection<ServiceDefinition<?>> definitions);
}
|
package com.hotmail.kalebmarc.textfighter.main;
import com.hotmail.kalebmarc.textfighter.item.Armour;
import com.hotmail.kalebmarc.textfighter.item.FirstAid;
import com.hotmail.kalebmarc.textfighter.item.InstaHealth;
import com.hotmail.kalebmarc.textfighter.item.Power;
import com.hotmail.kalebmarc.textfighter.player.*;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.representer.Representer;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
public class Saves {
private static DumperOptions options;
private static File saveLocation;
private static Map<String, Object> data;
private static Representer representer;
private static Scanner input;
private static String path;
private static Yaml yaml;
private static void setup() {
saveLocation = new File(path);
if (!saveLocation.exists())
try {
saveLocation.createNewFile();
} catch (IOException exception) {
exception.printStackTrace();
}
setupDumper();
yaml = new Yaml(representer, options);
data = Collections.synchronizedMap(new LinkedHashMap<String, Object>());
}
private static void setupDumper() {
options = new DumperOptions();
representer = new Representer();
options.setIndent(2);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setAllowUnicode(Charset.defaultCharset().name().contains("UTF"));
representer.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
}
public static boolean savesPrompt() {
User.promptNameSelection();
path = Saves.class.getProtectionDomain().getCodeSource().getLocation().getPath() + ".TFsave";
path = path.replace(".jar", "_" + User.name());
path = path.replaceAll("%20", " ");
Ui.cls();
Ui.println("
Ui.println("What would you like to do?");
Ui.println("
Ui.println("1) Load Save");
Ui.println("2) Convert Old Save");
Ui.println("3) Exit");
switch (Ui.getValidInt()) {
case 1:
load();
break;
case 2:
convert();
break;
default:
return false;
}
return true;
}
public static boolean load() {
setup();
FileReader reader = read(saveLocation);
if (reader == null) {
Ui.cls();
Ui.println("
Ui.println("Cannot find save file. ");
Ui.println("Starting a new game... ");
Ui.println("
Ui.pause();
data = Collections.synchronizedMap(new LinkedHashMap<String, Object>());
return true;
}
data = Collections.synchronizedMap((Map<String, Object>) yaml.load(reader));
//Health
Health.set(getInteger("User.Health"), getInteger("User.Max_Health"));
FirstAid.set(getInteger("User.FirstAid.Owns"), false);
FirstAid.used = getInteger("Stats.FirstAid.Used");
InstaHealth.set(getInteger("User.InstaHealth.Owns"), false);
InstaHealth.used = getInteger("Stats.InstaHealth.Used");
Health.timesDied = getInteger("Stats.TimesDied");
//Coins
Coins.set(getInteger("User.Balance"), false);
Bank.set(getInteger("Bank.Balance"), false);
Casino.totalCoinsWon = getInteger("Casino.Winnings");
Casino.gamesPlayed = getInteger("Casino.Plays");
Ach.boughtItem = getBoolean("Achievements.Bought_Item");
Stats.totalCoinsSpent = getInteger("Stats.Money_Spent.Coins");
Stats.coinsSpentOnBankInterest = getInteger("Stats.Money_Spent.Interest");
Stats.coinsSpentOnWeapons = getInteger("Stats.Money_Spent.Weapons");
Stats.coinsSpentOnHealth = getInteger("Stats.Money_Spent.Health");
Stats.xpBought = getInteger("Stats.Money_Spent.XP");
Loan.setCurrentLoan(getInteger("Bank.Current_Loan.Balance"));
Loan.setNetDue(getInteger("Bank.Current_Loan.Due"));
Xp.setLevel(getInteger("Stats.XP.Level"));
Xp.setOutOf(getInteger("Stats.XP.Needed"));
Xp.set(getInteger("Stats.XP.Amount"), false);
Xp.total = getInteger("Stats.XP.Total");
//Potions
Potion.spUsed = getInteger("Stats.Potions.Survival.Used");
Potion.rpUsed = getInteger("Stats.Potions.Recovery.Used");
Potion.set("survival", getInteger("User.Potions.Survival"), false);
Potion.set("recovery", getInteger("User.Potions.Recovery"), false);
//Settings
Settings.setDif(getString("Settings.Difficulty.Level"), false, false);
Settings.difLocked = getBoolean("Settings.Difficulty.Locked");
if(getBoolean("Settings.Cheats.Enabled")) Cheats.enable();
if(getBoolean("Settings.Cheats.Locked")) Cheats.lock();
Ui.guiEnabled = getBoolean("Settings.GUI.Enabled");
//Combat
Stats.kills = getInteger("Stats.Kills");
Stats.highScore = getInteger("Stats.High_Score");
Stats.totalKills = getInteger("Stats.Total_Kills");
Weapon.set(getInteger("User.Weapons.Current"));
List<String> weapons = new ArrayList<>();
String[] part;
for(int i = 0; i < weapons.size(); i++){
part = weapons.get(i).split(":");
if (Ui.isNumber(part[0])) {
Weapon.arrayWeapon.get(Integer.parseInt(part[0])).owns = true;
if (Ui.isNumber(part[1]))
Weapon.arrayWeapon.get(i).setAmmo(Integer.parseInt(part[1]), false);
}
}
Power.set(getInteger("User.Power"), false);
Power.used = getInteger("Stats.Power.Used");
Stats.totalDamageDealt = getInteger("Stats.Damage_Dealt");
Stats.bulletsFired = getInteger("Stats.Bullets_Fired");
Stats.bulletsThatHit = getInteger("Stats.Bullets_Hit");
List<Integer> armours = (List<Integer>) getList("User.Armour.Owns");
for(int i = 0; i < armours.size(); i++)
Armour.getArmours().get(i).setOwns(true);
Armour.set(getInteger("User.Armour.Current"));
//Enemy
Enemy.set(getInteger("Battle.Current.Enemy"));
Enemy.get().setHealth(getInteger("Battle.Current.Enemy_Health"), getInteger("Battle.Current.Enemy_Max_Health"));
//Achs
Ach.moneyMaker = getBoolean("Achievements.Money_Maker");
Ach.enemySlayer = getBoolean("Achievements.Enemy_Slayer");
Ach.firstKill = getBoolean("Achievements.First_Kill");
Ach.timeForAnUpgrade = getBoolean("Achievements.Time_For_An_Upgrade");
List<Boolean> achSet = (List<Boolean>) getList("Achievements.Enemies_Killed");
for (int i = 0; i < achSet.size(); i++)
Ach.arrayKilled.set(i, achSet.get(i));
Ach.textFighterMaster = getBoolean("Achievements.Text_Fighter_Master");
Ach.YAYPOWER = getBoolean("Achievements.YAY_POWER");
Ach.awwYouCareAboutMe = getBoolean("Achievements.Aww_You_Care_About_Me");
Ach.slayer = getBoolean("Achievements.Slayer");
Ach.nobodysPerfect = getBoolean("Achievements.Nobodys_Perfect");
Ach.makingMoney = getBoolean("Achievements.Making_Money");
Ach.gamblingAddiction = getBoolean("Achievements.Gabling_Addiction");
Ach.level2Fighter = getBoolean("Achievements.Level_2_Fighter");
Ach.level3Fighter = getBoolean("Achievements.Level_3_Fighter");
Ach.level4Fighter = getBoolean("Achievements.Level_4_Fighter");
Ach.level5Fighter = getBoolean("Achievements.Level_5_Fighter");
Ach.level6Fighter = getBoolean("Achievements.Level_6_Fighter");
Ach.level7Fighter = getBoolean("Achievements.Level_7_Fighter");
Ach.level8Fighter = getBoolean("Achievements.Level_8_Fighter");
Ach.level9Fighter = getBoolean("Achievements.Level_9_Fighter");
Ach.level10Fighter = getBoolean("Achievements.Level_10_Fighter");
Ach.honestPlayer = getBoolean("Achievements.Honest_Player");
Ach.learning = getBoolean("Achievements.Learning");
//Other Stuff
About.setViewed(getBoolean("Settings.About_Viewed"));
Stats.timesCheated = getInteger("Stats.Times_Cheated");
Stats.timesQuit = getInteger("Stats.Times_Quit");
Stats.itemsCrafted = getInteger("Stats.Items_Crafted");
Stats.diceGamesPlayed = getInteger("Stats.Games_Played.Dice");
Stats.slotGamesPlayed = getInteger("Stats.Games_Played.Slots");
return true;
}
public static boolean convert() {
Ui.cls();
Ui.println("
Ui.println("WARNING- Converting a save file may");
Ui.println("result in a corrupt save.");
Ui.println("It's recommended that you make a");
Ui.println("backup of your current save file(s)");
Ui.println("before you continue.");
Ui.println("
Ui.println("1) Exit");
Ui.println("2) Continue");
switch(Ui.getValidInt()){
case 1:
return false;
case 2:
break;
default:
return false;
}
try {
File file = new File(path);
if (!file.exists()) {
Ui.println("File not found. Please put an \"_\" before your username in the save file.");
System.exit(0);
}
input = new Scanner(file);
setup();
readString();
//Health
Health.set(readInt(), readInt());
FirstAid.set(readInt(), false);
FirstAid.used = readInt();
InstaHealth.set(readInt(), false);
InstaHealth.used = readInt();
Health.timesDied = readInt();
//Coins
Coins.set(readInt(), false);
Bank.set(readInt(), false);
Casino.totalCoinsWon = readInt();
Casino.gamesPlayed = readInt();
Ach.boughtItem = readBoolean();
Stats.totalCoinsSpent = readInt();
Stats.coinsSpentOnBankInterest = readInt();
Stats.coinsSpentOnWeapons = readInt();
Stats.coinsSpentOnHealth = readInt();
Stats.xpBought = readInt();
Loan.setCurrentLoan(readInt());
Loan.setNetDue(readInt());
Xp.setLevel(readInt());
Xp.setOutOf(readInt());
Xp.set(readInt(), false);
Xp.total = readInt();
//Potions
Potion.spUsed = readInt();
Potion.rpUsed = readInt();
Potion.set("survival", readInt(), false);
Potion.set("recovery", readInt(), false);
//Settings
Settings.setDif(input.nextLine(), false, false);
if (readBoolean()) Cheats.enable();
if (readBoolean()) Cheats.lock();
Settings.difLocked = readBoolean();
Ui.guiEnabled = readBoolean();
//Combat
Stats.kills = readInt();
Stats.highScore = readInt();
Stats.totalKills = readInt();
Weapon.set(readInt());
for (int i = 0; i < Weapon.arrayWeapon.size(); i++)
Weapon.arrayWeapon.get(i).owns = readBoolean();
for (int i = 0; i < Weapon.arrayWeapon.size(); i++)
Weapon.arrayWeapon.get(i).setAmmo(readInt(), false);
Power.set(readInt(), false);
Power.used = readInt();
Stats.totalDamageDealt = readInt();
Stats.bulletsFired = readInt();
Stats.bulletsThatHit = readInt();
for (int i = 0; i < Armour.getArmours().size(); i++)
Armour.getArmours().get(i).setOwns(readBoolean());
Armour.set(readInt());
//Enemy
Enemy.set(readInt());
Enemy.get().setHealth(readInt(), Enemy.get().getHealthMax());
//Achs
Ach.moneyMaker = readBoolean();
Ach.enemySlayer = readBoolean();
Ach.firstKill = readBoolean();
Ach.timeForAnUpgrade = readBoolean();
for (int i = 0; i < Enemy.arrayEnemy.size(); i++)
Ach.arrayKilled.set(i, readBoolean());
Ach.textFighterMaster = readBoolean();
Ach.YAYPOWER = readBoolean();
Ach.awwYouCareAboutMe = readBoolean();
Ach.slayer = readBoolean();
Ach.nobodysPerfect = readBoolean();
Ach.makingMoney = readBoolean();
Ach.gamblingAddiction = readBoolean();
Ach.level2Fighter = readBoolean();
Ach.level3Fighter = readBoolean();
Ach.level4Fighter = readBoolean();
Ach.level5Fighter = readBoolean();
Ach.level6Fighter = readBoolean();
Ach.level7Fighter = readBoolean();
Ach.level8Fighter = readBoolean();
Ach.level9Fighter = readBoolean();
Ach.level10Fighter = readBoolean();
Ach.honestPlayer = readBoolean();
Ach.learning = readBoolean();
//Other Stuff
About.setViewed(readBoolean());
Stats.timesCheated = readInt();
Stats.timesQuit = readInt();
Stats.itemsCrafted = readInt();
Stats.diceGamesPlayed = readInt();
Stats.slotGamesPlayed = readInt();
save();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return true;
}
public static boolean contains(String key) {
return data.containsKey(key);
}
public static boolean exists() {
return data != null;
}
public static boolean getBoolean(String key) {
Object tempObject = get(key);
if (tempObject instanceof Boolean)
return (Boolean) tempObject;
if (tempObject instanceof String)
if (tempObject.toString().equalsIgnoreCase("true") || tempObject.toString().equalsIgnoreCase("1"))
return true;
else if (tempObject.toString().equalsIgnoreCase("false") || tempObject.toString().equalsIgnoreCase("0"))
return false;
if (tempObject instanceof Number)
if (((Number) tempObject).intValue() == 1)
return true;
else if (((Number) tempObject).intValue() == 0)
return false;
return false;
}
public static boolean hasValue(String key) {
Object tempObject = data.get(key);
return (tempObject != null);
}
public static boolean isEmpty() {
return data.isEmpty() || data == null;
}
public static byte getByte(String key) {
Object tempObject = get(key);
if (tempObject instanceof Byte)
return (Byte) tempObject;
if (tempObject instanceof String)
if (Ui.isNumber(tempObject.toString()))
return Byte.parseByte(tempObject.toString());
if (tempObject instanceof Number)
return Byte.parseByte(tempObject.toString());
return -1;
}
public static char getChar(String key) {
Object tempObject = get(key);
if (tempObject instanceof Character)
return (Character) tempObject;
if (tempObject instanceof String)
return tempObject.toString().charAt(0);
if (tempObject instanceof Number)
return tempObject.toString().charAt(0);
return '\u0000';
}
public static double getDouble(String key) {
Object tempObject = get(key);
if (tempObject instanceof Double)
return (Double) tempObject;
if (tempObject instanceof String)
if (Ui.isDecimalNumber(tempObject.toString()))
return Double.parseDouble(tempObject.toString());
if (tempObject instanceof Number)
return Double.parseDouble(tempObject.toString());
return -1;
}
public static int getInteger(String key) {
Object tempObject = get(key);
if (tempObject instanceof Integer)
return (Integer) tempObject;
if (tempObject instanceof String)
if (Ui.isNumber(tempObject.toString()))
return Integer.parseInt(tempObject.toString());
if (tempObject instanceof Number)
return Integer.parseInt(tempObject.toString());
return -1;
}
public static List<?> getList(String key) {
Object tempObject = get(key);
if (tempObject instanceof List<?>)
return (List) tempObject;
return null;
}
public static long getLong(String key) {
Object tempObject = get(key);
if (tempObject instanceof Long)
return (Long) tempObject;
if (tempObject instanceof String)
if (Ui.isNumber(tempObject.toString()))
return Long.parseLong(tempObject.toString());
if (tempObject instanceof Number)
return Long.parseLong(tempObject.toString());
return -1;
}
public static Map<?, ?> getMap(String key) {
Object tempObject = get(key);
if (tempObject instanceof Map<?, ?>)
return (Map) tempObject;
return null;
}
public static Map<String, Object> getValues() {
if (!isEmpty())
return data;
return null;
}
public static Object get(String key) {
if (isEmpty())
return null;
if (key.contains(".")) {
String[] nodes = key.split("\\.");
Map<String, Object> currParent;
if (data.containsKey(nodes[0]) && (data.get(nodes[0]) instanceof Map))
currParent = (Map) data.get(nodes[0]);
else return null;
if (nodes.length > 1) {
for (int i = 1; i < nodes.length - 1; i++) {
if (currParent.containsKey(nodes[i]) && (currParent.get(nodes[i]) instanceof Map))
currParent = (Map) currParent.get(nodes[i]);
else return null;
}
if (currParent.containsKey(nodes[nodes.length - 1]))
return currParent.get(nodes[nodes.length - 1]);
}
} else if (!contains(key) || (contains(key) && !hasValue(key)))
return null;
return data.get(key);
}
public static Set<String> getKeys() {
if (!isEmpty())
return data.keySet();
return new HashSet<>();
}
public static short getShort(String key) {
Object tempObject = get(key);
if (tempObject instanceof Short)
return (Short) tempObject;
if (tempObject instanceof String)
if (Ui.isNumber(tempObject.toString()))
return Short.parseShort(tempObject.toString());
if (tempObject instanceof Number)
return Short.parseShort(tempObject.toString());
return -1;
}
public static String getString(String key) {
Object tempObject = get(key);
if (tempObject instanceof String)
return (String) tempObject;
return null;
}
public static FileReader read(File file) {
try {
if (!file.exists())
return null;
return new FileReader(file);
} catch (FileNotFoundException exception) {
exception.printStackTrace();
}
return null;
}
/**
*
* @return the next line as an integer
*/
private static int readInt(){
return Integer.parseInt(input.nextLine());
}
/**
*
* @return the next line as a boolean
*/
private static boolean readBoolean(){
return Boolean.parseBoolean(input.nextLine());
}
/**
*
* @return the next line as a String
*/
private static String readString(){
return input.nextLine();
}
public static void save() {
path = Saves.class.getProtectionDomain().getCodeSource().getLocation().getPath() + ".TFsave";
path = path.replace(".jar", "_" + User.name());
path = path.replaceAll("%20", " ");
setup();
/*
* TODO: make a version checker that checks each part of a version ex: 1.4.1DEV
* then determine whether or not it's older, current or newer.
*/
set("Version", Version.getFull());
//Health
set("User.Health", Health.get());
set("User.Max_Health", Health.getOutOf());
set("User.FirstAid.Owns", FirstAid.get());
set("Stats.FirstAid.Used", FirstAid.used);
set("User.InstaHealth.Owns", InstaHealth.get());
set("Stats.InstaHealth.Used", InstaHealth.used); // not saving
set("Stats.TimesDied", Health.timesDied);
//Coins
set("User.Balance", Coins.get());
set("Bank.Balance", Bank.get());
set("Casino.Winnings", Casino.totalCoinsWon);
set("Casino.Plays", Casino.gamesPlayed);
set("Achievements.Bought_Item", Ach.boughtItem);
set("Stats.Money_Spent.Coins", Stats.totalCoinsSpent);
set("Stats.Money_Spent.Interest", Stats.coinsSpentOnBankInterest);
set("Stats.Money_Spent.Weapons", Stats.coinsSpentOnWeapons);
set("Stats.Money_Spent.Health", Stats.coinsSpentOnHealth);
set("Stats.Money_Spent.XP", Stats.xpBought);
set("Bank.Current_Loan.Balance", Loan.getCurrentLoan());
set("Bank.Current_Loan.Due", Loan.getNetDue());
set("Stats.XP.Level", Xp.getLevel());
set("Stats.XP.Needed", Xp.getOutOf());
set("Stats.XP.Amount", Xp.get());
set("Stats.XP.Total", Xp.total);
//Potions
set("Stats.Potions.Survival.Used", Potion.spUsed);
set("Stats.Potions.Recovery.Used", Potion.rpUsed);
set("User.Potions.Survival", Potion.get("survival"));
set("User.Potions.Recovery", Potion.get("recovery"));
//Settings
set("Settings.Difficulty.Level", Settings.getDif());
set("Settings.Difficulty.Locked", Settings.difLocked);
set("Settings.Cheats.Enabled", Cheats.enabled()); // not saving
set("Settings.Cheats.Locked", Cheats.locked()); // not saving
set("Settings.GUI.Enabled", Ui.guiEnabled); // not saving
//Combat
set("Stats.Kills", Stats.kills);
set("Stats.High_Score", Stats.highScore);
set("User.Weapons.Current", Weapon.get());
List<String> ownedWeapons = new ArrayList<>();
for (int i = 0; i < Weapon.arrayWeapon.size(); i++)
if (Weapon.arrayWeapon.get(i).owns())
ownedWeapons.add(i + ":" + Weapon.arrayWeapon.get(i).getAmmo());
set("User.Weapons.Owns", ownedWeapons);
set("User.Power", Power.get());
set("Stats.Power.Used", Power.used);
set("Stats.Damage_Dealt", Stats.totalDamageDealt);
set("Stats.Bullets_Fired", Stats.bulletsFired);
set("Stats.Bullets_Hit", Stats.bulletsThatHit);
List<Integer> ownedArmour = new ArrayList<>();
for (int i = 0; i < Armour.getArmours().size(); i++)
if (Armour.getArmours().get(i).isOwns())
ownedArmour.add(i);
set("User.Armour.Owns", ownedArmour);
set("User.Armour.Current", Armour.get());
//Enemy
set("Battle.Current.Enemy", Enemy.arrayEnemy.indexOf(Enemy.get()));
set("Battle.Current.Enemy_Health", Enemy.get().getHealth());
set("Battle.Current.Enemy_Max_Health", Enemy.get().getHealthMax());
//Achs
set("Achievements.Money_Maker", Ach.moneyMaker);
set("Achievements.Enemy_Slayer", Ach.enemySlayer);
set("Achievements.First_Kill", Ach.firstKill);
set("Achievements.Time_For_An_Upgrade", Ach.timeForAnUpgrade);
List<String> enemiesKilled = new ArrayList<>();
for (int i = 0; i < Enemy.arrayEnemy.size(); i++)
if (Ach.arrayKilled.get(i))
enemiesKilled.add(Enemy.arrayEnemy.get(i).getName());
set("Achievements.Enemies_Killed", enemiesKilled);
set("Achievements.Text_Fighter_Master", Ach.textFighterMaster);
set("Achievements.YAY_POWER", Ach.YAYPOWER);
set("Achievements.Aww_You_Care_About_Me", Ach.awwYouCareAboutMe);
set("Achievements.Slayer", Ach.slayer);
set("Achievements.Nobodys_Perfect", Ach.nobodysPerfect);
set("Achievements.Making_Money", Ach.makingMoney);
set("Achievements.Gambling_Addiction", Ach.gamblingAddiction);
set("Achievements.Level_2_Fighter", Ach.level2Fighter);
set("Achievements.Level_3_Fighter", Ach.level3Fighter);
set("Achievements.Level_4_Fighter", Ach.level4Fighter);
set("Achievements.Level_5_Fighter", Ach.level5Fighter);
set("Achievements.Level_6_Fighter", Ach.level6Fighter);
set("Achievements.Level_7_Fighter", Ach.level7Fighter);
set("Achievements.Level_8_Fighter", Ach.level8Fighter);
set("Achievements.Level_9_Fighter", Ach.level9Fighter);
set("Achievements.Level_10_Fighter", Ach.level10Fighter);
set("Achievements.Honest_Player", Ach.honestPlayer);
set("Achievements.Learning", Ach.learning);
//Other Stuff
set("Settings.About_Viewed", About.viewed());
set("Stats.Times_Cheated", Stats.timesCheated);
set("Stats.Times_Quit", Stats.timesQuit);
set("Stats.Items_Crafted", Stats.timesCheated);
set("Stats.Games_Played.Dice", Stats.diceGamesPlayed);
set("Stats.Games_Played.Slots", Stats.slotGamesPlayed);
try {
if (!saveLocation.exists())
saveLocation.createNewFile();
FileWriter writer = new FileWriter(saveLocation);
writer.write(yaml.dump(data));
writer.flush();
writer.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
public static void set(String key, Object object) {
if (!exists())
return;
if (key.contains(".")) {
String[] nodes = key.split("\\.");
// if data doesn't contain top-level node, create nested Maps
if (!data.containsKey(nodes[0])) {
Map<String, Object> currNode = new HashMap<>(), prevNode;
currNode.put(nodes[nodes.length - 1], object);
for (int i = nodes.length - 2; i > 0; i
prevNode = currNode;
currNode = new HashMap<>();
currNode.put(nodes[i], prevNode);
}
// set top-level node to previous parent
data.put(nodes[0], currNode);
} else { // if data contains top-level node, work through each Map
Map[] prevNodes = new LinkedHashMap[nodes.length - 1];
if (nodes.length > 1) {
for (int i = 0; i <= nodes.length - 2; i++) {
if (data.containsKey(nodes[i]) && (data.get(nodes[i]) instanceof Map))
prevNodes[i] = new LinkedHashMap((Map) data.get(nodes[i]));
else if (!data.containsKey(nodes[i]))
prevNodes[i] = new LinkedHashMap();
else return; // TODO: Add protection boolean
}
prevNodes[prevNodes.length - 1].put(nodes[nodes.length - 1], object);
for (int i = prevNodes.length - 1; i > 1; i
prevNodes[i - 1].put(nodes[i], prevNodes[i]);
data.put(nodes[0], prevNodes[0]);
} else data.put(nodes[0], object);
}
return;
}
data.put(key, object);
}
}
|
package com.inductiveautomation.opcua.stack.client.handlers;
import java.nio.ByteOrder;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import com.google.common.collect.Lists;
import com.inductiveautomation.opcua.stack.client.UaTcpStackClient;
import com.inductiveautomation.opcua.stack.core.StatusCodes;
import com.inductiveautomation.opcua.stack.core.UaException;
import com.inductiveautomation.opcua.stack.core.channel.ChannelSecurity;
import com.inductiveautomation.opcua.stack.core.channel.ClientSecureChannel;
import com.inductiveautomation.opcua.stack.core.channel.SerializationQueue;
import com.inductiveautomation.opcua.stack.core.channel.headers.HeaderDecoder;
import com.inductiveautomation.opcua.stack.core.channel.headers.SymmetricSecurityHeader;
import com.inductiveautomation.opcua.stack.core.channel.messages.ErrorMessage;
import com.inductiveautomation.opcua.stack.core.channel.messages.MessageType;
import com.inductiveautomation.opcua.stack.core.channel.messages.TcpMessageDecoder;
import com.inductiveautomation.opcua.stack.core.serialization.UaMessage;
import com.inductiveautomation.opcua.stack.core.serialization.UaRequestMessage;
import com.inductiveautomation.opcua.stack.core.serialization.UaResponseMessage;
import com.inductiveautomation.opcua.stack.core.types.structured.ServiceFault;
import com.inductiveautomation.opcua.stack.core.util.BufferUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UaTcpClientSymmetricHandler extends ByteToMessageCodec<UaRequestMessage> implements HeaderDecoder {
private final Logger logger = LoggerFactory.getLogger(getClass());
private List<ByteBuf> chunkBuffers;
private final ClientSecureChannel secureChannel;
private final int maxChunkCount;
private final int maxChunkSize;
private final UaTcpStackClient client;
private final SerializationQueue serializationQueue;
private final CompletableFuture<Channel> handshakeFuture;
public UaTcpClientSymmetricHandler(UaTcpStackClient client,
SerializationQueue serializationQueue,
CompletableFuture<Channel> handshakeFuture) {
this.client = client;
this.serializationQueue = serializationQueue;
this.handshakeFuture = handshakeFuture;
secureChannel = client.getSecureChannel();
maxChunkCount = serializationQueue.getParameters().getLocalMaxChunkCount();
maxChunkSize = serializationQueue.getParameters().getLocalReceiveBufferSize();
chunkBuffers = Lists.newArrayListWithCapacity(maxChunkCount);
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
List<UaMessage> awaitingHandshake = ctx.channel().attr(UaTcpClientAcknowledgeHandler.AWAITING_HANDSHAKE_KEY).get();
if (awaitingHandshake != null) {
logger.debug("{} message(s) queued before handshake completed; sending now.", awaitingHandshake.size());
awaitingHandshake.forEach(m -> ctx.pipeline().write(m));
ctx.flush();
ctx.channel().attr(UaTcpClientAcknowledgeHandler.AWAITING_HANDSHAKE_KEY).set(null);
}
client.getExecutorService().execute(() -> handshakeFuture.complete(ctx.channel()));
}
@Override
protected void encode(ChannelHandlerContext ctx, UaRequestMessage message, ByteBuf out) throws Exception {
serializationQueue.encode((binaryEncoder, chunkEncoder) -> {
ByteBuf messageBuffer = BufferUtil.buffer();
try {
binaryEncoder.setBuffer(messageBuffer);
binaryEncoder.encodeMessage(null, message);
List<ByteBuf> chunks = chunkEncoder.encodeSymmetric(
secureChannel,
MessageType.SecureMessage,
messageBuffer,
chunkEncoder.nextRequestId()
);
ctx.executor().execute(() -> {
chunks.forEach(c -> ctx.write(c, ctx.voidPromise()));
ctx.flush();
});
} catch (UaException e) {
logger.error("Error encoding {}: {}", message.getClass(), e.getMessage(), e);
ctx.close();
} finally {
messageBuffer.release();
}
});
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);
while (buffer.readableBytes() >= HeaderLength &&
buffer.readableBytes() >= getMessageLength(buffer)) {
int messageLength = getMessageLength(buffer);
MessageType messageType = MessageType.fromMediumInt(buffer.getMedium(buffer.readerIndex()));
switch (messageType) {
case SecureMessage:
onSecureMessage(ctx, buffer.readSlice(messageLength), out);
break;
case Error:
onError(ctx, buffer.readSlice(messageLength));
break;
default:
out.add(buffer.readSlice(messageLength).retain());
}
}
}
private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws UaException {
buffer.skipBytes(3); // Skip messageType
char chunkType = (char) buffer.readByte();
if (chunkType == 'A') {
chunkBuffers.forEach(ByteBuf::release);
chunkBuffers.clear();
} else {
buffer.skipBytes(4);
long secureChannelId = buffer.readUnsignedInt();
if (secureChannelId != secureChannel.getChannelId()) {
throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid,
"invalid secure channel id: " + secureChannelId);
}
SymmetricSecurityHeader securityHeader = SymmetricSecurityHeader.decode(buffer);
ChannelSecurity channelSecurity = secureChannel.getChannelSecurity();
long currentTokenId = channelSecurity.getCurrentToken().getTokenId().longValue();
if (securityHeader.getTokenId() != currentTokenId) {
long previousTokenId = channelSecurity.getPreviousToken()
.map(t -> t.getTokenId().longValue())
.orElse(-1L);
if (securityHeader.getTokenId() != previousTokenId) {
throw new UaException(StatusCodes.Bad_SecureChannelTokenUnknown,
"unknown secure channel token: " + securityHeader.getTokenId());
}
}
int chunkSize = buffer.readerIndex(0).readableBytes();
if (chunkSize > maxChunkSize) {
throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
String.format("max chunk size exceeded (%s)", maxChunkSize));
}
chunkBuffers.add(buffer.retain());
if (chunkBuffers.size() > maxChunkCount) {
throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
String.format("max chunk count exceeded (%s)", maxChunkCount));
}
if (chunkType == 'F') {
final List<ByteBuf> buffersToDecode = chunkBuffers;
chunkBuffers = Lists.newArrayListWithCapacity(maxChunkCount);
serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
try {
ByteBuf messageBuffer = chunkDecoder.decodeSymmetric(
secureChannel,
MessageType.SecureMessage,
buffersToDecode
);
binaryDecoder.setBuffer(messageBuffer);
UaResponseMessage response = binaryDecoder.decodeMessage(null);
if (response instanceof ServiceFault) {
client.getExecutorService().execute(() -> client.receiveServiceFault((ServiceFault) response));
} else {
client.getExecutorService().execute(() -> client.receiveServiceResponse(response));
}
messageBuffer.release();
buffersToDecode.clear();
} catch (UaException e) {
logger.error("Error decoding symmetric message: {}", e.getMessage(), e);
ctx.close();
serializationQueue.pause();
}
});
}
}
}
private void onError(ChannelHandlerContext ctx, ByteBuf buffer) {
try {
ErrorMessage error = TcpMessageDecoder.decodeError(buffer);
logger.error("Received error message: " + error);
} catch (UaException e) {
logger.error("An exception occurred while decoding an error message: {}", e.getMessage(), e);
} finally {
ctx.close();
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
handshakeFuture.completeExceptionally(
new UaException(StatusCodes.Bad_ConnectionClosed, "connection closed"));
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.error("Exception caught: {}", cause.getMessage(), cause);
ctx.close();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.