input
stringlengths 20
285k
| output
stringlengths 20
285k
|
---|---|
public void duplicateWeekEndingMessageShouldDisappearWhenBlankWeekEndingDateSubmitted() {
WebElement newTimesheetButton = webDriver.findElement(By.id("new_timesheet"));
newTimesheetButton.click();
chooseParticularSundayAsWeekEndingDate(1);
WebElement dateSubmitButton = webDriver.findElement(By.id("submit"));
dateSubmitButton.click();
WebElement timesheetSubmitButton = webDriver.findElement(By.id("submit"));
timesheetSubmitButton.click();
waitForVisibilityOfElementById("new_timesheet").click();
chooseParticularSundayAsWeekEndingDate(1);
waitForVisibilityOfElementById("submit").click();
waitForVisibilityOfElementById("submit").click();
WebElement message = webDriver.findElement(By.xpath("//label[@class='error']"));
assertFalse(message.getText().contains(getExpectedErrorMessage("DuplicateTimesheetForWeek")));
}
| public void duplicateWeekEndingMessageShouldDisappearWhenBlankWeekEndingDateSubmitted() {
WebElement newTimesheetButton = webDriver.findElement(By.id("new_timesheet"));
newTimesheetButton.click();
chooseParticularSundayAsWeekEndingDate(2);
WebElement dateSubmitButton = webDriver.findElement(By.id("submit"));
dateSubmitButton.click();
WebElement timesheetSubmitButton = webDriver.findElement(By.id("submit"));
timesheetSubmitButton.click();
waitForVisibilityOfElementById("new_timesheet").click();
chooseParticularSundayAsWeekEndingDate(2);
waitForVisibilityOfElementById("submit").click();
waitForVisibilityOfElementById("submit").click();
WebElement message = webDriver.findElement(By.xpath("//label[@class='error']"));
assertFalse(message.getText().contains(getExpectedErrorMessage("DuplicateTimesheetForWeek")));
}
|
public T delegate() {
if (this.instance != null) {
Class<? extends T> temp = ServiceClassDiscovery.discoverImplementation(this.abstractClass, this.defaultImpl);
if (temp == null) {
throw new RuntimeException("Cannot find an implementation for the abstract class " + this.abstractClass.getName());
}
try {
this.instance = temp.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("Cannot instantiate implmentation " + temp.getName(), e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Cannot instantiate implmentation " + temp.getName(), e);
}
}
return this.instance;
}
| public T delegate() {
if (this.instance == null) {
Class<? extends T> temp = ServiceClassDiscovery.discoverImplementation(this.abstractClass, this.defaultImpl);
if (temp == null) {
throw new RuntimeException("Cannot find an implementation for the abstract class " + this.abstractClass.getName());
}
try {
this.instance = temp.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("Cannot instantiate implmentation " + temp.getName(), e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Cannot instantiate implmentation " + temp.getName(), e);
}
}
return this.instance;
}
|
public int processChat(List<TCChatLine> theChat) {
this.serverDataLock.acquireUninterruptibly();
this.serverDataLock.release();
ArrayList<TCChatLine> filteredChatLine = new ArrayList<TCChatLine>(theChat.size());
List<String> toTabs = new ArrayList<String>();
toTabs.add("*");
int _ind;
int ret = 0;
boolean skip = false;
int n = theChat.size();
StringBuilder filteredChat = new StringBuilder(theChat.get(0).getChatLineString().length() * n);
for (int z=0; z<n; z++)
filteredChat.append(theChat.get(z).getChatLineString());
for (int i = 0; i < filterSettings.numFilters; i++) {
if (!filterSettings.applyFilterToDirtyChat(i, filteredChat.toString())) continue;
if (filterSettings.removeMatches(i)) {
toTabs.clear();
toTabs.add("*");
skip = true;
break;
}
filteredChat = new StringBuilder(filterSettings.getLastMatchPretty());
if (filterSettings.sendToTabBool(i)) {
if (filterSettings.sendToAllTabs(i)) {
toTabs.clear();
for (ChatChannel chan : this.channelMap.values())
toTabs.add(chan.title);
skip = true;
continue;
} else {
String destTab = filterSettings.sendToTabName(i);
if (!this.channelMap.containsKey(destTab)) {
this.channelMap.put(destTab, new ChatChannel(destTab));
}
if (!toTabs.contains(destTab))
toTabs.add(destTab);
}
}
if (filterSettings.audioNotificationBool(i))
filterSettings.audioNotification(i);
}
Iterator splitChat = mc.fontRenderer.listFormattedStringToWidth(filteredChat.toString(), gnc.chatWidth).iterator();
boolean firstline = true;
while (splitChat.hasNext()) {
String _line = (String)splitChat.next();
if (!firstline)
_line = " " + _line;
filteredChatLine.add(new TCChatLine(theChat.get(0).getUpdatedCounter(), _line, theChat.get(0).getChatLineID()));
firstline = false;
}
for (String c : toTabs) {
this.addToChannel(c, filteredChatLine);
}
for (String _act : this.getActive()) {
if (toTabs.contains(_act))
ret++;
}
String coloredChat = "";
for (ChatLine cl : theChat)
coloredChat = coloredChat + cl.getChatLineString();
String cleanedChat = StringUtils.stripControlCodes(coloredChat);
if (generalSettings.saveChatLog.getValue()) TabbyChatUtils.logChat(this.withTimeStamp(cleanedChat));
if (!skip) {
Matcher findChannelClean = this.chatChannelPatternClean.matcher(cleanedChat);
Matcher findChannelDirty = this.chatChannelPatternDirty.matcher(coloredChat);
String cName = null;
boolean dirtyValid = (!serverSettings.delimColorBool.getValue() && !serverSettings.delimFormatBool.getValue()) ? true : findChannelDirty.find();
if (findChannelClean.find() && dirtyValid) {
cName = findChannelClean.group(1);
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
} else if(this.chatPMtoMePattern != null){
Matcher findPMtoMe = this.chatPMtoMePattern.matcher(cleanedChat);
if (findPMtoMe.find()) {
for(int i=1;i<=findPMtoMe.groupCount();i++) {
if(findPMtoMe.group(i) != null) {
cName = findPMtoMe.group(i);
ChatChannel newPM = new ChatChannel(cName);
newPM.cmdPrefix = "/msg "+cName;
this.channelMap.put(cName, newPM);
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
break;
}
}
} else if(this.chatPMfromMePattern != null) {
Matcher findPMfromMe = this.chatPMfromMePattern.matcher(cleanedChat);
if (findPMfromMe.find()) {
for(int i=1;i<=findPMfromMe.groupCount();i++) {
if(findPMfromMe.group(i) != null) {
cName = findPMfromMe.group(i);
ChatChannel newPM = new ChatChannel(cName);
newPM.cmdPrefix = "/msg "+cName;
this.channelMap.put(cName, newPM);
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
break;
}
}
}
}
}
}
if (ret == 0) {
for (String c : toTabs) {
if (c != "*" && this.channelMap.containsKey(c)) {
this.channelMap.get(c).unread = true;
}
}
}
List<String> activeTabs = this.getActive();
if (generalSettings.groupSpam.getValue() && activeTabs.size() > 0) {
if (toTabs.contains(activeTabs.get(0)))
this.lastChat = this.channelMap.get(activeTabs.get(0)).chatLog.subList(0, filteredChatLine.size());
else
this.lastChat = this.withTimeStamp(filteredChatLine);
} else
this.lastChat = this.withTimeStamp(filteredChatLine);
if (ret > 0) {
if (generalSettings.groupSpam.getValue() && this.channelMap.get(activeTabs.get(0)).hasSpam) {
gnc.setChatLines(0, this.lastChat);
} else {
gnc.addChatLines(0, this.lastChat);
}
}
return ret;
}
| public int processChat(List<TCChatLine> theChat) {
this.serverDataLock.acquireUninterruptibly();
this.serverDataLock.release();
ArrayList<TCChatLine> filteredChatLine = new ArrayList<TCChatLine>(theChat.size());
List<String> toTabs = new ArrayList<String>();
toTabs.add("*");
int _ind;
int ret = 0;
boolean skip = false;
int n = theChat.size();
StringBuilder filteredChat = new StringBuilder(theChat.get(0).getChatLineString().length() * n);
for (int z=0; z<n; z++)
filteredChat.append(theChat.get(z).getChatLineString());
for (int i = 0; i < filterSettings.numFilters; i++) {
if (!filterSettings.applyFilterToDirtyChat(i, filteredChat.toString())) continue;
if (filterSettings.removeMatches(i)) {
toTabs.clear();
toTabs.add("*");
skip = true;
break;
}
filteredChat = new StringBuilder(filterSettings.getLastMatchPretty());
if (filterSettings.sendToTabBool(i)) {
if (filterSettings.sendToAllTabs(i)) {
toTabs.clear();
for (ChatChannel chan : this.channelMap.values())
toTabs.add(chan.title);
skip = true;
continue;
} else {
String destTab = filterSettings.sendToTabName(i);
if (!this.channelMap.containsKey(destTab)) {
this.channelMap.put(destTab, new ChatChannel(destTab));
}
if (!toTabs.contains(destTab))
toTabs.add(destTab);
}
}
if (filterSettings.audioNotificationBool(i))
filterSettings.audioNotification(i);
}
Iterator splitChat = mc.fontRenderer.listFormattedStringToWidth(filteredChat.toString(), gnc.chatWidth).iterator();
boolean firstline = true;
while (splitChat.hasNext()) {
String _line = (String)splitChat.next();
if (!firstline)
_line = " " + _line;
filteredChatLine.add(new TCChatLine(theChat.get(0).getUpdatedCounter(), _line, theChat.get(0).getChatLineID()));
firstline = false;
}
for (String c : toTabs) {
this.addToChannel(c, filteredChatLine);
}
for (String _act : this.getActive()) {
if (toTabs.contains(_act))
ret++;
}
String coloredChat = "";
for (ChatLine cl : theChat)
coloredChat = coloredChat + cl.getChatLineString();
String cleanedChat = StringUtils.stripControlCodes(coloredChat);
if (generalSettings.saveChatLog.getValue()) TabbyChatUtils.logChat(this.withTimeStamp(cleanedChat));
if (!skip) {
Matcher findChannelClean = this.chatChannelPatternClean.matcher(cleanedChat);
Matcher findChannelDirty = this.chatChannelPatternDirty.matcher(coloredChat);
String cName = null;
boolean dirtyValid = (!serverSettings.delimColorBool.getValue() && !serverSettings.delimFormatBool.getValue()) ? true : findChannelDirty.find();
if (findChannelClean.find() && dirtyValid) {
cName = findChannelClean.group(1);
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
} else if(this.chatPMtoMePattern != null){
Matcher findPMtoMe = this.chatPMtoMePattern.matcher(cleanedChat);
if (findPMtoMe.find()) {
for(int i=1;i<=findPMtoMe.groupCount();i++) {
if(findPMtoMe.group(i) != null) {
cName = findPMtoMe.group(i);
if(!this.channelMap.containsKey(cName)) {
ChatChannel newPM = new ChatChannel(cName);
newPM.cmdPrefix = "/msg "+cName;
this.channelMap.put(cName, newPM);
}
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
break;
}
}
} else if(this.chatPMfromMePattern != null) {
Matcher findPMfromMe = this.chatPMfromMePattern.matcher(cleanedChat);
if (findPMfromMe.find()) {
for(int i=1;i<=findPMfromMe.groupCount();i++) {
if(findPMfromMe.group(i) != null) {
cName = findPMfromMe.group(i);
if(!this.channelMap.containsKey(cName)) {
ChatChannel newPM = new ChatChannel(cName);
newPM.cmdPrefix = "/msg "+cName;
this.channelMap.put(cName, newPM);
}
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
break;
}
}
}
}
}
}
if (ret == 0) {
for (String c : toTabs) {
if (c != "*" && this.channelMap.containsKey(c)) {
this.channelMap.get(c).unread = true;
}
}
}
List<String> activeTabs = this.getActive();
if (generalSettings.groupSpam.getValue() && activeTabs.size() > 0) {
if (toTabs.contains(activeTabs.get(0)))
this.lastChat = this.channelMap.get(activeTabs.get(0)).chatLog.subList(0, filteredChatLine.size());
else
this.lastChat = this.withTimeStamp(filteredChatLine);
} else
this.lastChat = this.withTimeStamp(filteredChatLine);
if (ret > 0) {
if (generalSettings.groupSpam.getValue() && this.channelMap.get(activeTabs.get(0)).hasSpam) {
gnc.setChatLines(0, this.lastChat);
} else {
gnc.addChatLines(0, this.lastChat);
}
}
return ret;
}
|
private void configure(URI uri, HttpURLConnection urlConnection, Request request) throws IOException, AuthenticationException {
PerRequestConfig conf = request.getPerRequestConfig();
int requestTimeout = (conf != null && conf.getRequestTimeoutInMs() != 0) ?
conf.getRequestTimeoutInMs() : config.getRequestTimeoutInMs();
urlConnection.setConnectTimeout(config.getConnectionTimeoutInMs());
if (requestTimeout != -1)
urlConnection.setReadTimeout(requestTimeout);
urlConnection.setInstanceFollowRedirects(false);
String host = uri.getHost();
String method = request.getReqType();
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
if (uri.getPort() == -1) {
urlConnection.setRequestProperty("Host", host);
} else {
urlConnection.setRequestProperty("Host", host + ":" + uri.getPort());
}
if (config.isCompressionEnabled()) {
urlConnection.setRequestProperty("Accept-Encoding", "gzip");
}
boolean contentTypeSet = false;
if (!method.equalsIgnoreCase("CONNECT")) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
urlConnection.setRequestProperty(name, value);
}
}
}
}
}
String ka = config.getKeepAlive() ? "keep-alive" : "close";
urlConnection.setRequestProperty("Connection", ka);
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
if (proxyServer != null) {
urlConnection.setRequestProperty("Proxy-Connection", ka);
if (proxyServer.getPrincipal() != null) {
urlConnection.setRequestProperty("Proxy-Authorization", AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
switch (realm.getAuthScheme()) {
case BASIC:
urlConnection.setRequestProperty("Authorization",
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
urlConnection.setRequestProperty("Authorization",
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
default:
throw new IllegalStateException(String.format(AsyncHttpProviderUtils.currentThread()
+ "Invalid Authentication %s", realm.toString()));
}
}
if (realm != null && realm.getDomain() != null && realm.getScheme() == Realm.AuthScheme.NTLM) {
jdkNtlmDomain = System.getProperty(NTLM_DOMAIN);
System.setProperty(NTLM_DOMAIN, realm.getDomain());
}
if (request.getHeaders().getFirstValue("Accept") == null) {
urlConnection.setRequestProperty("Accept", "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") == null && config.getUserAgent() != null) {
urlConnection.setRequestProperty("User-Agent", config.getUserAgent() + " (JDKAsyncHttpProvider)");
}
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
urlConnection.setRequestProperty("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
}
String reqType = request.getReqType();
urlConnection.setRequestMethod(reqType);
if ("POST".equals(reqType) || "PUT".equals(reqType)) {
urlConnection.setRequestProperty("Content-Length", "0");
urlConnection.setDoOutput(true);
if (cachedBytes != null) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(cachedBytesLenght));
urlConnection.setFixedLengthStreamingMode(cachedBytesLenght);
urlConnection.getOutputStream().write(cachedBytes, 0, cachedBytesLenght);
} else if (request.getByteData() != null) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(request.getByteData().length));
urlConnection.setFixedLengthStreamingMode(request.getByteData().length);
urlConnection.getOutputStream().write(request.getByteData());
} else if (request.getStringData() != null) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(request.getStringData().length()));
urlConnection.getOutputStream().write(request.getStringData().getBytes("UTF-8"));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
cachedBytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
cachedBytesLenght = lengthWrapper[0];
urlConnection.setRequestProperty("Content-Length", String.valueOf(cachedBytesLenght));
urlConnection.setFixedLengthStreamingMode(cachedBytesLenght);
urlConnection.getOutputStream().write(cachedBytes, 0, cachedBytesLenght);
} else if (request.getParams() != null) {
StringBuilder sb = new StringBuilder();
for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
urlConnection.setRequestProperty("Content-Length", String.valueOf(sb.length()));
urlConnection.setFixedLengthStreamingMode(sb.length());
if (!request.getHeaders().containsKey("Content-Type")) {
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
urlConnection.getOutputStream().write(sb.toString().getBytes("UTF-8"));
} else if (request.getParts() != null) {
int lenght = (int) request.getLength();
if (lenght != -1) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(lenght));
urlConnection.setFixedLengthStreamingMode(lenght);
}
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
urlConnection.setRequestProperty("Content-Type", mre.getContentType());
urlConnection.setRequestProperty("Content-Length", String.valueOf(mre.getContentLength()));
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(urlConnection.getOutputStream());
} else if (request.getEntityWriter() != null) {
int lenght = (int) request.getLength();
if (lenght != -1) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(lenght));
urlConnection.setFixedLengthStreamingMode(lenght);
}
request.getEntityWriter().writeEntity(urlConnection.getOutputStream());
} else if (request.getFile() != null) {
File file = request.getFile();
if (file.isHidden() || !file.exists() || !file.isFile()) {
throw new IOException(String.format("[" + Thread.currentThread().getName()
+ "] File %s is not a file, is hidden or doesn't exist", file.getAbsolutePath()));
}
long lenght = new RandomAccessFile(file, "r").length();
urlConnection.setRequestProperty("Content-Length", String.valueOf(lenght));
urlConnection.setFixedLengthStreamingMode((int) lenght);
FileInputStream fis = new FileInputStream(file);
try {
final byte[] buffer = new byte[(int) lenght];
fis.read(buffer);
urlConnection.getOutputStream().write(buffer);
} finally {
fis.close();
}
}
}
}
| private void configure(URI uri, HttpURLConnection urlConnection, Request request) throws IOException, AuthenticationException {
PerRequestConfig conf = request.getPerRequestConfig();
int requestTimeout = (conf != null && conf.getRequestTimeoutInMs() != 0) ?
conf.getRequestTimeoutInMs() : config.getRequestTimeoutInMs();
urlConnection.setConnectTimeout(config.getConnectionTimeoutInMs());
if (requestTimeout != -1)
urlConnection.setReadTimeout(requestTimeout);
urlConnection.setInstanceFollowRedirects(false);
String host = uri.getHost();
String method = request.getReqType();
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
if (uri.getPort() == -1) {
urlConnection.setRequestProperty("Host", host);
} else {
urlConnection.setRequestProperty("Host", host + ":" + uri.getPort());
}
if (config.isCompressionEnabled()) {
urlConnection.setRequestProperty("Accept-Encoding", "gzip");
}
boolean contentTypeSet = false;
if (!method.equalsIgnoreCase("CONNECT")) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
urlConnection.setRequestProperty(name, value);
}
}
}
}
}
String ka = config.getKeepAlive() ? "keep-alive" : "close";
urlConnection.setRequestProperty("Connection", ka);
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
if (proxyServer != null) {
urlConnection.setRequestProperty("Proxy-Connection", ka);
if (proxyServer.getPrincipal() != null) {
urlConnection.setRequestProperty("Proxy-Authorization", AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
switch (realm.getAuthScheme()) {
case BASIC:
urlConnection.setRequestProperty("Authorization",
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
urlConnection.setRequestProperty("Authorization",
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
default:
throw new IllegalStateException(String.format(AsyncHttpProviderUtils.currentThread()
+ "Invalid Authentication %s", realm.toString()));
}
}
if (realm != null && realm.getDomain() != null && realm.getScheme() == Realm.AuthScheme.NTLM) {
jdkNtlmDomain = System.getProperty(NTLM_DOMAIN);
System.setProperty(NTLM_DOMAIN, realm.getDomain());
}
if (request.getHeaders().getFirstValue("Accept") == null) {
urlConnection.setRequestProperty("Accept", "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") == null && config.getUserAgent() != null) {
urlConnection.setRequestProperty("User-Agent", config.getUserAgent() + " (JDKAsyncHttpProvider)");
}
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
urlConnection.setRequestProperty("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
}
String reqType = request.getReqType();
urlConnection.setRequestMethod(reqType);
if ("POST".equals(reqType) || "PUT".equals(reqType)) {
urlConnection.setRequestProperty("Content-Length", "0");
urlConnection.setDoOutput(true);
if (cachedBytes != null) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(cachedBytesLenght));
urlConnection.setFixedLengthStreamingMode(cachedBytesLenght);
urlConnection.getOutputStream().write(cachedBytes, 0, cachedBytesLenght);
} else if (request.getByteData() != null) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(request.getByteData().length));
urlConnection.setFixedLengthStreamingMode(request.getByteData().length);
urlConnection.getOutputStream().write(request.getByteData());
} else if (request.getStringData() != null) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(request.getStringData().length()));
urlConnection.getOutputStream().write(request.getStringData().getBytes("UTF-8"));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
cachedBytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
cachedBytesLenght = lengthWrapper[0];
urlConnection.setRequestProperty("Content-Length", String.valueOf(cachedBytesLenght));
urlConnection.setFixedLengthStreamingMode(cachedBytesLenght);
urlConnection.getOutputStream().write(cachedBytes, 0, cachedBytesLenght);
} else if (request.getParams() != null) {
StringBuilder sb = new StringBuilder();
for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
urlConnection.setRequestProperty("Content-Length", String.valueOf(sb.length()));
urlConnection.setFixedLengthStreamingMode(sb.length());
if (!request.getHeaders().containsKey("Content-Type")) {
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
urlConnection.getOutputStream().write(sb.toString().getBytes("UTF-8"));
} else if (request.getParts() != null) {
int lenght = (int) request.getLength();
if (lenght != -1) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(lenght));
urlConnection.setFixedLengthStreamingMode(lenght);
}
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
urlConnection.setRequestProperty("Content-Type", mre.getContentType());
urlConnection.setRequestProperty("Content-Length", String.valueOf(mre.getContentLength()));
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(urlConnection.getOutputStream());
} else if (request.getEntityWriter() != null) {
int lenght = (int) request.getLength();
if (lenght != -1) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(lenght));
urlConnection.setFixedLengthStreamingMode(lenght);
}
request.getEntityWriter().writeEntity(urlConnection.getOutputStream());
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format(Thread.currentThread()
+ "File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
long lenght = new RandomAccessFile(file, "r").length();
urlConnection.setRequestProperty("Content-Length", String.valueOf(lenght));
urlConnection.setFixedLengthStreamingMode((int) lenght);
FileInputStream fis = new FileInputStream(file);
try {
final byte[] buffer = new byte[(int) lenght];
fis.read(buffer);
urlConnection.getOutputStream().write(buffer);
} finally {
fis.close();
}
}
}
}
|
public static ItemMeta deserializeItemMeta(ItemMeta meta, Map<String, Object> args) {
if(args.containsKey("display-name")) meta.setDisplayName((String) args.get("display-name"));
if(args.containsKey("enchants")){
Map<String, Double> enchantements = (Map<String, Double>) args.get("enchants");
Set<String> liste = enchantements.keySet();
for(String e : liste)
meta.addEnchant(Enchantment.getByName(e), enchantements.get(e).intValue(), false);
}
return meta;
}
| public static ItemMeta deserializeItemMeta(ItemMeta meta, Map<String, Object> args) {
if(args.containsKey("display-name")) meta.setDisplayName((String) args.get("display-name"));
if(args.containsKey("enchants")){
Map<String, Double> enchantements = (Map<String, Double>) args.get("enchants");
Set<String> liste = enchantements.keySet();
for(String e : liste)
meta.addEnchant(Enchantment.getByName(e), enchantements.get(e).intValue(), true);
}
return meta;
}
|
public CommandRequestInterface doWklyAllotmentPreCheck(CommandRequest request) {
User user = request.getSession().getUserNull(request.getUser());
int weekReqs = user.getKeyedMap().getObject(RequestUserData.WEEKREQS,0);
if (_weekMax != 0 && weekReqs >= _weekMax && !_weekExempt.check(user)) {
request.setAllowed(false);
request.setDeniedResponse(new CommandResponse(530, "Access denied - " +
"You have reached max(" + _weekMax + ") number of requests per week"));
}
return request;
}
| public CommandRequestInterface doWklyAllotmentPreCheck(CommandRequest request) {
User user = request.getSession().getUserNull(request.getUser());
if (user != null) {
int weekReqs = user.getKeyedMap().getObjectInteger(RequestUserData.WEEKREQS);
if (_weekMax != 0 && weekReqs >= _weekMax && !_weekExempt.check(user)) {
request.setAllowed(false);
request.setDeniedResponse(new CommandResponse(530, "Access denied - " + "You have reached max(" + _weekMax + ") number of requests per week"));
}
return request;
}
request.setAllowed(false);
request.setDeniedResponse(new CommandResponse(530, "Access denied - No Such User"));
return request;
}
|
private void loadAccountList() {
View accountsLabel = mContentView.findViewById(R.id.accounts_label);
LinearLayout contents = (LinearLayout)mContentView.findViewById(R.id.accounts);
Context context = getActivity();
AccountManager mgr = AccountManager.get(context);
Account[] accounts = mgr.getAccounts();
final int N = accounts.length;
if (N == 0) {
accountsLabel.setVisibility(View.GONE);
contents.setVisibility(View.GONE);
return;
}
LayoutInflater inflater = (LayoutInflater)context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
AuthenticatorDescription[] descs = AccountManager.get(context).getAuthenticatorTypes();
final int M = descs.length;
for (int i=0; i<N; i++) {
Account account = accounts[i];
AuthenticatorDescription desc = null;
for (int j=0; j<M; j++) {
if (account.type.equals(descs[j].type)) {
desc = descs[j];
break;
}
}
if (desc == null) {
Log.w(TAG, "No descriptor for account name=" + account.name
+ " type=" + account.type);
continue;
}
Drawable icon = null;
try {
if (desc.iconId != 0) {
Context authContext = context.createPackageContext(desc.packageName, 0);
icon = authContext.getResources().getDrawable(desc.iconId);
}
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, "No icon for account type " + desc.type);
}
TextView child = (TextView)inflater.inflate(R.layout.master_clear_account,
contents, false);
child.setText(account.name);
if (icon != null) {
child.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
}
contents.addView(child);
}
accountsLabel.setVisibility(View.VISIBLE);
contents.setVisibility(View.VISIBLE);
}
| private void loadAccountList() {
View accountsLabel = mContentView.findViewById(R.id.accounts_label);
LinearLayout contents = (LinearLayout)mContentView.findViewById(R.id.accounts);
contents.removeAllViews();
Context context = getActivity();
AccountManager mgr = AccountManager.get(context);
Account[] accounts = mgr.getAccounts();
final int N = accounts.length;
if (N == 0) {
accountsLabel.setVisibility(View.GONE);
contents.setVisibility(View.GONE);
return;
}
LayoutInflater inflater = (LayoutInflater)context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
AuthenticatorDescription[] descs = AccountManager.get(context).getAuthenticatorTypes();
final int M = descs.length;
for (int i=0; i<N; i++) {
Account account = accounts[i];
AuthenticatorDescription desc = null;
for (int j=0; j<M; j++) {
if (account.type.equals(descs[j].type)) {
desc = descs[j];
break;
}
}
if (desc == null) {
Log.w(TAG, "No descriptor for account name=" + account.name
+ " type=" + account.type);
continue;
}
Drawable icon = null;
try {
if (desc.iconId != 0) {
Context authContext = context.createPackageContext(desc.packageName, 0);
icon = authContext.getResources().getDrawable(desc.iconId);
}
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, "No icon for account type " + desc.type);
}
TextView child = (TextView)inflater.inflate(R.layout.master_clear_account,
contents, false);
child.setText(account.name);
if (icon != null) {
child.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
}
contents.addView(child);
}
accountsLabel.setVisibility(View.VISIBLE);
contents.setVisibility(View.VISIBLE);
}
|
public ExceptionFilterEditor(Composite parent, JavaExceptionBreakpointAdvancedPage page) {
fBreakpoint = (IJavaExceptionBreakpoint) page.getBreakpoint();
Composite outer = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.marginHeight = 0;
layout.marginWidth = 0;
outer.setLayout(layout);
GridData gd = new GridData(GridData.FILL_BOTH);
outer.setLayoutData(gd);
outer.setFont(parent.getFont());
Label label= new Label(outer, SWT.NONE);
label.setText(PropertyPageMessages.getString("ExceptionFilterEditor.5"));
label.setFont(parent.getFont());
gd= new GridData();
gd.horizontalSpan= 2;
label.setLayoutData(gd);
fFilterTable = new Table(outer, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
TableLayout tableLayout = new TableLayout();
ColumnLayoutData[] columnLayoutData = new ColumnLayoutData[1];
columnLayoutData[0] = new ColumnWeightData(100);
tableLayout.addColumnData(columnLayoutData[0]);
fFilterTable.setLayout(tableLayout);
fFilterTable.setFont(parent.getFont());
new TableColumn(fFilterTable, SWT.NONE);
fFilterViewer = new CheckboxTableViewer(fFilterTable);
fTableEditor = new TableEditor(fFilterTable);
fFilterViewer.setLabelProvider(new FilterLabelProvider());
fFilterViewer.setSorter(new FilterViewerSorter());
fFilterContentProvider = new FilterContentProvider(fFilterViewer);
fFilterViewer.setContentProvider(fFilterContentProvider);
fFilterViewer.setInput(this);
gd = new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
gd.widthHint = 100;
fFilterViewer.getTable().setLayoutData(gd);
fFilterViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
Filter filter = (Filter) event.getElement();
fFilterContentProvider.toggleFilter(filter);
}
});
fFilterViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (selection.isEmpty()) {
fRemoveFilterButton.setEnabled(false);
} else {
fRemoveFilterButton.setEnabled(true);
}
}
});
fFilterViewer.getTable().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event) {
if (event.character == SWT.DEL && event.stateMask == 0) {
removeFilters();
}
}
});
createFilterButtons(outer);
}
| public ExceptionFilterEditor(Composite parent, JavaExceptionBreakpointAdvancedPage page) {
fBreakpoint = (IJavaExceptionBreakpoint) page.getBreakpoint();
Composite outer = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.marginHeight = 0;
layout.marginWidth = 0;
outer.setLayout(layout);
GridData gd = new GridData(GridData.FILL_BOTH);
outer.setLayoutData(gd);
outer.setFont(parent.getFont());
Label label= new Label(outer, SWT.NONE);
label.setText(PropertyPageMessages.getString("ExceptionFilterEditor.5"));
label.setFont(parent.getFont());
gd= new GridData();
gd.horizontalSpan= 2;
label.setLayoutData(gd);
fFilterTable = new Table(outer, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
TableLayout tableLayout = new TableLayout();
ColumnLayoutData[] columnLayoutData = new ColumnLayoutData[1];
columnLayoutData[0] = new ColumnWeightData(100);
tableLayout.addColumnData(columnLayoutData[0]);
fFilterTable.setLayout(tableLayout);
fFilterTable.setFont(parent.getFont());
new TableColumn(fFilterTable, SWT.NONE);
fFilterViewer = new CheckboxTableViewer(fFilterTable);
fTableEditor = new TableEditor(fFilterTable);
fFilterViewer.setLabelProvider(new FilterLabelProvider());
fFilterViewer.setSorter(new FilterViewerSorter());
fFilterContentProvider = new FilterContentProvider(fFilterViewer);
fFilterViewer.setContentProvider(fFilterContentProvider);
fFilterViewer.setInput(this);
gd = new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
gd.widthHint = 100;
gd.heightHint = 100;
fFilterViewer.getTable().setLayoutData(gd);
fFilterViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
Filter filter = (Filter) event.getElement();
fFilterContentProvider.toggleFilter(filter);
}
});
fFilterViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (selection.isEmpty()) {
fRemoveFilterButton.setEnabled(false);
} else {
fRemoveFilterButton.setEnabled(true);
}
}
});
fFilterViewer.getTable().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event) {
if (event.character == SWT.DEL && event.stateMask == 0) {
removeFilters();
}
}
});
createFilterButtons(outer);
}
|
public ArrayList<String> run(IrcMessage message, String command) {
clearResponses();
String[] params = message.body.split("#");
if (params.length < 2) {
System.err.println("Can't parse the ticket id from the message");
return responses;
}
BugzillaProxy bz = new BugzillaProxy(BZ_URL);
try {
bz.connect(USERNAME, PASSWORD);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
BugzillaTicket bzTicket = null;
try {
bzTicket = bz.getTicket(Integer.parseInt(params[1]));
} catch (XmlRpcException e) {
e.printStackTrace();
}
if (bzTicket != null) {
String ticketURL = bz.getURL() + "/show_bug.cgi?id=" + bzTicket.getID();
addResponse("["+ bzTicket.getComponent() +"] " + bzTicket.getSummary() + " <"+ ticketURL +">");
}
return responses;
}
| public ArrayList<String> run(IrcMessage message, String command) {
clearResponses();
String[] params = message.body.split("#");
if (params.length < 2) {
System.err.println("Can't parse the ticket id from the message");
return responses;
}
BugzillaProxy bz = new BugzillaProxy(BZ_URL);
try {
bz.connect(USERNAME, PASSWORD);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
BugzillaTicket bzTicket = null;
try {
bzTicket = bz.getTicket(Integer.parseInt(params[1]));
} catch (XmlRpcException e) {
e.printStackTrace();
}
if (bzTicket != null) {
String ticketURL = bz.getURL() + "/show_bug.cgi?id=" + bzTicket.getID();
addResponse("bz#" + bzTicket.getID() + ": ["+ bzTicket.getComponent() +"] " + bzTicket.getSummary() + " <"+ ticketURL +">");
}
return responses;
}
|
static public TSOServerConfig parseConfig(String args[]){
config = new TSOServerConfig();
if (args.length == 0) {
new JCommander(config).usage();
System.exit(0);
}
new JCommander(config, args);
return config;
}
| static public TSOServerConfig parseConfig(String args[]){
TSOServerConfig config = new TSOServerConfig();
if (args.length == 0) {
new JCommander(config).usage();
System.exit(0);
}
new JCommander(config, args);
return config;
}
|
private void init() {
try {
final PackageInfo info = getPackageManager().getPackageInfo(this.getPackageName(), 0);
setTitle(res.getString(R.string.about) + " (ver. " + info.versionName + ")");
((TextView) findViewById(R.id.contributors)).setMovementMethod(LinkMovementMethod.getInstance());
((TextView) findViewById(R.id.changelog)).setMovementMethod(LinkMovementMethod.getInstance());
} catch (Exception e) {
Log.e("AboutActivity.init: Failed to obtain package version.");
}
}
| private void init() {
try {
final PackageInfo info = getPackageManager().getPackageInfo(this.getPackageName(), 0);
((TextView) findViewById(R.id.about_version_string)).setText(info.versionName);
((TextView) findViewById(R.id.contributors)).setMovementMethod(LinkMovementMethod.getInstance());
((TextView) findViewById(R.id.changelog)).setMovementMethod(LinkMovementMethod.getInstance());
} catch (Exception e) {
Log.e("AboutActivity.init: Failed to obtain package version.");
}
}
|
public void afterOpcode(int seen) {
if (seen == ANEWARRAY) {
Number arraySize;
try {
Item arraySizeItem = stack.getStackItem(0);
if (arraySizeItem == null || !(arraySizeItem.getConstant() instanceof Number)) {
throw new AssertionError("wrong byte code: anewarray should get int as 0th oprand stack entry");
}
arraySize = (Number) arraySizeItem.getConstant();
} finally {
super.afterOpcode(seen);
}
Item createdArray = stack.getStackItem(0);
createdArray.setUserValue(arraySize);
return;
}
super.afterOpcode(seen);
if (seen != NEW) {
return;
}
try {
JavaClass clazz = Repository.lookupClass(getClassConstantOperand());
if (clazz.instanceOf(throwable)) {
stack.getStackItem(0).setUserValue(IS_THROWABLE);
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException("class not found", e);
}
}
| public void afterOpcode(int seen) {
if (seen == ANEWARRAY) {
Number arraySize;
try {
Item arraySizeItem = stack.getStackItem(0);
if (arraySizeItem == null || !(arraySizeItem.getConstant() instanceof Number)) {
throw new AssertionError("wrong byte code: anewarray should get int as 0th oprand stack entry, " +
"but given value is: " + arraySizeItem.getConstant());
}
arraySize = (Number) arraySizeItem.getConstant();
} finally {
super.afterOpcode(seen);
}
Item createdArray = stack.getStackItem(0);
createdArray.setUserValue(arraySize);
return;
}
super.afterOpcode(seen);
if (seen != NEW) {
return;
}
try {
JavaClass clazz = Repository.lookupClass(getClassConstantOperand());
if (clazz.instanceOf(throwable)) {
stack.getStackItem(0).setUserValue(IS_THROWABLE);
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException("class not found", e);
}
}
|
public void execute()
throws MojoExecutionException
{
if ( !"maven-plugin".equals( project.getPackaging() ) )
{
return;
}
if ( project.getArtifactId().toLowerCase().startsWith( "maven-" )
&& project.getArtifactId().toLowerCase().endsWith( "-plugin" )
&& !"org.apache.maven.plugin".equals( project.getGroupId() ) )
{
getLog().error( "\n\nArtifact Ids of the format maven-___-plugin are reserved for \n"
+ "plugins in the Group Id org.apache.maven.plugins\n"
+ "Please change your artifactId to the format ___-maven-plugin\n"
+ "In the future this error will break the build.\n\n" );
}
String defaultGoalPrefix = PluginDescriptor.getGoalPrefixFromArtifactId( project.getArtifactId() );
if ( goalPrefix == null )
{
goalPrefix = defaultGoalPrefix;
}
else if ( !goalPrefix.equals( defaultGoalPrefix ) )
{
getLog().warn(
"\n\nGoal prefix is specified as: '" + goalPrefix + "'. "
+ "Maven currently expects it to be '" + defaultGoalPrefix + "'.\n" );
}
mojoScanner.setActiveExtractors( extractors );
PluginDescriptor pluginDescriptor = new PluginDescriptor();
pluginDescriptor.setGroupId( project.getGroupId() );
pluginDescriptor.setArtifactId( project.getArtifactId() );
pluginDescriptor.setVersion( project.getVersion() );
pluginDescriptor.setGoalPrefix( goalPrefix );
pluginDescriptor.setName( project.getName() );
pluginDescriptor.setDescription( project.getDescription() );
if ( encoding == null || encoding.length() < 1 )
{
getLog().warn( "Using platform encoding (" + ReaderFactory.FILE_ENCODING
+ " actually) to read mojo metadata, i.e. build is platform dependent!" );
}
else
{
getLog().info( "Using '" + encoding + "' encoding to read mojo metadata." );
}
try
{
pluginDescriptor.setDependencies( PluginUtils.toComponentDependencies( project.getRuntimeDependencies() ) );
PluginToolsRequest request = new DefaultPluginToolsRequest( project, pluginDescriptor );
request.setEncoding( encoding );
mojoScanner.populatePluginDescriptor( request );
getOutputDirectory().mkdirs();
createGenerator().execute( getOutputDirectory(), request );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error writing plugin descriptor", e );
}
catch ( InvalidPluginDescriptorException e )
{
throw new MojoExecutionException( "Error extracting plugin descriptor: \'" + e.getLocalizedMessage() + "\'",
e );
}
catch ( ExtractionException e )
{
throw new MojoExecutionException( "Error extracting plugin descriptor: \'" + e.getLocalizedMessage() + "\'",
e );
}
catch ( LinkageError e )
{
throw new MojoExecutionException( "The API of the mojo scanner is not compatible with this plugin version."
+ " Please check the plugin dependencies configured in the POM and ensure the versions match.", e );
}
}
| public void execute()
throws MojoExecutionException
{
if ( !"maven-plugin".equals( project.getPackaging() ) )
{
return;
}
if ( project.getArtifactId().toLowerCase().startsWith( "maven-" )
&& project.getArtifactId().toLowerCase().endsWith( "-plugin" )
&& !"org.apache.maven.plugins".equals( project.getGroupId() ) )
{
getLog().error( "\n\nArtifact Ids of the format maven-___-plugin are reserved for \n"
+ "plugins in the Group Id org.apache.maven.plugins\n"
+ "Please change your artifactId to the format ___-maven-plugin\n"
+ "In the future this error will break the build.\n\n" );
}
String defaultGoalPrefix = PluginDescriptor.getGoalPrefixFromArtifactId( project.getArtifactId() );
if ( goalPrefix == null )
{
goalPrefix = defaultGoalPrefix;
}
else if ( !goalPrefix.equals( defaultGoalPrefix ) )
{
getLog().warn(
"\n\nGoal prefix is specified as: '" + goalPrefix + "'. "
+ "Maven currently expects it to be '" + defaultGoalPrefix + "'.\n" );
}
mojoScanner.setActiveExtractors( extractors );
PluginDescriptor pluginDescriptor = new PluginDescriptor();
pluginDescriptor.setGroupId( project.getGroupId() );
pluginDescriptor.setArtifactId( project.getArtifactId() );
pluginDescriptor.setVersion( project.getVersion() );
pluginDescriptor.setGoalPrefix( goalPrefix );
pluginDescriptor.setName( project.getName() );
pluginDescriptor.setDescription( project.getDescription() );
if ( encoding == null || encoding.length() < 1 )
{
getLog().warn( "Using platform encoding (" + ReaderFactory.FILE_ENCODING
+ " actually) to read mojo metadata, i.e. build is platform dependent!" );
}
else
{
getLog().info( "Using '" + encoding + "' encoding to read mojo metadata." );
}
try
{
pluginDescriptor.setDependencies( PluginUtils.toComponentDependencies( project.getRuntimeDependencies() ) );
PluginToolsRequest request = new DefaultPluginToolsRequest( project, pluginDescriptor );
request.setEncoding( encoding );
mojoScanner.populatePluginDescriptor( request );
getOutputDirectory().mkdirs();
createGenerator().execute( getOutputDirectory(), request );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error writing plugin descriptor", e );
}
catch ( InvalidPluginDescriptorException e )
{
throw new MojoExecutionException( "Error extracting plugin descriptor: \'" + e.getLocalizedMessage() + "\'",
e );
}
catch ( ExtractionException e )
{
throw new MojoExecutionException( "Error extracting plugin descriptor: \'" + e.getLocalizedMessage() + "\'",
e );
}
catch ( LinkageError e )
{
throw new MojoExecutionException( "The API of the mojo scanner is not compatible with this plugin version."
+ " Please check the plugin dependencies configured in the POM and ensure the versions match.", e );
}
}
|
public void finalizeAction(Reference reference) {
TermConverterService termConverterService =
(TermConverterService) ComponentManager.get("uk.ac.ox.oucs.termdates.BsgTermConverterService");
ContentCollection entity = (ContentCollection)reference.getEntity();
SortedMap<Integer, String> oldMap = new TreeMap<Integer, String>();
SortedSet<Integer> newSet = new TreeSet<Integer>();
ResourceProperties properties = entity.getProperties();
int startWeek = parseInt(properties.getProperty(PROP_BSG_START_WEEK));
int endWeek = parseInt(properties.getProperty(PROP_BSG_END_WEEK));
Collection<ContentEntity> collection = entity.getMemberResources();
for (ContentEntity contentEntity : collection) {
if (contentEntity instanceof ContentCollection) {
ContentCollection content = (ContentCollection)contentEntity;
String weekName = content.getProperties().getProperty(PROP_BSG_WEEK);
if (null != weekName) {
oldMap.put(new Integer(weekName), content.getId());
}
}
}
for (int i = startWeek; i <= endWeek; i++) {
newSet.add(i);
}
Object[] oldArray = oldMap.keySet().toArray();
Object[] newArray = newSet.toArray();
try {
Map<String, String> stashMap = new HashMap<String, String>();
String lastId = null;
for (int i=0; i<newArray.length; i++) {
Integer newInteger = ((Integer)newArray[i]);
String name = termConverterService.getWeekName(newInteger);
ContentCollection from = null;
ContentCollectionEdit edit = null;
if (i<oldArray.length) {
Integer oldInteger = ((Integer)oldArray[i]);
if (newInteger.intValue() == oldInteger.intValue()) {
lastId = oldMap.get(oldInteger);
oldMap.remove(oldInteger);
continue;
}
String id = null;
String key = oldMap.get(oldInteger);
if (stashMap.containsKey(key)) {
id = stashMap.get(key);
} else {
id = key;
}
from = contentService.getCollection(id);
oldMap.remove(oldInteger);
}
try {
edit = contentService.addCollection(
entity.getId(), Validator.escapeResourceName(name));
} catch (IdUsedException e) {
String stashId = entity.getId() + Validator.escapeResourceName(name) + "/";
String tempId = entity.getId() + Validator.escapeResourceName(
new Long(System.currentTimeMillis()).toString()) + "/";
ContentCollectionEdit temp = contentService.addCollection(tempId);
ContentCollection stash = contentService.getCollection(stashId);
ResourcePropertiesEdit resourcePropertiesEdit = temp.getPropertiesEdit();
resourcePropertiesEdit.addAll(stash.getProperties());
Collection<ContentEntity> resources = stash.getMemberResources();
for (ContentEntity contentEntity : resources) {
contentService.moveIntoFolder(contentEntity.getId(), temp.getId());
}
stashMap.put(stashId, tempId);
contentService.commitCollection(temp);
contentService.removeCollection(stash.getId());
if (oldMap.containsValue(stashId)) {
for (Map.Entry<Integer, String> entry : oldMap.entrySet()) {
if (stashId.equals(entry.getValue())) {
oldMap.remove(entry.getKey());
}
}
}
edit = contentService.addCollection(stashId);
}
ResourcePropertiesEdit resourceProperties = edit.getPropertiesEdit();
resourceProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
resourceProperties.addProperty(PROP_BSG_WEEK, Integer.toString((Integer)newArray[i]));
if (null != from) {
Collection<ContentEntity> resources = from.getMemberResources();
for (ContentEntity contentEntity : resources) {
contentService.moveIntoFolder(contentEntity.getId(), edit.getId());
}
contentService.removeCollection(from.getId());
}
contentService.commitCollection(edit);
lastId = edit.getId();
}
for (Map.Entry<Integer, String> entry : oldMap.entrySet()) {
copyResources(entry.getValue(), lastId);
}
for (Map.Entry<String, String> entry : stashMap.entrySet()) {
copyResources(entry.getValue(), lastId);
}
} catch (IdUnusedException e) {
e.printStackTrace();
} catch (TypeException e) {
e.printStackTrace();
} catch (PermissionException e) {
e.printStackTrace();
} catch (IdUsedException e) {
e.printStackTrace();
} catch (IdLengthException e) {
e.printStackTrace();
} catch (IdInvalidException e) {
e.printStackTrace();
} catch (InUseException e) {
e.printStackTrace();
} catch (ServerOverloadException e) {
e.printStackTrace();
} catch (OverQuotaException e) {
e.printStackTrace();
} catch (InconsistentException e) {
e.printStackTrace();
}
}
| public void finalizeAction(Reference reference) {
TermConverterService termConverterService =
(TermConverterService) ComponentManager.get("uk.ac.ox.oucs.termdates.BsgTermConverterService");
ContentCollection entity = (ContentCollection)reference.getEntity();
SortedMap<Integer, String> oldMap = new TreeMap<Integer, String>();
SortedSet<Integer> newSet = new TreeSet<Integer>();
ResourceProperties properties = entity.getProperties();
int startWeek = parseInt(properties.getProperty(PROP_BSG_START_WEEK));
int endWeek = parseInt(properties.getProperty(PROP_BSG_END_WEEK));
Collection<ContentEntity> collection = entity.getMemberResources();
for (ContentEntity contentEntity : collection) {
if (contentEntity instanceof ContentCollection) {
ContentCollection content = (ContentCollection)contentEntity;
String weekName = content.getProperties().getProperty(PROP_BSG_WEEK);
if (null != weekName) {
oldMap.put(new Integer(weekName), content.getId());
}
}
}
for (int i = startWeek; i <= endWeek; i++) {
newSet.add(i);
}
Object[] oldArray = oldMap.keySet().toArray();
Object[] newArray = newSet.toArray();
try {
Map<String, String> stashMap = new HashMap<String, String>();
String lastId = null;
for (int i=0; i<newArray.length; i++) {
Integer newInteger = ((Integer)newArray[i]);
String name = termConverterService.getWeekName(newInteger);
ContentCollection from = null;
ContentCollectionEdit edit = null;
if (i<oldArray.length) {
Integer oldInteger = ((Integer)oldArray[i]);
if (newInteger.intValue() == oldInteger.intValue()) {
lastId = oldMap.get(oldInteger);
oldMap.remove(oldInteger);
continue;
}
String id = null;
String key = oldMap.get(oldInteger);
if (stashMap.containsKey(key)) {
id = stashMap.get(key);
} else {
id = key;
}
from = contentService.getCollection(id);
oldMap.remove(oldInteger);
}
try {
edit = contentService.addCollection(
entity.getId(), Validator.escapeResourceName(name));
} catch (IdUsedException e) {
String stashId = entity.getId() + Validator.escapeResourceName(name) + "/";
String tempId = entity.getId() + Validator.escapeResourceName(
new Long(System.currentTimeMillis()).toString()) + "/";
ContentCollectionEdit temp = contentService.addCollection(tempId);
ContentCollection stash = contentService.getCollection(stashId);
ResourcePropertiesEdit resourcePropertiesEdit = temp.getPropertiesEdit();
resourcePropertiesEdit.addAll(stash.getProperties());
Collection<ContentEntity> resources = stash.getMemberResources();
for (ContentEntity contentEntity : resources) {
contentService.moveIntoFolder(contentEntity.getId(), temp.getId());
}
stashMap.put(stashId, tempId);
contentService.commitCollection(temp);
contentService.removeCollection(stash.getId());
if (oldMap.containsValue(stashId)) {
Integer removalKey = null;
for (Map.Entry<Integer, String> entry : oldMap.entrySet()) {
if (stashId.equals(entry.getValue())) {
removalKey = entry.getKey();
break;
}
}
if (removalKey != null) {
oldMap.remove(removalKey);
}
}
edit = contentService.addCollection(stashId);
}
ResourcePropertiesEdit resourceProperties = edit.getPropertiesEdit();
resourceProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
resourceProperties.addProperty(PROP_BSG_WEEK, Integer.toString((Integer)newArray[i]));
if (null != from) {
Collection<ContentEntity> resources = from.getMemberResources();
for (ContentEntity contentEntity : resources) {
contentService.moveIntoFolder(contentEntity.getId(), edit.getId());
}
contentService.removeCollection(from.getId());
}
contentService.commitCollection(edit);
lastId = edit.getId();
}
for (Map.Entry<Integer, String> entry : oldMap.entrySet()) {
copyResources(entry.getValue(), lastId);
}
for (Map.Entry<String, String> entry : stashMap.entrySet()) {
copyResources(entry.getValue(), lastId);
}
} catch (IdUnusedException e) {
e.printStackTrace();
} catch (TypeException e) {
e.printStackTrace();
} catch (PermissionException e) {
e.printStackTrace();
} catch (IdUsedException e) {
e.printStackTrace();
} catch (IdLengthException e) {
e.printStackTrace();
} catch (IdInvalidException e) {
e.printStackTrace();
} catch (InUseException e) {
e.printStackTrace();
} catch (ServerOverloadException e) {
e.printStackTrace();
} catch (OverQuotaException e) {
e.printStackTrace();
} catch (InconsistentException e) {
e.printStackTrace();
}
}
|
public void deploy(DeploymentEntity deployment) {
LOG.debug("Processing deployment {}", deployment.getName());
List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
Map<String, ResourceEntity> resources = deployment.getResources();
for (String resourceName : resources.keySet()) {
LOG.info("Processing resource {}", resourceName);
if (isBpmnResource(resourceName)) {
ResourceEntity resource = resources.get(resourceName);
byte[] bytes = resource.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
BpmnParse bpmnParse = bpmnParser
.createParse()
.sourceInputStream(inputStream)
.deployment(deployment)
.name(resourceName);
bpmnParse.execute();
for (ProcessDefinitionEntity processDefinition: bpmnParse.getProcessDefinitions()) {
processDefinition.setResourceName(resourceName);
if (deployment.getTenantId() != null) {
processDefinition.setTenantId(deployment.getTenantId());
}
String diagramResourceName = getDiagramResourceForProcess(resourceName, processDefinition.getKey(), resources);
if(deployment.isNew()) {
if (Context.getProcessEngineConfiguration().isCreateDiagramOnDeploy() &&
diagramResourceName==null && processDefinition.isGraphicalNotationDefined()) {
try {
byte[] diagramBytes = IoUtil.readInputStream(ProcessDiagramGenerator.generatePngDiagram(bpmnParse.getBpmnModel()), null);
diagramResourceName = getProcessImageResourceName(resourceName, processDefinition.getKey(), "png");
createResource(diagramResourceName, diagramBytes, deployment);
} catch (Throwable t) {
LOG.warn("Error while generating process diagram, image will not be stored in repository", t);
}
}
}
processDefinition.setDiagramResourceName(diagramResourceName);
processDefinitions.add(processDefinition);
}
}
}
List<String> keyList = new ArrayList<String>();
for (ProcessDefinitionEntity processDefinition : processDefinitions) {
if (keyList.contains(processDefinition.getKey())) {
throw new ActivitiException("The deployment contains process definitions with the same key (process id atrribute), this is not allowed");
}
keyList.add(processDefinition.getKey());
}
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionEntityManager processDefinitionManager = commandContext.getProcessDefinitionEntityManager();
DbSqlSession dbSqlSession = commandContext.getSession(DbSqlSession.class);
for (ProcessDefinitionEntity processDefinition : processDefinitions) {
List<TimerEntity> timers = new ArrayList<TimerEntity>();
if (deployment.isNew()) {
int processDefinitionVersion;
ProcessDefinitionEntity latestProcessDefinition = null;
if (processDefinition.getTenantId() != null && !ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) {
latestProcessDefinition = processDefinitionManager
.findLatestProcessDefinitionByKeyAndTenantId(processDefinition.getKey(), processDefinition.getTenantId());
} else {
latestProcessDefinition = processDefinitionManager
.findLatestProcessDefinitionByKey(processDefinition.getKey());
}
if (latestProcessDefinition != null) {
processDefinitionVersion = latestProcessDefinition.getVersion() + 1;
} else {
processDefinitionVersion = 1;
}
processDefinition.setVersion(processDefinitionVersion);
processDefinition.setDeploymentId(deployment.getId());
String nextId = idGenerator.getNextId();
String processDefinitionId = processDefinition.getKey()
+ ":" + processDefinition.getVersion()
+ ":" + nextId;
if (processDefinitionId.length() > 64) {
processDefinitionId = nextId;
}
processDefinition.setId(processDefinitionId);
removeObsoleteTimers(processDefinition);
addTimerDeclarations(processDefinition, timers);
removeObsoleteMessageEventSubscriptions(processDefinition, latestProcessDefinition);
addMessageEventSubscriptions(processDefinition);
dbSqlSession.insert(processDefinition);
addAuthorizations(processDefinition);
scheduleTimers(timers);
if(commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_CREATED, processDefinition));
}
} else {
String deploymentId = deployment.getId();
processDefinition.setDeploymentId(deploymentId);
ProcessDefinitionEntity persistedProcessDefinition = null;
if (processDefinition.getTenantId() == null) {
persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinition.getKey());
} else {
persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKeyAndTenantId(deploymentId, processDefinition.getKey(), processDefinition.getTenantId());
}
if (persistedProcessDefinition != null) {
processDefinition.setId(persistedProcessDefinition.getId());
processDefinition.setVersion(persistedProcessDefinition.getVersion());
processDefinition.setSuspensionState(persistedProcessDefinition.getSuspensionState());
}
}
Context
.getProcessEngineConfiguration()
.getDeploymentManager()
.getProcessDefinitionCache()
.add(processDefinition.getId(), processDefinition);
deployment.addDeployedArtifact(processDefinition);
}
}
| public void deploy(DeploymentEntity deployment) {
LOG.debug("Processing deployment {}", deployment.getName());
List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
Map<String, ResourceEntity> resources = deployment.getResources();
for (String resourceName : resources.keySet()) {
LOG.info("Processing resource {}", resourceName);
if (isBpmnResource(resourceName)) {
ResourceEntity resource = resources.get(resourceName);
byte[] bytes = resource.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
BpmnParse bpmnParse = bpmnParser
.createParse()
.sourceInputStream(inputStream)
.deployment(deployment)
.name(resourceName);
bpmnParse.execute();
for (ProcessDefinitionEntity processDefinition: bpmnParse.getProcessDefinitions()) {
processDefinition.setResourceName(resourceName);
if (deployment.getTenantId() != null) {
processDefinition.setTenantId(deployment.getTenantId());
}
String diagramResourceName = getDiagramResourceForProcess(resourceName, processDefinition.getKey(), resources);
if(deployment.isNew()) {
if (Context.getProcessEngineConfiguration().isCreateDiagramOnDeploy() &&
diagramResourceName==null && processDefinition.isGraphicalNotationDefined()) {
try {
byte[] diagramBytes = IoUtil.readInputStream(ProcessDiagramGenerator.generatePngDiagram(bpmnParse.getBpmnModel()), null);
diagramResourceName = getProcessImageResourceName(resourceName, processDefinition.getKey(), "png");
createResource(diagramResourceName, diagramBytes, deployment);
} catch (Throwable t) {
LOG.warn("Error while generating process diagram, image will not be stored in repository", t);
}
}
}
processDefinition.setDiagramResourceName(diagramResourceName);
processDefinitions.add(processDefinition);
}
}
}
List<String> keyList = new ArrayList<String>();
for (ProcessDefinitionEntity processDefinition : processDefinitions) {
if (keyList.contains(processDefinition.getKey())) {
throw new ActivitiException("The deployment contains process definitions with the same key (process id atrribute), this is not allowed");
}
keyList.add(processDefinition.getKey());
}
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionEntityManager processDefinitionManager = commandContext.getProcessDefinitionEntityManager();
DbSqlSession dbSqlSession = commandContext.getSession(DbSqlSession.class);
for (ProcessDefinitionEntity processDefinition : processDefinitions) {
List<TimerEntity> timers = new ArrayList<TimerEntity>();
if (deployment.isNew()) {
int processDefinitionVersion;
ProcessDefinitionEntity latestProcessDefinition = null;
if (processDefinition.getTenantId() != null && !ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) {
latestProcessDefinition = processDefinitionManager
.findLatestProcessDefinitionByKeyAndTenantId(processDefinition.getKey(), processDefinition.getTenantId());
} else {
latestProcessDefinition = processDefinitionManager
.findLatestProcessDefinitionByKey(processDefinition.getKey());
}
if (latestProcessDefinition != null) {
processDefinitionVersion = latestProcessDefinition.getVersion() + 1;
} else {
processDefinitionVersion = 1;
}
processDefinition.setVersion(processDefinitionVersion);
processDefinition.setDeploymentId(deployment.getId());
String nextId = idGenerator.getNextId();
String processDefinitionId = processDefinition.getKey()
+ ":" + processDefinition.getVersion()
+ ":" + nextId;
if (processDefinitionId.length() > 64) {
processDefinitionId = nextId;
}
processDefinition.setId(processDefinitionId);
removeObsoleteTimers(processDefinition);
addTimerDeclarations(processDefinition, timers);
removeObsoleteMessageEventSubscriptions(processDefinition, latestProcessDefinition);
addMessageEventSubscriptions(processDefinition);
dbSqlSession.insert(processDefinition);
addAuthorizations(processDefinition);
scheduleTimers(timers);
if(commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_CREATED, processDefinition));
}
} else {
String deploymentId = deployment.getId();
processDefinition.setDeploymentId(deploymentId);
ProcessDefinitionEntity persistedProcessDefinition = null;
if (processDefinition.getTenantId() == null || ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) {
persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinition.getKey());
} else {
persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKeyAndTenantId(deploymentId, processDefinition.getKey(), processDefinition.getTenantId());
}
if (persistedProcessDefinition != null) {
processDefinition.setId(persistedProcessDefinition.getId());
processDefinition.setVersion(persistedProcessDefinition.getVersion());
processDefinition.setSuspensionState(persistedProcessDefinition.getSuspensionState());
}
}
Context
.getProcessEngineConfiguration()
.getDeploymentManager()
.getProcessDefinitionCache()
.add(processDefinition.getId(), processDefinition);
deployment.addDeployedArtifact(processDefinition);
}
}
|
public NamespaceFilter(DumpWriter sink, String configString) {
super(sink);
invert = configString.startsWith("!");
matches = new HashMap();
String[] namespaceKeys = {
"NS_MAIN",
"NS_TALK",
"NS_USER",
"NS_USER_TALK",
"NS_PROJECT",
"NS_PROJECT_TALK",
"NS_IMAGE",
"NS_IMAGE_TALK",
"NS_MEDIAWIKI",
"NS_MEDIAWIKI_TALK",
"NS_TEMPLATE",
"NS_TEMPLATE_TALK",
"NS_HELP",
"NS_HELP_TALK",
"NS_CATEGORY",
"NS_CATEGORY_TALK" };
String[] itemList = configString.trim().split(",");
for (int i = 0; i < itemList.length; i++) {
String keyString = itemList[i];
String trimmed = keyString.trim();
try {
int key = Integer.parseInt(trimmed);
matches.put(new Integer(key), trimmed);
} catch (NumberFormatException e) {
for (int key = 0; key < namespaceKeys.length; key++) {
if (trimmed.equalsIgnoreCase(namespaceKeys[key]))
matches.put(new Integer(key), trimmed);
}
}
}
}
| public NamespaceFilter(DumpWriter sink, String configString) {
super(sink);
invert = configString.startsWith("!");
if (invert)
configString = configString.substring(1);
matches = new HashMap();
String[] namespaceKeys = {
"NS_MAIN",
"NS_TALK",
"NS_USER",
"NS_USER_TALK",
"NS_PROJECT",
"NS_PROJECT_TALK",
"NS_IMAGE",
"NS_IMAGE_TALK",
"NS_MEDIAWIKI",
"NS_MEDIAWIKI_TALK",
"NS_TEMPLATE",
"NS_TEMPLATE_TALK",
"NS_HELP",
"NS_HELP_TALK",
"NS_CATEGORY",
"NS_CATEGORY_TALK" };
String[] itemList = configString.trim().split(",");
for (int i = 0; i < itemList.length; i++) {
String keyString = itemList[i];
String trimmed = keyString.trim();
try {
int key = Integer.parseInt(trimmed);
matches.put(new Integer(key), trimmed);
} catch (NumberFormatException e) {
for (int key = 0; key < namespaceKeys.length; key++) {
if (trimmed.equalsIgnoreCase(namespaceKeys[key]))
matches.put(new Integer(key), trimmed);
}
}
}
}
|
public List<GraphPath> getPaths(RoutingRequest options) {
final Graph graph = graphService.getGraph(options.getRouterId());
if (options.rctx == null) {
options.setRoutingContext(graph);
options.rctx.pathParsers = new PathParser[1];
options.rctx.pathParsers[0] = new BasicPathParser();
}
if (!options.getModes().isTransit()) {
return sptService.getShortestPathTree(options).getPaths();
}
RaptorData data = graph.getService(RaptorDataService.class).getData();
double initialWalk = options.getMaxWalkDistance() * 1.1;
options.setMaxWalkDistance(initialWalk);
RoutingRequest walkOptions = options.clone();
walkOptions.rctx.pathParsers = new PathParser[0];
TraverseModeSet modes = options.getModes().clone();
modes.setTransit(false);
walkOptions.setModes(modes);
RaptorSearch search = new RaptorSearch(data, options);
if (data.maxTransitRegions != null) {
Calendar tripDate = Calendar.getInstance(graph.getTimeZone());
tripDate.setTime(new Date(1000L * options.dateTime));
Calendar maxTransitStart = Calendar.getInstance(graph.getTimeZone());
maxTransitStart.set(Calendar.YEAR, data.maxTransitRegions.startYear);
maxTransitStart.set(Calendar.MONTH, data.maxTransitRegions.startMonth);
maxTransitStart.set(Calendar.DAY_OF_MONTH, data.maxTransitRegions.startDay);
int day = 0;
while (tripDate.after(maxTransitStart)) {
day++;
tripDate.add(Calendar.DAY_OF_MONTH, -1);
}
if (day > data.maxTransitRegions.maxTransit.length || options.isWheelchairAccessible()) {
day = -1;
}
search.maxTimeDayIndex = day;
}
long searchBeginTime = System.currentTimeMillis();
int bestElapsedTime = Integer.MAX_VALUE;
RETRY: do {
for (int i = 0; i < options.getMaxTransfers() + 2; ++i) {
round(data, options, walkOptions, search, i);
long elapsed = System.currentTimeMillis() - searchBeginTime;
if (elapsed > multiPathTimeout && multiPathTimeout > 0
&& search.getTargetStates().size() > 0)
break RETRY;
if (search.getTargetStates().size() >= options.getNumItineraries()) {
int oldBest = bestElapsedTime;
for (RaptorState state : search.getTargetStates()) {
final int elapsedTime = (int) Math
.abs(state.arrivalTime - options.dateTime);
if (elapsedTime < bestElapsedTime) {
bestElapsedTime = elapsedTime;
}
}
int improvement = oldBest - bestElapsedTime;
if (improvement < 600)
break RETRY;
}
}
options.setMaxWalkDistance(options.getMaxWalkDistance() * 2);
walkOptions.setMaxWalkDistance(options.getMaxWalkDistance());
options.setWalkReluctance(options.getWalkReluctance() * 2);
walkOptions.setWalkReluctance(options.getWalkReluctance());
search.reset(options);
} while (options.getMaxWalkDistance() < initialWalk * MAX_WALK_MULTIPLE && initialWalk < Double.MAX_VALUE);
List<RaptorState> targetStates = search.getTargetStates();
if (targetStates.isEmpty()) {
log.info("RAPTOR found no paths (try retrying?)");
}
Collections.sort(targetStates);
List<GraphPath> paths = new ArrayList<GraphPath>();
for (RaptorState targetState : targetStates) {
ArrayList<RaptorState> states = new ArrayList<RaptorState>();
RaptorState cur = targetState;
while (cur != null) {
states.add(cur);
cur = cur.parent;
}
State state = getState(options, data, states);
paths.add(new GraphPath(state, true));
}
return paths;
}
| public List<GraphPath> getPaths(RoutingRequest options) {
final Graph graph = graphService.getGraph(options.getRouterId());
if (options.rctx == null) {
options.setRoutingContext(graph);
options.rctx.pathParsers = new PathParser[1];
options.rctx.pathParsers[0] = new BasicPathParser();
}
if (!options.getModes().isTransit()) {
return sptService.getShortestPathTree(options).getPaths();
}
RaptorData data = graph.getService(RaptorDataService.class).getData();
double initialWalk = options.getMaxWalkDistance() * 1.1;
options.setMaxWalkDistance(initialWalk);
RoutingRequest walkOptions = options.clone();
walkOptions.rctx.pathParsers = new PathParser[0];
TraverseModeSet modes = options.getModes().clone();
modes.setTransit(false);
walkOptions.setModes(modes);
RaptorSearch search = new RaptorSearch(data, options);
if (data.maxTransitRegions != null) {
Calendar tripDate = Calendar.getInstance(graph.getTimeZone());
tripDate.setTime(new Date(1000L * options.dateTime));
Calendar maxTransitStart = Calendar.getInstance(graph.getTimeZone());
maxTransitStart.set(Calendar.YEAR, data.maxTransitRegions.startYear);
maxTransitStart.set(Calendar.MONTH, data.maxTransitRegions.startMonth);
maxTransitStart.set(Calendar.DAY_OF_MONTH, data.maxTransitRegions.startDay);
int day = 0;
while (tripDate.after(maxTransitStart)) {
day++;
tripDate.add(Calendar.DAY_OF_MONTH, -1);
}
if (day > data.maxTransitRegions.maxTransit.length || options.isWheelchairAccessible()) {
day = -1;
}
search.maxTimeDayIndex = day;
}
long searchBeginTime = System.currentTimeMillis();
int bestElapsedTime = Integer.MAX_VALUE;
RETRY: do {
for (int i = 0; i < options.getMaxTransfers() + 2; ++i) {
round(data, options, walkOptions, search, i);
long elapsed = System.currentTimeMillis() - searchBeginTime;
if (elapsed > multiPathTimeout * 1000 && multiPathTimeout > 0
&& search.getTargetStates().size() > 0)
break RETRY;
if (search.getTargetStates().size() >= options.getNumItineraries()) {
int oldBest = bestElapsedTime;
for (RaptorState state : search.getTargetStates()) {
final int elapsedTime = (int) Math
.abs(state.arrivalTime - options.dateTime);
if (elapsedTime < bestElapsedTime) {
bestElapsedTime = elapsedTime;
}
}
int improvement = oldBest - bestElapsedTime;
if (improvement < 600)
break RETRY;
}
}
options.setMaxWalkDistance(options.getMaxWalkDistance() * 2);
walkOptions.setMaxWalkDistance(options.getMaxWalkDistance());
options.setWalkReluctance(options.getWalkReluctance() * 2);
walkOptions.setWalkReluctance(options.getWalkReluctance());
search.reset(options);
} while (options.getMaxWalkDistance() < initialWalk * MAX_WALK_MULTIPLE && initialWalk < Double.MAX_VALUE);
List<RaptorState> targetStates = search.getTargetStates();
if (targetStates.isEmpty()) {
log.info("RAPTOR found no paths (try retrying?)");
}
Collections.sort(targetStates);
List<GraphPath> paths = new ArrayList<GraphPath>();
for (RaptorState targetState : targetStates) {
ArrayList<RaptorState> states = new ArrayList<RaptorState>();
RaptorState cur = targetState;
while (cur != null) {
states.add(cur);
cur = cur.parent;
}
State state = getState(options, data, states);
paths.add(new GraphPath(state, true));
}
return paths;
}
|
private void createReturnOperations(List<OperationMessage> operations, RequestState returnState,
IdToEntityMap toProcess) {
for (Map.Entry<SimpleProxyId<?>, AutoBean<? extends BaseProxy>> entry : toProcess.entrySet()) {
SimpleProxyId<?> id = entry.getKey();
AutoBean<? extends BaseProxy> bean = entry.getValue();
Object domainObject = bean.getTag(Constants.DOMAIN_OBJECT);
WriteOperation writeOperation;
if (id.isEphemeral()) {
returnState.getResolver().resolveClientValue(domainObject, id.getProxyClass(),
Collections.<String> emptySet());
}
if (id.isEphemeral() || id.isSynthetic() || domainObject == null) {
writeOperation = null;
} else if (!service.isLive(domainObject)) {
writeOperation = WriteOperation.DELETE;
} else if (id.wasEphemeral()) {
writeOperation = WriteOperation.PERSIST;
} else {
writeOperation = WriteOperation.UPDATE;
}
Splittable version = null;
if (writeOperation == WriteOperation.PERSIST || writeOperation == WriteOperation.UPDATE) {
Object domainVersion = service.getVersion(domainObject);
if (domainVersion == null) {
throw new UnexpectedException("The persisted entity with id "
+ service.getId(domainObject) + " has a null version", null);
}
version = returnState.flatten(domainVersion);
}
boolean inResponse = bean.getTag(Constants.IN_RESPONSE) != null;
if (WriteOperation.UPDATE.equals(writeOperation) && !inResponse) {
String previousVersion = bean.<String> getTag(Constants.VERSION_PROPERTY_B64);
if (version != null && previousVersion != null
&& version.equals(fromBase64(previousVersion))) {
continue;
}
}
OperationMessage op = FACTORY.operation().as();
if (id.wasEphemeral()) {
op.setClientId(id.getClientId());
}
op.setOperation(writeOperation);
if (inResponse) {
Map<String, Splittable> propertyMap = new LinkedHashMap<String, Splittable>();
Map<String, Object> diff = AutoBeanUtils.getAllProperties(bean);
for (Map.Entry<String, Object> d : diff.entrySet()) {
Object value = d.getValue();
if (value != null) {
propertyMap.put(d.getKey(), EntityCodex.encode(returnState, value));
}
}
op.setPropertyMap(propertyMap);
}
if (!id.isEphemeral() && !id.isSynthetic()) {
op.setServerId(toBase64(id.getServerId()));
}
if (id.isSynthetic()) {
op.setStrength(Strength.SYNTHETIC);
op.setSyntheticId(id.getSyntheticId());
} else if (id.isEphemeral()) {
op.setStrength(Strength.EPHEMERAL);
}
op.setTypeToken(service.resolveTypeToken(id.getProxyClass()));
if (version != null) {
op.setVersion(toBase64(version.getPayload()));
}
operations.add(op);
}
}
| private void createReturnOperations(List<OperationMessage> operations, RequestState returnState,
IdToEntityMap toProcess) {
for (Map.Entry<SimpleProxyId<?>, AutoBean<? extends BaseProxy>> entry : toProcess.entrySet()) {
SimpleProxyId<?> id = entry.getKey();
AutoBean<? extends BaseProxy> bean = entry.getValue();
Object domainObject = bean.getTag(Constants.DOMAIN_OBJECT);
WriteOperation writeOperation;
if (id.isEphemeral() && returnState.isEntityType(id.getProxyClass())) {
returnState.getResolver().resolveClientValue(domainObject, id.getProxyClass(),
Collections.<String> emptySet());
}
if (id.isEphemeral() || id.isSynthetic() || domainObject == null) {
writeOperation = null;
} else if (!service.isLive(domainObject)) {
writeOperation = WriteOperation.DELETE;
} else if (id.wasEphemeral()) {
writeOperation = WriteOperation.PERSIST;
} else {
writeOperation = WriteOperation.UPDATE;
}
Splittable version = null;
if (writeOperation == WriteOperation.PERSIST || writeOperation == WriteOperation.UPDATE) {
Object domainVersion = service.getVersion(domainObject);
if (domainVersion == null) {
throw new UnexpectedException("The persisted entity with id "
+ service.getId(domainObject) + " has a null version", null);
}
version = returnState.flatten(domainVersion);
}
boolean inResponse = bean.getTag(Constants.IN_RESPONSE) != null;
if (WriteOperation.UPDATE.equals(writeOperation) && !inResponse) {
String previousVersion = bean.<String> getTag(Constants.VERSION_PROPERTY_B64);
if (version != null && previousVersion != null
&& version.equals(fromBase64(previousVersion))) {
continue;
}
}
OperationMessage op = FACTORY.operation().as();
if (id.wasEphemeral()) {
op.setClientId(id.getClientId());
}
op.setOperation(writeOperation);
if (inResponse) {
Map<String, Splittable> propertyMap = new LinkedHashMap<String, Splittable>();
Map<String, Object> diff = AutoBeanUtils.getAllProperties(bean);
for (Map.Entry<String, Object> d : diff.entrySet()) {
Object value = d.getValue();
if (value != null) {
propertyMap.put(d.getKey(), EntityCodex.encode(returnState, value));
}
}
op.setPropertyMap(propertyMap);
}
if (!id.isEphemeral() && !id.isSynthetic()) {
op.setServerId(toBase64(id.getServerId()));
}
if (id.isSynthetic()) {
op.setStrength(Strength.SYNTHETIC);
op.setSyntheticId(id.getSyntheticId());
} else if (id.isEphemeral()) {
op.setStrength(Strength.EPHEMERAL);
}
op.setTypeToken(service.resolveTypeToken(id.getProxyClass()));
if (version != null) {
op.setVersion(toBase64(version.getPayload()));
}
operations.add(op);
}
}
|
public FirstTimeQuery(ModelMap model,Connection con,HttpServletRequest request, int curYear, String access){
try {
Statement statement = con.createStatement();
String query=null;
ResultSet resultSet = null;
TitleArray titleArray= new TitleArray("Austria","Agricultural Tractor", "sales" );
int countryId = 7;
String multiplier="";
if (access.equals("c")) {
titleArray = new TitleArray("China","Agricultural Tractor", "sales" );
countryId = 210000;
multiplier="*10000";
}
if (access.equals("i")) {
titleArray = new TitleArray("India","Agricultural Tractor", "sales" );
countryId = 2000000;
multiplier="*200000";
}
query="SELECT YEAR(DATE_ADD( CURDATE(), INTERVAL -5 YEAR)) as year1 ";
List<Year> years = new ArrayList<Year>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Year year = new Year(resultSet.getString("year1"),resultSet.getString("year1"));
years.add(year);
for (int i=1;i<=10;i++) {
Year nextYear = new Year(
Integer.toString(Integer.parseInt(year.getId())+i),
Integer.toString(Integer.parseInt(year.getId())+i));
years.add(nextYear);
}
}
YearArray yearArray = new YearArray("Company",years,"TOTAL");
ColumnModel columnModel = new ColumnModel(yearArray.getJsonYearArray());
String query2="";
if (access.equals("w")) {
query2 = " select a.year, SUM(a.quantity) as quantity, substr(b.name,1,20) as company " +
" from Facts_w a, Company b, Country c, Product d "+
" where a.companyid=b.id and a.sales_production=1 AND a.countryId NOT IN (20,21,0) "+
" and a.productId = 1 and a.year >=2008 and b.name != 'ALL COMPANIES' "+
" and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " +
" and d.id = a.productId and a.access = 'w' and a.countryId = c.id "+
" group by a.year, b.name, d.name, 'EUROPE' order by b.name , a.year asc ";
}else {
query2 = " select a.year, a.quantity, b.name from Facts_"+access+" a, Company b, Country c " +
" where a.companyid=b.id " +
" and a.countryid=c.id " +
" and c.id="+countryId +
" and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " +
" and a.sales_production= 1" +
" and a.productid=1"+multiplier +
" and a.access = '" + access + "' " +
" and b.name!='ALL COMPANIES' " +
" order by b.name , a.year asc";
}
resultSet = statement.executeQuery(query2);
String currentCompany="";
JSONObject obj2a = null;
JSONArray array7 = new JSONArray();
totalLine2 = new HashMap<String,Integer>();
otherLine2 = new HashMap<String,Integer>();
while (resultSet.next()) {
int totalQuantity=0;
if (totalLine2.get(resultSet.getString("year"))!= null) {
totalQuantity= totalLine2.get(resultSet.getString("year"));
}
totalQuantity += Integer.parseInt(resultSet.getString("quantity"));
totalLine2.put(resultSet.getString("year"), totalQuantity);
int otherQuantity=0;
if (otherLine2.get(resultSet.getString("year"))!= null) {
otherQuantity= otherLine2.get(resultSet.getString("year"));
}
otherQuantity += Integer.parseInt(resultSet.getString("quantity"));
otherLine2.put(resultSet.getString("year"), otherQuantity);
if (!currentCompany.equals(resultSet.getString("name"))) {
if (!currentCompany.equals("")){
array7.put(obj2a);
}
obj2a = new JSONObject();
currentCompany=resultSet.getString("name");
obj2a.put("Company",currentCompany);
obj2a.put(resultSet.getString("year"),resultSet.getString("quantity"));
} else {
obj2a.put(resultSet.getString("year"),resultSet.getString("quantity"));
}
}
if (obj2a != null) {
array7.put(obj2a);
}
JSONObject obj7 = new JSONObject();
obj7.put("myData", array7);
JSONArray array4 = new JSONArray();
array4.put(columnModel.getModelObject());
array4.put(yearArray.getJsonYearObject());
array4.put(obj7);
array4.put(titleArray.getJsonTitleObject());
JSONObject obj5 = new JSONObject();
obj5.put("tabData", array4);
AddJsonRowTotal aj = new AddJsonRowTotal(obj5);
JSONObject objTotal = new JSONObject();
objTotal.put("Company","TOTAL");
Iterator<Entry<String, Integer>> it = totalLine2.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Integer> pairs = it.next();
objTotal.put(pairs.getKey(), pairs.getValue());
}
objTotal.put("TOTAL", aj.getTotal());
JSONArray array8 = new JSONArray();
if (objTotal != null) {
array8.put(objTotal);
JSONObject obj8 = new JSONObject();
obj8.put("myTotals", array8);
model.addAttribute("jsonTotal",obj8);
}
model.addAttribute("jsonData",obj5);
logger.warning(obj5.toString());
if (request.getParameter("list") == null){
query = "select id, country from Country where id != 0 and access = '"+access+"' order by country asc " ;
List<Country> countries = new ArrayList<Country>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Country country = new Country(resultSet.getString("id"),resultSet.getString("country"));
countries.add(country);
}
model.addAttribute("dropdown1a",countries);
model.addAttribute("dropdown2a",countries);
query = "select id, name from Product where id != 0 and access = '"+access+"' order by name asc " ;
List<Product> products = new ArrayList<Product>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Product product = new Product(resultSet.getString("id"),resultSet.getString("name"));
products.add(product);
}
model.addAttribute("dropdown1b",products);
model.addAttribute("dropdown2b",products);
model.addAttribute("dropdown1c",years);
model.addAttribute("dropdown2c",years);
query = " select distinct a.id, substr(a.name,1,20) as name from Company a , Facts_"+access+" b " +
" where a.id != 0" +
" and b.companyid = a.id " +
" and b.access = '" + access +"' and " +
" a.access = '" + access + "' " +
" and a.name != 'ALL COMPANIES' " +
" order by a.name asc " ;
logger.warning(query);
List<Company> companies = new ArrayList<Company>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Company company = new Company(resultSet.getString("id"),resultSet.getString("name"));
companies.add(company);
}
model.addAttribute("dropdown1d",companies);
model.addAttribute("dropdown2d",companies);
model.addAttribute("firstTimeFromServer",obj5);
this.model = model;
}
}catch(Exception e) {
logger.warning("ERRRRRRRRRRROR: "+e.getMessage());
e.printStackTrace();
}
}
| public FirstTimeQuery(ModelMap model,Connection con,HttpServletRequest request, int curYear, String access){
try {
Statement statement = con.createStatement();
String query=null;
ResultSet resultSet = null;
TitleArray titleArray= new TitleArray("Austria","Agricultural Tractor", "sales" );
int countryId = 7;
String multiplier="";
if (access.equals("c")) {
titleArray = new TitleArray("China","Agricultural Tractor", "sales" );
countryId = 210000;
multiplier="*10000";
}
if (access.equals("i")) {
titleArray = new TitleArray("India","Agricultural Tractor", "sales" );
countryId = 2000000;
multiplier="*200000";
}
query="SELECT YEAR(DATE_ADD( CURDATE(), INTERVAL -5 YEAR)) as year1 ";
List<Year> years = new ArrayList<Year>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Year year = new Year(resultSet.getString("year1"),resultSet.getString("year1"));
years.add(year);
for (int i=1;i<=10;i++) {
Year nextYear = new Year(
Integer.toString(Integer.parseInt(year.getId())+i),
Integer.toString(Integer.parseInt(year.getId())+i));
years.add(nextYear);
}
}
YearArray yearArray = new YearArray("Company",years,"TOTAL");
ColumnModel columnModel = new ColumnModel(yearArray.getJsonYearArray());
String query2="";
if (access.equals("w")) {
query2 = " select a.year, SUM(a.quantity) as quantity, substr(b.name,1,20) as name " +
" from Facts_w a, Company b, Country c, Product d "+
" where a.companyid=b.id and a.sales_production=1 AND a.countryId NOT IN (20,21,0) "+
" and a.productId = 1 and a.year >=2008 and b.name != 'ALL COMPANIES' "+
" and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " +
" and d.id = a.productId and a.access = 'w' and a.countryId = c.id "+
" group by a.year, b.name, d.name, 'EUROPE' order by b.name , a.year asc ";
}else {
query2 = " select a.year, a.quantity, b.name from Facts_"+access+" a, Company b, Country c " +
" where a.companyid=b.id " +
" and a.countryid=c.id " +
" and c.id="+countryId +
" and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " +
" and a.sales_production= 1" +
" and a.productid=1"+multiplier +
" and a.access = '" + access + "' " +
" and b.name!='ALL COMPANIES' " +
" order by b.name , a.year asc";
}
resultSet = statement.executeQuery(query2);
String currentCompany="";
JSONObject obj2a = null;
JSONArray array7 = new JSONArray();
totalLine2 = new HashMap<String,Integer>();
otherLine2 = new HashMap<String,Integer>();
while (resultSet.next()) {
int totalQuantity=0;
if (totalLine2.get(resultSet.getString("year"))!= null) {
totalQuantity= totalLine2.get(resultSet.getString("year"));
}
totalQuantity += Integer.parseInt(resultSet.getString("quantity"));
totalLine2.put(resultSet.getString("year"), totalQuantity);
int otherQuantity=0;
if (otherLine2.get(resultSet.getString("year"))!= null) {
otherQuantity= otherLine2.get(resultSet.getString("year"));
}
otherQuantity += Integer.parseInt(resultSet.getString("quantity"));
otherLine2.put(resultSet.getString("year"), otherQuantity);
if (!currentCompany.equals(resultSet.getString("name"))) {
if (!currentCompany.equals("")){
array7.put(obj2a);
}
obj2a = new JSONObject();
currentCompany=resultSet.getString("name");
obj2a.put("Company",currentCompany);
obj2a.put(resultSet.getString("year"),resultSet.getString("quantity"));
} else {
obj2a.put(resultSet.getString("year"),resultSet.getString("quantity"));
}
}
if (obj2a != null) {
array7.put(obj2a);
}
JSONObject obj7 = new JSONObject();
obj7.put("myData", array7);
JSONArray array4 = new JSONArray();
array4.put(columnModel.getModelObject());
array4.put(yearArray.getJsonYearObject());
array4.put(obj7);
array4.put(titleArray.getJsonTitleObject());
JSONObject obj5 = new JSONObject();
obj5.put("tabData", array4);
AddJsonRowTotal aj = new AddJsonRowTotal(obj5);
JSONObject objTotal = new JSONObject();
objTotal.put("Company","TOTAL");
Iterator<Entry<String, Integer>> it = totalLine2.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Integer> pairs = it.next();
objTotal.put(pairs.getKey(), pairs.getValue());
}
objTotal.put("TOTAL", aj.getTotal());
JSONArray array8 = new JSONArray();
if (objTotal != null) {
array8.put(objTotal);
JSONObject obj8 = new JSONObject();
obj8.put("myTotals", array8);
model.addAttribute("jsonTotal",obj8);
}
model.addAttribute("jsonData",obj5);
logger.warning(obj5.toString());
if (request.getParameter("list") == null){
query = "select id, country from Country where id != 0 and access = '"+access+"' order by country asc " ;
List<Country> countries = new ArrayList<Country>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Country country = new Country(resultSet.getString("id"),resultSet.getString("country"));
countries.add(country);
}
model.addAttribute("dropdown1a",countries);
model.addAttribute("dropdown2a",countries);
query = "select id, name from Product where id != 0 and access = '"+access+"' order by name asc " ;
List<Product> products = new ArrayList<Product>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Product product = new Product(resultSet.getString("id"),resultSet.getString("name"));
products.add(product);
}
model.addAttribute("dropdown1b",products);
model.addAttribute("dropdown2b",products);
model.addAttribute("dropdown1c",years);
model.addAttribute("dropdown2c",years);
query = " select distinct a.id, substr(a.name,1,20) as name from Company a , Facts_"+access+" b " +
" where a.id != 0" +
" and b.companyid = a.id " +
" and b.access = '" + access +"' and " +
" a.access = '" + access + "' " +
" and a.name != 'ALL COMPANIES' " +
" order by a.name asc " ;
logger.warning(query);
List<Company> companies = new ArrayList<Company>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Company company = new Company(resultSet.getString("id"),resultSet.getString("name"));
companies.add(company);
}
model.addAttribute("dropdown1d",companies);
model.addAttribute("dropdown2d",companies);
model.addAttribute("firstTimeFromServer",obj5);
this.model = model;
}
}catch(Exception e) {
logger.warning("ERRRRRRRRRRROR: "+e.getMessage());
e.printStackTrace();
}
}
|
protected <U extends IValue> Result<U> makeRangeFromNumber(NumberResult from) {
if (getType().lub(from.getType()).isIntegerType()) {
return makeRangeWithDefaultStep(from, getValueFactory().integer(1));
}
if (getType().lub(from.getType()).isRealType()) {
return makeRangeWithDefaultStep(from, getValueFactory().real(1.0));
}
throw new ImplementationError("Unknown number type in makeRangeFromNumber");
}
| protected <U extends IValue> Result<U> makeRangeFromNumber(NumberResult from) {
if (getType().lub(from.getType()).isIntegerType()) {
return makeRangeWithDefaultStep(from, getValueFactory().integer(1));
}
if (getType().lub(from.getType()).isRealType()) {
return makeRangeWithDefaultStep(from, getValueFactory().real(1.0));
}
if (getType().lub(from.getType()).isNumberType()) {
return makeRangeWithDefaultStep(from, getValueFactory().integer(1));
}
throw new ImplementationError("Unknown number type in makeRangeFromNumber");
}
|
public boolean hasNext() {
if (frame != null && frame.next == null) {
while (true) {
if (frame.previous == Status.INIT) {
H id2 = context2.getModel().getHandle(frame.node2);
if (frame.node1 == null)
{
frame.next = Status.ENTER;
frame.source = null;
frame.destination = frame.node2;
}
else
{
H id1 = context1.getModel().getHandle(frame.node1);
if (diff.comparator.compare(id1, id2) != 0) {
frame.next = Status.ERROR;
frame.source = frame.node1;
frame.destination = frame.node2;
} else {
frame.next = Status.ENTER;
frame.source = frame.node1;
frame.destination = frame.node2;
}
}
break;
} else if (frame.previous == Status.ERROR) {
break;
} else if (frame.previous == Status.LEAVE) {
frame = frame.parent;
if (frame != null) {
frame.previous = Status.RESUME;
continue;
} else {
break;
}
} else if (frame.previous == Status.MOVED_IN) {
frame = new Frame(frame, frame.source, frame.destination);
continue;
} else if (frame.previous == Status.ADDED) {
frame = new Frame(frame, frame.source, frame.destination);
continue;
} else if (frame.previous == Status.ENTER) {
ListAdapter<L1, H> adapter1;
L1 children1;
if (frame.source != null)
{
children1 = context1.getModel().getChildren(frame.node1);
adapter1 = diff.adapter1;
}
else
{
children1 = null;
adapter1 = new ListAdapter<L1, H>() {
public int size(L1 list) {
return 0;
}
public Iterator<H> iterator(L1 list, boolean reverse) {
return Collections.<H>emptyList().iterator();
}
};
}
L2 children2 = context2.getModel().getChildren(frame.node2);
frame.it1 = adapter1.iterator(children1, false);
frame.it2 = diff.adapter2.iterator(children2, false);
frame.it = LCS.create(
adapter1,
diff.adapter2,
diff.comparator).perform(children1, children2);
} else {
}
if (frame.it.hasNext()) {
switch (frame.it.next()) {
case KEEP:
N1 next1 = context1.findByHandle(frame.it1.next());
N2 next2 = context2.findByHandle(frame.it2.next());
frame = new Frame(frame, next1, next2);
return hasNext();
case ADD:
frame.it2.next();
H addedHandle = frame.it.getElement();
N2 added = context2.findByHandle(addedHandle);
H addedId = context2.getModel().getHandle(added);
N1 a = context1.findByHandle(addedId);
if (a != null) {
frame.next = Status.MOVED_IN;
frame.source = a;
frame.destination = added;
} else {
frame.next = Status.ADDED;
frame.source = null;
frame.destination = added;
}
break;
case REMOVE:
frame.it1.next();
H removedHandle = frame.it.getElement();
N1 removed = context1.findByHandle(removedHandle);
H removedId = context1.getModel().getHandle(removed);
N2 b = context2.findByHandle(removedId);
if (b != null) {
frame.next = Status.MOVED_OUT;
frame.source = removed;
frame.destination = b;
} else {
frame.next = Status.REMOVED;
frame.source = removed;
frame.destination = null;
}
break;
default:
throw new AssertionError();
}
} else {
frame.next = Status.LEAVE;
frame.source = frame.node1;
frame.destination = frame.node2;
}
break;
}
}
return frame != null && frame.next != null;
}
| public boolean hasNext() {
if (frame != null && frame.next == null) {
while (true) {
if (frame.previous == Status.INIT) {
H id2 = context2.getModel().getHandle(frame.node2);
if (frame.node1 == null)
{
frame.next = Status.ENTER;
frame.source = null;
frame.destination = frame.node2;
}
else
{
H id1 = context1.getModel().getHandle(frame.node1);
if (diff.comparator.compare(id1, id2) != 0) {
frame.next = Status.ERROR;
frame.source = frame.node1;
frame.destination = frame.node2;
} else {
frame.next = Status.ENTER;
frame.source = frame.node1;
frame.destination = frame.node2;
}
}
break;
} else if (frame.previous == Status.ERROR) {
break;
} else if (frame.previous == Status.LEAVE) {
frame = frame.parent;
if (frame != null) {
frame.previous = Status.RESUME;
continue;
} else {
break;
}
} else if (frame.previous == Status.MOVED_IN) {
frame = new Frame(frame, frame.source, frame.destination);
continue;
} else if (frame.previous == Status.ADDED) {
frame = new Frame(frame, frame.source, frame.destination);
continue;
} else if (frame.previous == Status.ENTER) {
ListAdapter<L1, H> adapter1;
L1 children1;
if (frame.source != null)
{
children1 = context1.getModel().getChildren(frame.node1);
adapter1 = diff.adapter1;
}
else
{
children1 = null;
adapter1 = new ListAdapter<L1, H>() {
public int size(L1 list) {
return 0;
}
public Iterator<H> iterator(L1 list, boolean reverse) {
return Collections.<H>emptyList().iterator();
}
};
}
L2 children2 = context2.getModel().getChildren(frame.node2);
frame.it1 = adapter1.iterator(children1, false);
frame.it2 = diff.adapter2.iterator(children2, false);
frame.it = LCS.create(
adapter1,
diff.adapter2,
diff.comparator).perform(children1, children2);
} else {
}
if (frame.it.hasNext()) {
switch (frame.it.next()) {
case KEEP:
N1 next1 = context1.findByHandle(frame.it1.next());
N2 next2 = context2.findByHandle(frame.it2.next());
frame = new Frame(frame, next1, next2);
continue;
case ADD:
frame.it2.next();
H addedHandle = frame.it.getElement();
N2 added = context2.findByHandle(addedHandle);
H addedId = context2.getModel().getHandle(added);
N1 a = context1.findByHandle(addedId);
if (a != null) {
frame.next = Status.MOVED_IN;
frame.source = a;
frame.destination = added;
} else {
frame.next = Status.ADDED;
frame.source = null;
frame.destination = added;
}
break;
case REMOVE:
frame.it1.next();
H removedHandle = frame.it.getElement();
N1 removed = context1.findByHandle(removedHandle);
H removedId = context1.getModel().getHandle(removed);
N2 b = context2.findByHandle(removedId);
if (b != null) {
frame.next = Status.MOVED_OUT;
frame.source = removed;
frame.destination = b;
} else {
frame.next = Status.REMOVED;
frame.source = removed;
frame.destination = null;
}
break;
default:
throw new AssertionError();
}
} else {
frame.next = Status.LEAVE;
frame.source = frame.node1;
frame.destination = frame.node2;
}
break;
}
}
return frame != null && frame.next != null;
}
|
public JComponent build() {
Locale locale = new Locale(configuration.getLanguage());
ComponentOrientation orientation = ComponentOrientation.getOrientation(locale);
String colSpec = FormLayoutUtil.getColSpec(COL_SPEC, orientation);
FormLayout layout = new FormLayout(colSpec, ROW_SPEC);
PanelBuilder builder = new PanelBuilder(layout);
builder.border(Borders.DLU4);
builder.opaque(true);
CellConstraints cc = new CellConstraints();
smcheckBox = new JCheckBox(Messages.getString("NetworkTab.3"));
smcheckBox.setContentAreaFilled(false);
smcheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMinimized((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (configuration.isMinimized()) {
smcheckBox.setSelected(true);
}
autoStart = new JCheckBox(Messages.getString("NetworkTab.57"));
autoStart.setContentAreaFilled(false);
autoStart.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setAutoStart((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (configuration.isAutoStart()) {
autoStart.setSelected(true);
}
JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), FormLayoutUtil.flip(cc.xyw(1, 1, 9), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.addLabel(Messages.getString("NetworkTab.0"), FormLayoutUtil.flip(cc.xy(1, 7), colSpec, orientation));
final KeyedComboBoxModel kcbm = new KeyedComboBoxModel(new Object[] {
"ar", "bg", "ca", "zhs", "zht", "cz", "da", "nl", "en", "en_uk", "fi", "fr",
"de", "el", "iw", "is", "it", "ja", "ko", "no", "pl", "pt", "br",
"ro", "ru", "sl", "es", "sv", "tr"}, new Object[] {
"Arabic", "Bulgarian", "Catalan", "Chinese (Simplified)",
"Chinese (Traditional)", "Czech", "Danish", "Dutch", "English (US)", "English (UK)",
"Finnish", "French", "German", "Greek", "Hebrew", "Icelandic", "Italian",
"Japanese", "Korean", "Norwegian", "Polish", "Portuguese",
"Portuguese (Brazilian)", "Romanian", "Russian", "Slovenian",
"Spanish", "Swedish", "Turkish"});
langs = new JComboBox(kcbm);
langs.setEditable(false);
String defaultLang;
if (configuration.getLanguage() != null && configuration.getLanguage().length() > 0) {
defaultLang = configuration.getLanguage();
} else {
defaultLang = Locale.getDefault().getLanguage();
}
if (defaultLang == null) {
defaultLang = "en";
}
kcbm.setSelectedKey(defaultLang);
if (langs.getSelectedIndex() == -1) {
langs.setSelectedIndex(0);
}
langs.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
configuration.setLanguage((String) kcbm.getSelectedKey());
}
}
});
builder.add(langs, FormLayoutUtil.flip(cc.xyw(3, 7, 7), colSpec, orientation));
builder.add(smcheckBox, FormLayoutUtil.flip(cc.xy(1, 9), colSpec, orientation));
if (Platform.isWindows()) {
builder.add(autoStart, FormLayoutUtil.flip(cc.xyw(3, 9, 7), colSpec, orientation));
}
if (!configuration.isHideAdvancedOptions()) {
CustomJButton service = new CustomJButton(Messages.getString("NetworkTab.4"));
service.setToolTipText(Messages.getString("NetworkTab.63"));
service.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (PMS.get().installWin32Service()) {
LOGGER.info(Messages.getString("PMS.41"));
JOptionPane.showMessageDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("NetworkTab.11") +
Messages.getString("NetworkTab.12"),
Messages.getString("Dialog.Information"),
JOptionPane.INFORMATION_MESSAGE
);
} else {
JOptionPane.showMessageDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("NetworkTab.14"),
Messages.getString("Dialog.Error"),
JOptionPane.ERROR_MESSAGE
);
}
}
});
builder.add(service, FormLayoutUtil.flip(cc.xy(1, 11), colSpec, orientation));
if (System.getProperty(LooksFrame.START_SERVICE) != null || !Platform.isWindows()) {
service.setEnabled(false);
}
CustomJButton serviceUninstall = new CustomJButton(Messages.getString("GeneralTab.2"));
serviceUninstall.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PMS.get().uninstallWin32Service();
LOGGER.info(Messages.getString("GeneralTab.3"));
JOptionPane.showMessageDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("GeneralTab.3"),
Messages.getString("Dialog.Information"),
JOptionPane.INFORMATION_MESSAGE
);
}
});
builder.add(serviceUninstall, FormLayoutUtil.flip(cc.xy(3, 11), colSpec, orientation));
if (System.getProperty(LooksFrame.START_SERVICE) != null || !Platform.isWindows()) {
serviceUninstall.setEnabled(false);
}
}
CustomJButton checkForUpdates = new CustomJButton(Messages.getString("NetworkTab.8"));
checkForUpdates.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LooksFrame frame = (LooksFrame) PMS.get().getFrame();
frame.checkForUpdates();
}
});
if (configuration.isHideAdvancedOptions()) {
builder.add(checkForUpdates, FormLayoutUtil.flip(cc.xy(1, 11), colSpec, orientation));
} else {
builder.add(checkForUpdates, FormLayoutUtil.flip(cc.xy(1, 13), colSpec, orientation));
}
autoUpdateCheckBox = new JCheckBox(Messages.getString("NetworkTab.9"));
autoUpdateCheckBox.setContentAreaFilled(false);
autoUpdateCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setAutoUpdate((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (configuration.isAutoUpdate()) {
autoUpdateCheckBox.setSelected(true);
}
if (configuration.isHideAdvancedOptions()) {
builder.add(autoUpdateCheckBox, FormLayoutUtil.flip(cc.xyw(3, 11, 7), colSpec, orientation));
} else {
builder.add(autoUpdateCheckBox, FormLayoutUtil.flip(cc.xyw(3, 13, 7), colSpec, orientation));
}
if (!Build.isUpdatable()) {
checkForUpdates.setEnabled(false);
autoUpdateCheckBox.setEnabled(false);
}
hideAdvancedOptions = new JCheckBox(Messages.getString("NetworkTab.61"));
hideAdvancedOptions.setContentAreaFilled(false);
hideAdvancedOptions.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configuration.setHideAdvancedOptions(hideAdvancedOptions.isSelected());
}
});
if (configuration.isHideAdvancedOptions()) {
hideAdvancedOptions.setSelected(true);
builder.add(hideAdvancedOptions, FormLayoutUtil.flip(cc.xyw(1, 13, 9), colSpec, orientation));
} else {
builder.add(hideAdvancedOptions, FormLayoutUtil.flip(cc.xyw(1, 15, 9), colSpec, orientation));
}
ArrayList<RendererConfiguration> allConfs = RendererConfiguration.getEnabledRenderersConfigurations();
ArrayList<Object> keyValues = new ArrayList<>();
ArrayList<Object> nameValues = new ArrayList<>();
keyValues.add("");
nameValues.add(Messages.getString("NetworkTab.37"));
if (allConfs != null) {
for (RendererConfiguration renderer : allConfs) {
if (renderer != null) {
keyValues.add(renderer.getRendererName());
nameValues.add(renderer.getRendererName());
}
}
}
final KeyedComboBoxModel renderersKcbm = new KeyedComboBoxModel(
(Object[]) keyValues.toArray(new Object[keyValues.size()]),
(Object[]) nameValues.toArray(new Object[nameValues.size()]));
renderers = new JComboBox(renderersKcbm);
renderers.setEditable(false);
String defaultRenderer = configuration.getRendererDefault();
renderersKcbm.setSelectedKey(defaultRenderer);
if (renderers.getSelectedIndex() == -1) {
renderers.setSelectedIndex(0);
}
if (!configuration.isHideAdvancedOptions()) {
CustomJButton confEdit = new CustomJButton(Messages.getString("NetworkTab.51"));
confEdit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel tPanel = new JPanel(new BorderLayout());
final File conf = new File(configuration.getProfilePath());
final JTextArea textArea = new JTextArea();
textArea.setFont(new Font("Courier", Font.PLAIN, 12));
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new java.awt.Dimension(900, 450));
try {
try (FileInputStream fis = new FileInputStream(conf); BufferedReader in = new BufferedReader(new InputStreamReader(fis))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
}
} catch (Exception e1) {
return;
}
tPanel.add(scrollPane, BorderLayout.NORTH);
Object[] options = {Messages.getString("LooksFrame.9"), Messages.getString("NetworkTab.45")};
if (JOptionPane.showOptionDialog((JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
tPanel, Messages.getString("NetworkTab.51"),
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, null) == JOptionPane.OK_OPTION) {
String text = textArea.getText();
try {
try (FileOutputStream fos = new FileOutputStream(conf)) {
fos.write(text.getBytes());
fos.flush();
}
configuration.reload();
} catch (Exception e1) {
JOptionPane.showMessageDialog((JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("NetworkTab.52") + e1.toString());
}
}
}
});
builder.add(confEdit, FormLayoutUtil.flip(cc.xy(1, 17), colSpec, orientation));
host = new JTextField(configuration.getServerHostname());
host.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setHostname(host.getText());
}
});
port = new JTextField(configuration.getServerPort() != 5001 ? "" + configuration.getServerPort() : "");
port.setToolTipText(Messages.getString("NetworkTab.64"));
port.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
try {
String p = port.getText();
if (StringUtils.isEmpty(p)) {
p = "5001";
}
int ab = Integer.parseInt(p);
configuration.setServerPort(ab);
} catch (NumberFormatException nfe) {
LOGGER.debug("Could not parse port from \"" + port.getText() + "\"");
}
}
});
cmp = builder.addSeparator(Messages.getString("NetworkTab.22"), FormLayoutUtil.flip(cc.xyw(1, 19, 9), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
final KeyedComboBoxModel networkInterfaces = createNetworkInterfacesModel();
networkinterfacesCBX = new JComboBox(networkInterfaces);
networkInterfaces.setSelectedKey(configuration.getNetworkInterface());
networkinterfacesCBX.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
configuration.setNetworkInterface((String) networkInterfaces.getSelectedKey());
}
}
});
ip_filter = new JTextField(configuration.getIpFilter());
ip_filter.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setIpFilter(ip_filter.getText());
}
});
maxbitrate = new JTextField(configuration.getMaximumBitrateDisplay());
maxbitrate.setToolTipText(Messages.getString("NetworkTab.65"));
maxbitrate.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMaximumBitrate(maxbitrate.getText());
}
});
builder.addLabel(Messages.getString("NetworkTab.20"), FormLayoutUtil.flip(cc.xy(1, 21), colSpec, orientation));
builder.add(networkinterfacesCBX, FormLayoutUtil.flip(cc.xyw(3, 21, 7), colSpec, orientation));
builder.addLabel(Messages.getString("NetworkTab.23"), FormLayoutUtil.flip(cc.xy(1, 23), colSpec, orientation));
builder.add(host, FormLayoutUtil.flip(cc.xyw(3, 23, 7), colSpec, orientation));
builder.addLabel(Messages.getString("NetworkTab.24"), FormLayoutUtil.flip(cc.xy(1, 25), colSpec, orientation));
builder.add(port, FormLayoutUtil.flip(cc.xyw(3, 25, 7), colSpec, orientation));
builder.addLabel(Messages.getString("NetworkTab.30"), FormLayoutUtil.flip(cc.xy(1, 27), colSpec, orientation));
builder.add(ip_filter, FormLayoutUtil.flip(cc.xyw(3, 27, 7), colSpec, orientation));
builder.addLabel(Messages.getString("NetworkTab.35"), FormLayoutUtil.flip(cc.xy(1, 29), colSpec, orientation));
builder.add(maxbitrate, FormLayoutUtil.flip(cc.xyw(3, 29, 7), colSpec, orientation));
cmp = builder.addSeparator(Messages.getString("NetworkTab.31"), FormLayoutUtil.flip(cc.xyw(1, 31, 9), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
newHTTPEngine = new JCheckBox(Messages.getString("NetworkTab.32"));
newHTTPEngine.setSelected(configuration.isHTTPEngineV2());
newHTTPEngine.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setHTTPEngineV2((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(newHTTPEngine, FormLayoutUtil.flip(cc.xy(1, 33), colSpec, orientation));
preventSleep = new JCheckBox(Messages.getString("NetworkTab.33"));
preventSleep.setSelected(configuration.isPreventsSleep());
preventSleep.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setPreventsSleep((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(preventSleep, FormLayoutUtil.flip(cc.xy(1, 35), colSpec, orientation));
JCheckBox fdCheckBox = new JCheckBox(Messages.getString("NetworkTab.38"));
fdCheckBox.setContentAreaFilled(false);
fdCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setRendererForceDefault((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (configuration.isRendererForceDefault()) {
fdCheckBox.setSelected(true);
}
builder.addLabel(Messages.getString("NetworkTab.62"), FormLayoutUtil.flip(cc.xy(1, 37), colSpec, orientation));
final CustomJButton setRenderers = new CustomJButton(Messages.getString("GeneralTab.5"));
setRenderers.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SelectRenderers.showDialog();
}
});
builder.add(setRenderers, FormLayoutUtil.flip(cc.xy(3, 37), colSpec, orientation));
builder.addLabel(Messages.getString("NetworkTab.36"), FormLayoutUtil.flip(cc.xy(1, 39), colSpec, orientation));
builder.add(renderers, FormLayoutUtil.flip(cc.xyw(3, 39, 7), colSpec, orientation));
extNetBox = new JCheckBox(Messages.getString("NetworkTab.56"));
extNetBox.setToolTipText(Messages.getString("NetworkTab.67"));
extNetBox.setContentAreaFilled(false);
extNetBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setExternalNetwork((e.getStateChange() == ItemEvent.SELECTED));
}
});
extNetBox.setSelected(configuration.getExternalNetwork());
builder.add(extNetBox, FormLayoutUtil.flip(cc.xy(1, 43), colSpec, orientation));
}
JPanel panel = builder.getPanel();
panel.applyComponentOrientation(orientation);
JScrollPane scrollPane = new JScrollPane(
panel,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
return scrollPane;
}
| public JComponent build() {
Locale locale = new Locale(configuration.getLanguage());
ComponentOrientation orientation = ComponentOrientation.getOrientation(locale);
String colSpec = FormLayoutUtil.getColSpec(COL_SPEC, orientation);
FormLayout layout = new FormLayout(colSpec, ROW_SPEC);
PanelBuilder builder = new PanelBuilder(layout);
builder.border(Borders.DLU4);
builder.opaque(true);
CellConstraints cc = new CellConstraints();
smcheckBox = new JCheckBox(Messages.getString("NetworkTab.3"));
smcheckBox.setContentAreaFilled(false);
smcheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMinimized((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (configuration.isMinimized()) {
smcheckBox.setSelected(true);
}
autoStart = new JCheckBox(Messages.getString("NetworkTab.57"));
autoStart.setContentAreaFilled(false);
autoStart.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setAutoStart((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (configuration.isAutoStart()) {
autoStart.setSelected(true);
}
JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), FormLayoutUtil.flip(cc.xyw(1, 1, 9), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.addLabel(Messages.getString("NetworkTab.0"), FormLayoutUtil.flip(cc.xy(1, 7), colSpec, orientation));
final KeyedComboBoxModel kcbm = new KeyedComboBoxModel(new Object[] {
"ar", "bg", "ca", "zhs", "zht", "cz", "da", "nl", "en", "en_uk", "fi", "fr",
"de", "el", "iw", "is", "it", "ja", "ko", "no", "pl", "pt", "br",
"ro", "ru", "sl", "es", "sv", "tr"}, new Object[] {
"Arabic", "Bulgarian", "Catalan", "Chinese (Simplified)",
"Chinese (Traditional)", "Czech", "Danish", "Dutch", "English (US)", "English (UK)",
"Finnish", "French", "German", "Greek", "Hebrew", "Icelandic", "Italian",
"Japanese", "Korean", "Norwegian", "Polish", "Portuguese",
"Portuguese (Brazilian)", "Romanian", "Russian", "Slovenian",
"Spanish", "Swedish", "Turkish"});
langs = new JComboBox(kcbm);
langs.setEditable(false);
String defaultLang;
if (configuration.getLanguage() != null && configuration.getLanguage().length() > 0) {
defaultLang = configuration.getLanguage();
} else {
defaultLang = Locale.getDefault().getLanguage();
}
if (defaultLang == null) {
defaultLang = "en";
}
kcbm.setSelectedKey(defaultLang);
if (langs.getSelectedIndex() == -1) {
langs.setSelectedIndex(0);
}
langs.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
configuration.setLanguage((String) kcbm.getSelectedKey());
}
}
});
builder.add(langs, FormLayoutUtil.flip(cc.xyw(3, 7, 7), colSpec, orientation));
builder.add(smcheckBox, FormLayoutUtil.flip(cc.xy(1, 9), colSpec, orientation));
if (Platform.isWindows()) {
builder.add(autoStart, FormLayoutUtil.flip(cc.xyw(3, 9, 7), colSpec, orientation));
}
if (!configuration.isHideAdvancedOptions()) {
CustomJButton service = new CustomJButton(Messages.getString("NetworkTab.4"));
service.setToolTipText(Messages.getString("NetworkTab.63"));
service.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (PMS.get().installWin32Service()) {
LOGGER.info(Messages.getString("PMS.41"));
JOptionPane.showMessageDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("NetworkTab.11") +
Messages.getString("NetworkTab.12"),
Messages.getString("Dialog.Information"),
JOptionPane.INFORMATION_MESSAGE
);
} else {
JOptionPane.showMessageDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("NetworkTab.14"),
Messages.getString("Dialog.Error"),
JOptionPane.ERROR_MESSAGE
);
}
}
});
builder.add(service, FormLayoutUtil.flip(cc.xy(1, 11), colSpec, orientation));
if (System.getProperty(LooksFrame.START_SERVICE) != null || !Platform.isWindows()) {
service.setEnabled(false);
}
CustomJButton serviceUninstall = new CustomJButton(Messages.getString("GeneralTab.2"));
serviceUninstall.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PMS.get().uninstallWin32Service();
LOGGER.info(Messages.getString("GeneralTab.3"));
JOptionPane.showMessageDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("GeneralTab.3"),
Messages.getString("Dialog.Information"),
JOptionPane.INFORMATION_MESSAGE
);
}
});
builder.add(serviceUninstall, FormLayoutUtil.flip(cc.xy(3, 11), colSpec, orientation));
if (System.getProperty(LooksFrame.START_SERVICE) != null || !Platform.isWindows()) {
serviceUninstall.setEnabled(false);
}
}
CustomJButton checkForUpdates = new CustomJButton(Messages.getString("NetworkTab.8"));
checkForUpdates.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LooksFrame frame = (LooksFrame) PMS.get().getFrame();
frame.checkForUpdates();
}
});
if (configuration.isHideAdvancedOptions()) {
builder.add(checkForUpdates, FormLayoutUtil.flip(cc.xy(1, 11), colSpec, orientation));
} else {
builder.add(checkForUpdates, FormLayoutUtil.flip(cc.xy(1, 13), colSpec, orientation));
}
autoUpdateCheckBox = new JCheckBox(Messages.getString("NetworkTab.9"));
autoUpdateCheckBox.setContentAreaFilled(false);
autoUpdateCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setAutoUpdate((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (configuration.isAutoUpdate()) {
autoUpdateCheckBox.setSelected(true);
}
if (configuration.isHideAdvancedOptions()) {
builder.add(autoUpdateCheckBox, FormLayoutUtil.flip(cc.xyw(3, 11, 7), colSpec, orientation));
} else {
builder.add(autoUpdateCheckBox, FormLayoutUtil.flip(cc.xyw(3, 13, 7), colSpec, orientation));
}
if (!Build.isUpdatable()) {
checkForUpdates.setEnabled(false);
autoUpdateCheckBox.setEnabled(false);
}
hideAdvancedOptions = new JCheckBox(Messages.getString("NetworkTab.61"));
hideAdvancedOptions.setContentAreaFilled(false);
hideAdvancedOptions.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configuration.setHideAdvancedOptions(hideAdvancedOptions.isSelected());
}
});
if (configuration.isHideAdvancedOptions()) {
hideAdvancedOptions.setSelected(true);
builder.add(hideAdvancedOptions, FormLayoutUtil.flip(cc.xyw(1, 13, 9), colSpec, orientation));
} else {
builder.add(hideAdvancedOptions, FormLayoutUtil.flip(cc.xyw(1, 15, 9), colSpec, orientation));
}
ArrayList<RendererConfiguration> allConfs = RendererConfiguration.getEnabledRenderersConfigurations();
ArrayList<Object> keyValues = new ArrayList<>();
ArrayList<Object> nameValues = new ArrayList<>();
keyValues.add("");
nameValues.add(Messages.getString("NetworkTab.37"));
if (allConfs != null) {
for (RendererConfiguration renderer : allConfs) {
if (renderer != null) {
keyValues.add(renderer.getRendererName());
nameValues.add(renderer.getRendererName());
}
}
}
final KeyedComboBoxModel renderersKcbm = new KeyedComboBoxModel(
(Object[]) keyValues.toArray(new Object[keyValues.size()]),
(Object[]) nameValues.toArray(new Object[nameValues.size()]));
renderers = new JComboBox(renderersKcbm);
renderers.setEditable(false);
String defaultRenderer = configuration.getRendererDefault();
renderersKcbm.setSelectedKey(defaultRenderer);
if (renderers.getSelectedIndex() == -1) {
renderers.setSelectedIndex(0);
}
if (!configuration.isHideAdvancedOptions()) {
CustomJButton confEdit = new CustomJButton(Messages.getString("NetworkTab.51"));
confEdit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel tPanel = new JPanel(new BorderLayout());
final File conf = new File(configuration.getProfilePath());
final JTextArea textArea = new JTextArea();
textArea.setFont(new Font("Courier", Font.PLAIN, 12));
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new java.awt.Dimension(900, 450));
try {
try (FileInputStream fis = new FileInputStream(conf); BufferedReader in = new BufferedReader(new InputStreamReader(fis))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
textArea.setText(sb.toString());
}
} catch (Exception e1) {
return;
}
tPanel.add(scrollPane, BorderLayout.NORTH);
Object[] options = {Messages.getString("LooksFrame.9"), Messages.getString("NetworkTab.45")};
if (JOptionPane.showOptionDialog((JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
tPanel, Messages.getString("NetworkTab.51"),
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, null) == JOptionPane.OK_OPTION) {
String text = textArea.getText();
try {
try (FileOutputStream fos = new FileOutputStream(conf)) {
fos.write(text.getBytes());
fos.flush();
}
configuration.reload();
} catch (Exception e1) {
JOptionPane.showMessageDialog((JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("NetworkTab.52") + e1.toString());
}
}
}
});
builder.add(confEdit, FormLayoutUtil.flip(cc.xy(1, 17), colSpec, orientation));
host = new JTextField(configuration.getServerHostname());
host.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setHostname(host.getText());
}
});
port = new JTextField(configuration.getServerPort() != 5001 ? "" + configuration.getServerPort() : "");
port.setToolTipText(Messages.getString("NetworkTab.64"));
port.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
try {
String p = port.getText();
if (StringUtils.isEmpty(p)) {
p = "5001";
}
int ab = Integer.parseInt(p);
configuration.setServerPort(ab);
} catch (NumberFormatException nfe) {
LOGGER.debug("Could not parse port from \"" + port.getText() + "\"");
}
}
});
cmp = builder.addSeparator(Messages.getString("NetworkTab.22"), FormLayoutUtil.flip(cc.xyw(1, 19, 9), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
final KeyedComboBoxModel networkInterfaces = createNetworkInterfacesModel();
networkinterfacesCBX = new JComboBox(networkInterfaces);
networkInterfaces.setSelectedKey(configuration.getNetworkInterface());
networkinterfacesCBX.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
configuration.setNetworkInterface((String) networkInterfaces.getSelectedKey());
}
}
});
ip_filter = new JTextField(configuration.getIpFilter());
ip_filter.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setIpFilter(ip_filter.getText());
}
});
maxbitrate = new JTextField(configuration.getMaximumBitrateDisplay());
maxbitrate.setToolTipText(Messages.getString("NetworkTab.65"));
maxbitrate.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMaximumBitrate(maxbitrate.getText());
}
});
builder.addLabel(Messages.getString("NetworkTab.20"), FormLayoutUtil.flip(cc.xy(1, 21), colSpec, orientation));
builder.add(networkinterfacesCBX, FormLayoutUtil.flip(cc.xyw(3, 21, 7), colSpec, orientation));
builder.addLabel(Messages.getString("NetworkTab.23"), FormLayoutUtil.flip(cc.xy(1, 23), colSpec, orientation));
builder.add(host, FormLayoutUtil.flip(cc.xyw(3, 23, 7), colSpec, orientation));
builder.addLabel(Messages.getString("NetworkTab.24"), FormLayoutUtil.flip(cc.xy(1, 25), colSpec, orientation));
builder.add(port, FormLayoutUtil.flip(cc.xyw(3, 25, 7), colSpec, orientation));
builder.addLabel(Messages.getString("NetworkTab.30"), FormLayoutUtil.flip(cc.xy(1, 27), colSpec, orientation));
builder.add(ip_filter, FormLayoutUtil.flip(cc.xyw(3, 27, 7), colSpec, orientation));
builder.addLabel(Messages.getString("NetworkTab.35"), FormLayoutUtil.flip(cc.xy(1, 29), colSpec, orientation));
builder.add(maxbitrate, FormLayoutUtil.flip(cc.xyw(3, 29, 7), colSpec, orientation));
cmp = builder.addSeparator(Messages.getString("NetworkTab.31"), FormLayoutUtil.flip(cc.xyw(1, 31, 9), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
newHTTPEngine = new JCheckBox(Messages.getString("NetworkTab.32"));
newHTTPEngine.setSelected(configuration.isHTTPEngineV2());
newHTTPEngine.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setHTTPEngineV2((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(newHTTPEngine, FormLayoutUtil.flip(cc.xy(1, 33), colSpec, orientation));
preventSleep = new JCheckBox(Messages.getString("NetworkTab.33"));
preventSleep.setSelected(configuration.isPreventsSleep());
preventSleep.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setPreventsSleep((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(preventSleep, FormLayoutUtil.flip(cc.xy(1, 35), colSpec, orientation));
JCheckBox fdCheckBox = new JCheckBox(Messages.getString("NetworkTab.38"));
fdCheckBox.setContentAreaFilled(false);
fdCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setRendererForceDefault((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (configuration.isRendererForceDefault()) {
fdCheckBox.setSelected(true);
}
builder.addLabel(Messages.getString("NetworkTab.62"), FormLayoutUtil.flip(cc.xy(1, 37), colSpec, orientation));
final CustomJButton setRenderers = new CustomJButton(Messages.getString("GeneralTab.5"));
setRenderers.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SelectRenderers.showDialog();
}
});
builder.add(setRenderers, FormLayoutUtil.flip(cc.xy(3, 37), colSpec, orientation));
builder.addLabel(Messages.getString("NetworkTab.36"), FormLayoutUtil.flip(cc.xy(1, 39), colSpec, orientation));
builder.add(renderers, FormLayoutUtil.flip(cc.xyw(3, 39, 7), colSpec, orientation));
extNetBox = new JCheckBox(Messages.getString("NetworkTab.56"));
extNetBox.setToolTipText(Messages.getString("NetworkTab.67"));
extNetBox.setContentAreaFilled(false);
extNetBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setExternalNetwork((e.getStateChange() == ItemEvent.SELECTED));
}
});
extNetBox.setSelected(configuration.getExternalNetwork());
builder.add(extNetBox, FormLayoutUtil.flip(cc.xy(1, 43), colSpec, orientation));
}
JPanel panel = builder.getPanel();
panel.applyComponentOrientation(orientation);
JScrollPane scrollPane = new JScrollPane(
panel,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
return scrollPane;
}
|
public void testDeploymentUserPrivileges()
throws Exception
{
TestContainer.getInstance().getTestContext().setUsername( "test-user" );
TestContainer.getInstance().getTestContext().setPassword( "admin123" );
List<ClientPermission> permissions = this.getPermissions();
Assert.assertEquals( this.getExpectedPrivilegeCount(), permissions.size() );
this.checkPermission( permissions, "nexus:*", 0 );
this.checkPermission( permissions, "nexus:status", 1 );
this.checkPermission( permissions, "nexus:authentication", 1 );
this.checkPermission( permissions, "nexus:settings", 0 );
this.checkPermission( permissions, "nexus:repositories", 1 );
this.checkPermission( permissions, "nexus:repotemplates", 0 );
this.checkPermission( permissions, "nexus:repogroups", 1 );
this.checkPermission( permissions, "nexus:index", 1 );
this.checkPermission( permissions, "nexus:identify", 1 );
this.checkPermission( permissions, "nexus:attributes", 0 );
this.checkPermission( permissions, "nexus:cache", 0 );
this.checkPermission( permissions, "nexus:routes", 0 );
this.checkPermission( permissions, "nexus:tasks", 0 );
this.checkPermission( permissions, "security:privileges", 0 );
this.checkPermission( permissions, "security:roles", 0 );
this.checkPermission( permissions, "security:users", 0 );
this.checkPermission( permissions, "nexus:logs", 0 );
this.checkPermission( permissions, "nexus:configuration", 0 );
this.checkPermission( permissions, "nexus:feeds", 1 );
this.checkPermission( permissions, "nexus:targets", 0 );
this.checkPermission( permissions, "nexus:wastebasket", 0 );
this.checkPermission( permissions, "nexus:artifact", 1 );
this.checkPermission( permissions, "nexus:repostatus", 1 );
this.checkPermission( permissions, "security:usersforgotpw", 9 );
this.checkPermission( permissions, "security:usersforgotid", 9 );
this.checkPermission( permissions, "security:usersreset", 0 );
this.checkPermission( permissions, "security:userschangepw", 9 );
this.checkPermission( permissions, "nexus:command", 0 );
this.checkPermission( permissions, "nexus:repometa", 0 );
this.checkPermission( permissions, "nexus:tasksrun", 0 );
this.checkPermission( permissions, "nexus:tasktypes", 0 );
this.checkPermission( permissions, "nexus:componentscontentclasses", 1 );
this.checkPermission( permissions, "nexus:componentscheduletypes", 0 );
this.checkPermission( permissions, "security:userssetpw", 0 );
this.checkPermission( permissions, "nexus:componentrealmtypes", 0 );
this.checkPermission( permissions, "nexus:componentsrepotypes", 1 );
this.checkPermission( permissions, "security:componentsuserlocatortypes", 0 );
for ( ClientPermission outPermission : permissions )
{
int count = 0;
for ( ClientPermission inPermission : permissions )
{
if(outPermission.getId().equals( inPermission.getId() ))
{
count++;
}
if(count > 1)
{
Assert.fail( "Duplicate privilege: "+ outPermission.getId() +" found count: "+ count);
}
}
}
}
| public void testDeploymentUserPrivileges()
throws Exception
{
TestContainer.getInstance().getTestContext().setUsername( "test-user" );
TestContainer.getInstance().getTestContext().setPassword( "admin123" );
List<ClientPermission> permissions = this.getPermissions();
Assert.assertEquals( this.getExpectedPrivilegeCount(), permissions.size() );
this.checkPermission( permissions, "nexus:*", 0 );
this.checkPermission( permissions, "nexus:status", 1 );
this.checkPermission( permissions, "nexus:authentication", 1 );
this.checkPermission( permissions, "nexus:settings", 0 );
this.checkPermission( permissions, "nexus:repositories", 1 );
this.checkPermission( permissions, "nexus:repotemplates", 0 );
this.checkPermission( permissions, "nexus:repogroups", 1 );
this.checkPermission( permissions, "nexus:index", 1 );
this.checkPermission( permissions, "nexus:identify", 1 );
this.checkPermission( permissions, "nexus:attributes", 0 );
this.checkPermission( permissions, "nexus:cache", 0 );
this.checkPermission( permissions, "nexus:routes", 0 );
this.checkPermission( permissions, "nexus:tasks", 0 );
this.checkPermission( permissions, "security:privileges", 0 );
this.checkPermission( permissions, "security:roles", 0 );
this.checkPermission( permissions, "security:users", 0 );
this.checkPermission( permissions, "nexus:logs", 0 );
this.checkPermission( permissions, "nexus:configuration", 0 );
this.checkPermission( permissions, "nexus:targets", 0 );
this.checkPermission( permissions, "nexus:wastebasket", 0 );
this.checkPermission( permissions, "nexus:artifact", 1 );
this.checkPermission( permissions, "nexus:repostatus", 1 );
this.checkPermission( permissions, "security:usersforgotpw", 9 );
this.checkPermission( permissions, "security:usersforgotid", 9 );
this.checkPermission( permissions, "security:usersreset", 0 );
this.checkPermission( permissions, "security:userschangepw", 9 );
this.checkPermission( permissions, "nexus:command", 0 );
this.checkPermission( permissions, "nexus:repometa", 0 );
this.checkPermission( permissions, "nexus:tasksrun", 0 );
this.checkPermission( permissions, "nexus:tasktypes", 0 );
this.checkPermission( permissions, "nexus:componentscontentclasses", 1 );
this.checkPermission( permissions, "nexus:componentscheduletypes", 0 );
this.checkPermission( permissions, "security:userssetpw", 0 );
this.checkPermission( permissions, "nexus:componentrealmtypes", 0 );
this.checkPermission( permissions, "nexus:componentsrepotypes", 1 );
this.checkPermission( permissions, "security:componentsuserlocatortypes", 0 );
for ( ClientPermission outPermission : permissions )
{
int count = 0;
for ( ClientPermission inPermission : permissions )
{
if(outPermission.getId().equals( inPermission.getId() ))
{
count++;
}
if(count > 1)
{
Assert.fail( "Duplicate privilege: "+ outPermission.getId() +" found count: "+ count);
}
}
}
}
|
public TilePopup(final Tile tile, final FreeColClient freeColClient, final Canvas canvas, GUI gui) {
super(Messages.message("tile",
"%x%", String.valueOf(tile.getX()),
"%y%", String.valueOf(tile.getY())));
this.canvas = canvas;
this.gui = gui;
if (tile == null) {
return;
}
final Unit activeUnit = gui.getActiveUnit();
if (activeUnit != null) {
JMenuItem gotoMenuItem = new JMenuItem(Messages.message("gotoThisTile"));
gotoMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
freeColClient.getInGameController().setDestination(activeUnit, tile);
if (freeColClient.getGame().getCurrentPlayer() == freeColClient.getMyPlayer()) {
freeColClient.getInGameController().moveToDestination(activeUnit);
}
}
});
add(gotoMenuItem);
hasAnItem = true;
addSeparator();
}
for (final Unit currentUnit : tile.getUnitList()) {
addUnit(currentUnit, !currentUnit.isUnderRepair(), false);
for (Unit unit : currentUnit.getUnitList()) {
addUnit(unit, true, true);
}
boolean hasGoods = false;
for (Goods goods: currentUnit.getGoodsList()) {
addGoods(goods, false, true);
hasGoods = true;
}
if (hasGoods) {
JMenuItem dumpItem = new JMenuItem(Messages.message("dumpCargo"));
dumpItem.setAction(new UnloadAction(freeColClient));
add(dumpItem);
}
}
if (tile.getUnitCount() > 0) {
addSeparator();
}
Settlement settlement = tile.getSettlement();
if (settlement != null) {
if (settlement.getOwner() == freeColClient.getMyPlayer()) {
addColony(((Colony) settlement));
} else if (settlement instanceof IndianSettlement) {
addIndianSettlement((IndianSettlement) settlement);
}
if (hasItem()) {
addSeparator();
}
}
addTile(tile);
if (FreeCol.isInDebugMode()
&& freeColClient.getFreeColServer() != null) {
addSeparator();
JMenu takeOwnership = new JMenu("Take ownership");
takeOwnership.setOpaque(false);
boolean notEmpty = false;
for (final Unit currentUnit : tile.getUnitList()) {
JMenuItem toMenuItem = new JMenuItem(currentUnit.toString());
toMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Player mp = (Player) freeColClient.getFreeColServer().getGame()
.getFreeColGameObject(freeColClient.getMyPlayer().getId());
currentUnit.setOwner(mp);
for (Unit unit : currentUnit.getUnitList()) {
unit.setOwner(mp);
}
}
});
takeOwnership.add(toMenuItem);
notEmpty = true;
if (currentUnit.isCarrier()) {
final AIUnit au = (AIUnit) freeColClient.getFreeColServer().getAIMain().getAIObject(currentUnit);
if (au.getMission() != null && au.getMission() instanceof TransportMission) {
JMenuItem menuItem = new JMenuItem("Transport list for: " + currentUnit.toString() +
" (" + currentUnit.hashCode() + ")");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
canvas.showInformationMessage(au.getMission().toString());
}
});
}
}
}
if (tile.getSettlement() != null) {
if (!notEmpty) {
takeOwnership.addSeparator();
}
JMenuItem toMenuItem = new JMenuItem(tile.getSettlement().toString());
toMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Player mp = (Player) freeColClient.getFreeColServer().getGame()
.getFreeColGameObject(freeColClient.getMyPlayer().getId());
tile.getSettlement().setOwner(mp);
}
});
takeOwnership.add(toMenuItem);
notEmpty = true;
}
if (notEmpty) {
add(takeOwnership);
hasAnItem = true;
}
}
}
| public TilePopup(final Tile tile, final FreeColClient freeColClient, final Canvas canvas, GUI gui) {
super(Messages.message("tile",
"%x%", String.valueOf(tile.getX()),
"%y%", String.valueOf(tile.getY())));
this.canvas = canvas;
this.gui = gui;
if (tile == null) {
return;
}
final Unit activeUnit = gui.getActiveUnit();
if (activeUnit != null) {
JMenuItem gotoMenuItem = new JMenuItem(Messages.message("gotoThisTile"));
gotoMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (activeUnit.getTile()!=tile) {
freeColClient.getInGameController().setDestination(activeUnit, tile);
if (freeColClient.getGame().getCurrentPlayer() == freeColClient.getMyPlayer()) {
freeColClient.getInGameController().moveToDestination(activeUnit);
}
}
}
});
add(gotoMenuItem);
hasAnItem = true;
addSeparator();
}
for (final Unit currentUnit : tile.getUnitList()) {
addUnit(currentUnit, !currentUnit.isUnderRepair(), false);
for (Unit unit : currentUnit.getUnitList()) {
addUnit(unit, true, true);
}
boolean hasGoods = false;
for (Goods goods: currentUnit.getGoodsList()) {
addGoods(goods, false, true);
hasGoods = true;
}
if (hasGoods) {
JMenuItem dumpItem = new JMenuItem(Messages.message("dumpCargo"));
dumpItem.setAction(new UnloadAction(freeColClient));
add(dumpItem);
}
}
if (tile.getUnitCount() > 0) {
addSeparator();
}
Settlement settlement = tile.getSettlement();
if (settlement != null) {
if (settlement.getOwner() == freeColClient.getMyPlayer()) {
addColony(((Colony) settlement));
} else if (settlement instanceof IndianSettlement) {
addIndianSettlement((IndianSettlement) settlement);
}
if (hasItem()) {
addSeparator();
}
}
addTile(tile);
if (FreeCol.isInDebugMode()
&& freeColClient.getFreeColServer() != null) {
addSeparator();
JMenu takeOwnership = new JMenu("Take ownership");
takeOwnership.setOpaque(false);
boolean notEmpty = false;
for (final Unit currentUnit : tile.getUnitList()) {
JMenuItem toMenuItem = new JMenuItem(currentUnit.toString());
toMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Player mp = (Player) freeColClient.getFreeColServer().getGame()
.getFreeColGameObject(freeColClient.getMyPlayer().getId());
currentUnit.setOwner(mp);
for (Unit unit : currentUnit.getUnitList()) {
unit.setOwner(mp);
}
}
});
takeOwnership.add(toMenuItem);
notEmpty = true;
if (currentUnit.isCarrier()) {
final AIUnit au = (AIUnit) freeColClient.getFreeColServer().getAIMain().getAIObject(currentUnit);
if (au.getMission() != null && au.getMission() instanceof TransportMission) {
JMenuItem menuItem = new JMenuItem("Transport list for: " + currentUnit.toString() +
" (" + currentUnit.hashCode() + ")");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
canvas.showInformationMessage(au.getMission().toString());
}
});
}
}
}
if (tile.getSettlement() != null) {
if (!notEmpty) {
takeOwnership.addSeparator();
}
JMenuItem toMenuItem = new JMenuItem(tile.getSettlement().toString());
toMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Player mp = (Player) freeColClient.getFreeColServer().getGame()
.getFreeColGameObject(freeColClient.getMyPlayer().getId());
tile.getSettlement().setOwner(mp);
}
});
takeOwnership.add(toMenuItem);
notEmpty = true;
}
if (notEmpty) {
add(takeOwnership);
hasAnItem = true;
}
}
}
|
@Override public int getNewLC(int lc, Module mod) {
return mod.evaluate(getOperand("FC"));
}
| @Override public int getNewLC(int lc, Module mod) {
return lc+mod.evaluate(getOperand("FC"));
}
|
public static void main(String[] args) throws IOException {
Locale locale = new Locale("en", "US");
Locale.setDefault(locale);
CommandLineParser parser = new PosixParser();
CommandLine commandLine;
try {
commandLine = parser.parse(options, args);
} catch (ParseException ex) {
usage();
return;
}
baksmaliOptions options = new baksmaliOptions();
boolean disassemble = true;
boolean doDump = false;
String dumpFileName = null;
boolean setBootClassPath = false;
String[] remainingArgs = commandLine.getArgs();
Option[] clOptions = commandLine.getOptions();
for (int i=0; i<clOptions.length; i++) {
Option option = clOptions[i];
String opt = option.getOpt();
switch (opt.charAt(0)) {
case 'v':
version();
return;
case '?':
while (++i < clOptions.length) {
if (clOptions[i].getOpt().charAt(0) == '?') {
usage(true);
return;
}
}
usage(false);
return;
case 'o':
options.outputDirectory = commandLine.getOptionValue("o");
break;
case 'p':
options.noParameterRegisters = true;
break;
case 'l':
options.useLocalsDirective = true;
break;
case 's':
options.useSequentialLabels = true;
break;
case 'b':
options.outputDebugInfo = false;
break;
case 'd':
options.bootClassPathDirs.add(option.getValue());
break;
case 'f':
options.addCodeOffsets = true;
break;
case 'r':
String[] values = commandLine.getOptionValues('r');
int registerInfo = 0;
if (values == null || values.length == 0) {
registerInfo = baksmaliOptions.ARGS | baksmaliOptions.DEST;
} else {
for (String value: values) {
if (value.equalsIgnoreCase("ALL")) {
registerInfo |= baksmaliOptions.ALL;
} else if (value.equalsIgnoreCase("ALLPRE")) {
registerInfo |= baksmaliOptions.ALLPRE;
} else if (value.equalsIgnoreCase("ALLPOST")) {
registerInfo |= baksmaliOptions.ALLPOST;
} else if (value.equalsIgnoreCase("ARGS")) {
registerInfo |= baksmaliOptions.ARGS;
} else if (value.equalsIgnoreCase("DEST")) {
registerInfo |= baksmaliOptions.DEST;
} else if (value.equalsIgnoreCase("MERGE")) {
registerInfo |= baksmaliOptions.MERGE;
} else if (value.equalsIgnoreCase("FULLMERGE")) {
registerInfo |= baksmaliOptions.FULLMERGE;
} else {
usage();
return;
}
}
if ((registerInfo & baksmaliOptions.FULLMERGE) != 0) {
registerInfo &= ~baksmaliOptions.MERGE;
}
}
options.registerInfo = registerInfo;
break;
case 'c':
String bcp = commandLine.getOptionValue("c");
if (bcp != null && bcp.charAt(0) == ':') {
options.addExtraClassPath(bcp);
} else {
setBootClassPath = true;
options.setBootClassPath(bcp);
}
break;
case 'x':
options.deodex = true;
break;
case 'm':
options.noAccessorComments = true;
break;
case 'a':
options.apiLevel = Integer.parseInt(commandLine.getOptionValue("a"));
break;
case 'j':
options.jobs = Integer.parseInt(commandLine.getOptionValue("j"));
break;
case 'N':
disassemble = false;
break;
case 'D':
doDump = true;
dumpFileName = commandLine.getOptionValue("D");
break;
case 'I':
options.ignoreErrors = true;
break;
case 'T':
options.inlineResolver = new CustomInlineMethodResolver(options.classPath, new File(commandLine.getOptionValue("T")));
break;
case 'R':
String rif = commandLine.getOptionValue("R");
options.setResourceIdFiles(rif);
break;
default:
assert false;
}
}
if (remainingArgs.length != 1) {
usage();
return;
}
if (options.jobs <= 0) {
options.jobs = Runtime.getRuntime().availableProcessors();
if (options.jobs > 6) {
options.jobs = 6;
}
}
if (options.apiLevel >= 17) {
options.checkPackagePrivateAccess = true;
}
String inputDexFileName = remainingArgs[0];
File dexFileFile = new File(inputDexFileName);
if (!dexFileFile.exists()) {
System.err.println("Can't find the file " + inputDexFileName);
System.exit(1);
}
DexBackedDexFile dexFile = DexFileFactory.loadDexFile(dexFileFile, options.apiLevel);
if (dexFile.isOdexFile()) {
if (!options.deodex) {
System.err.println("Warning: You are disassembling an odex file without deodexing it. You");
System.err.println("won't be able to re-assemble the results unless you deodex it with the -x");
System.err.println("option");
options.allowOdex = true;
}
} else {
options.deodex = false;
}
if (!setBootClassPath && (options.deodex || options.registerInfo != 0)) {
if (dexFile instanceof DexBackedOdexFile) {
options.bootClassPathEntries = ((DexBackedOdexFile)dexFile).getDependencies();
} else {
options.bootClassPathEntries = getDefaultBootClassPathForApi(options.apiLevel);
}
}
if (options.inlineResolver == null && dexFile instanceof DexBackedOdexFile) {
options.inlineResolver =
InlineMethodResolver.createInlineMethodResolver(((DexBackedOdexFile)dexFile).getOdexVersion());
}
boolean errorOccurred = false;
if (disassemble) {
errorOccurred = !baksmali.disassembleDexFile(dexFile, options);
}
if (doDump) {
if (dumpFileName == null) {
dumpFileName = commandLine.getOptionValue(inputDexFileName + ".dump");
}
dump.dump(dexFile, dumpFileName, options.apiLevel);
}
if (errorOccurred) {
System.exit(1);
}
}
| public static void main(String[] args) throws IOException {
Locale locale = new Locale("en", "US");
Locale.setDefault(locale);
CommandLineParser parser = new PosixParser();
CommandLine commandLine;
try {
commandLine = parser.parse(options, args);
} catch (ParseException ex) {
usage();
return;
}
baksmaliOptions options = new baksmaliOptions();
boolean disassemble = true;
boolean doDump = false;
String dumpFileName = null;
boolean setBootClassPath = false;
String[] remainingArgs = commandLine.getArgs();
Option[] clOptions = commandLine.getOptions();
for (int i=0; i<clOptions.length; i++) {
Option option = clOptions[i];
String opt = option.getOpt();
switch (opt.charAt(0)) {
case 'v':
version();
return;
case '?':
while (++i < clOptions.length) {
if (clOptions[i].getOpt().charAt(0) == '?') {
usage(true);
return;
}
}
usage(false);
return;
case 'o':
options.outputDirectory = commandLine.getOptionValue("o");
break;
case 'p':
options.noParameterRegisters = true;
break;
case 'l':
options.useLocalsDirective = true;
break;
case 's':
options.useSequentialLabels = true;
break;
case 'b':
options.outputDebugInfo = false;
break;
case 'd':
options.bootClassPathDirs.add(option.getValue());
break;
case 'f':
options.addCodeOffsets = true;
break;
case 'r':
String[] values = commandLine.getOptionValues('r');
int registerInfo = 0;
if (values == null || values.length == 0) {
registerInfo = baksmaliOptions.ARGS | baksmaliOptions.DEST;
} else {
for (String value: values) {
if (value.equalsIgnoreCase("ALL")) {
registerInfo |= baksmaliOptions.ALL;
} else if (value.equalsIgnoreCase("ALLPRE")) {
registerInfo |= baksmaliOptions.ALLPRE;
} else if (value.equalsIgnoreCase("ALLPOST")) {
registerInfo |= baksmaliOptions.ALLPOST;
} else if (value.equalsIgnoreCase("ARGS")) {
registerInfo |= baksmaliOptions.ARGS;
} else if (value.equalsIgnoreCase("DEST")) {
registerInfo |= baksmaliOptions.DEST;
} else if (value.equalsIgnoreCase("MERGE")) {
registerInfo |= baksmaliOptions.MERGE;
} else if (value.equalsIgnoreCase("FULLMERGE")) {
registerInfo |= baksmaliOptions.FULLMERGE;
} else {
usage();
return;
}
}
if ((registerInfo & baksmaliOptions.FULLMERGE) != 0) {
registerInfo &= ~baksmaliOptions.MERGE;
}
}
options.registerInfo = registerInfo;
break;
case 'c':
String bcp = commandLine.getOptionValue("c");
if (bcp != null && bcp.charAt(0) == ':') {
options.addExtraClassPath(bcp);
} else {
setBootClassPath = true;
options.setBootClassPath(bcp);
}
break;
case 'x':
options.deodex = true;
break;
case 'm':
options.noAccessorComments = true;
break;
case 'a':
options.apiLevel = Integer.parseInt(commandLine.getOptionValue("a"));
break;
case 'j':
options.jobs = Integer.parseInt(commandLine.getOptionValue("j"));
break;
case 'i':
String rif = commandLine.getOptionValue("i");
options.setResourceIdFiles(rif);
break;
case 'N':
disassemble = false;
break;
case 'D':
doDump = true;
dumpFileName = commandLine.getOptionValue("D");
break;
case 'I':
options.ignoreErrors = true;
break;
case 'T':
options.inlineResolver = new CustomInlineMethodResolver(options.classPath, new File(commandLine.getOptionValue("T")));
break;
default:
assert false;
}
}
if (remainingArgs.length != 1) {
usage();
return;
}
if (options.jobs <= 0) {
options.jobs = Runtime.getRuntime().availableProcessors();
if (options.jobs > 6) {
options.jobs = 6;
}
}
if (options.apiLevel >= 17) {
options.checkPackagePrivateAccess = true;
}
String inputDexFileName = remainingArgs[0];
File dexFileFile = new File(inputDexFileName);
if (!dexFileFile.exists()) {
System.err.println("Can't find the file " + inputDexFileName);
System.exit(1);
}
DexBackedDexFile dexFile = DexFileFactory.loadDexFile(dexFileFile, options.apiLevel);
if (dexFile.isOdexFile()) {
if (!options.deodex) {
System.err.println("Warning: You are disassembling an odex file without deodexing it. You");
System.err.println("won't be able to re-assemble the results unless you deodex it with the -x");
System.err.println("option");
options.allowOdex = true;
}
} else {
options.deodex = false;
}
if (!setBootClassPath && (options.deodex || options.registerInfo != 0)) {
if (dexFile instanceof DexBackedOdexFile) {
options.bootClassPathEntries = ((DexBackedOdexFile)dexFile).getDependencies();
} else {
options.bootClassPathEntries = getDefaultBootClassPathForApi(options.apiLevel);
}
}
if (options.inlineResolver == null && dexFile instanceof DexBackedOdexFile) {
options.inlineResolver =
InlineMethodResolver.createInlineMethodResolver(((DexBackedOdexFile)dexFile).getOdexVersion());
}
boolean errorOccurred = false;
if (disassemble) {
errorOccurred = !baksmali.disassembleDexFile(dexFile, options);
}
if (doDump) {
if (dumpFileName == null) {
dumpFileName = commandLine.getOptionValue(inputDexFileName + ".dump");
}
dump.dump(dexFile, dumpFileName, options.apiLevel);
}
if (errorOccurred) {
System.exit(1);
}
}
|
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON);
final DataSource source = mysqlDataSource;
int count = 1;
try
{
count = Integer.parseInt(req.getParameter("queries"));
if (count > 500)
{
count = 500;
}
if (count < 1)
{
count = 1;
}
}
catch (NumberFormatException nfexc)
{
}
final World[] worlds = new World[count];
final Random random = ThreadLocalRandom.current();
try (Connection conn = source.getConnection())
{
try (PreparedStatement statement = conn.prepareStatement(DB_QUERY,
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY))
{
for (int i = 0; i < count; i++)
{
final int id = random.nextInt(DB_ROWS) + 1;
statement.setInt(1, id);
try (ResultSet results = statement.executeQuery())
{
if (results.next())
{
worlds[i] = new World(id, results.getInt("randomNumber"));
}
}
}
}
}
catch (SQLException sqlex)
{
System.err.println("SQL Exception: " + sqlex);
}
try
{
Common.MAPPER.writeValue(res.getOutputStream(), worlds);
}
catch (IOException ioe)
{
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON);
final DataSource source = mysqlDataSource;
int count = 1;
try
{
count = Integer.parseInt(req.getParameter("queries"));
if (count > 500)
{
count = 500;
}
if (count < 1)
{
count = 1;
}
}
catch (NumberFormatException nfexc)
{
}
final World[] worlds = new World[count];
final Random random = ThreadLocalRandom.current();
try (Connection conn = source.getConnection())
{
try (PreparedStatement statement = conn.prepareStatement(DB_QUERY,
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY))
{
for (int i = 0; i < count; i++)
{
final int id = random.nextInt(DB_ROWS) + 1;
statement.setInt(1, id);
try (ResultSet results = statement.executeQuery())
{
if (results.next())
{
worlds[i] = new World(id, results.getInt("randomNumber"));
}
}
}
}
}
catch (SQLException sqlex)
{
System.err.println("SQL Exception: " + sqlex);
}
try
{
if (count == 1)
{
Common.MAPPER.writeValue(res.getOutputStream(), worlds[0]);
}
else
{
Common.MAPPER.writeValue(res.getOutputStream(), worlds);
}
}
catch (IOException ioe)
{
}
}
|
protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
WebdavNsIntf intf = null;
boolean serverError = false;
try {
String debugStr = getInitParameter("debug");
if (debugStr != null) {
debug = !"0".equals(debugStr);
}
if (debug) {
debugMsg("entry: " + req.getMethod());
dumpRequest(req);
}
tryWait(req, true);
intf = getNsIntf(req);
if (req.getCharacterEncoding() == null) {
req.setCharacterEncoding("UTF-8");
if (debug) {
debugMsg("No charset specified in request; forced to UTF-8");
}
}
if (debug && dumpContent) {
resp = new CharArrayWrappedResponse(resp,
getLogger(), debug);
}
String methodName = req.getMethod();
MethodBase method = intf.getMethod(methodName);
if (method == null) {
logIt("No method for '" + methodName + "'");
} else {
method.doMethod(req, resp);
}
} catch (WebdavForbidden wdf) {
sendError(intf, wdf, resp);
} catch (Throwable t) {
serverError = handleException(intf, t, resp, serverError);
} finally {
if (intf != null) {
try {
intf.close();
} catch (Throwable t) {
serverError = handleException(intf, t, resp, serverError);
}
}
try {
tryWait(req, false);
} catch (Throwable t) {}
if (debug && dumpContent) {
CharArrayWrappedResponse wresp = (CharArrayWrappedResponse)resp;
if (wresp.getUsedOutputStream()) {
debugMsg("------------------------ response written to output stream -------------------");
} else {
String str = wresp.toString();
debugMsg("------------------------ Dump of response -------------------");
debugMsg(str);
debugMsg("---------------------- End dump of response -----------------");
byte[] bs = str.getBytes();
resp = (HttpServletResponse)wresp.getResponse();
debugMsg("contentLength=" + bs.length);
resp.setContentLength(bs.length);
resp.getOutputStream().write(bs);
}
}
try {
HttpSession sess = req.getSession(false);
if (sess != null) {
sess.invalidate();
}
} catch (Throwable t) {}
}
}
| protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
WebdavNsIntf intf = null;
boolean serverError = false;
try {
String debugStr = getInitParameter("debug");
if (debugStr != null) {
debug = !"0".equals(debugStr);
}
if (debug) {
debugMsg("entry: " + req.getMethod());
dumpRequest(req);
}
tryWait(req, true);
intf = getNsIntf(req);
if (req.getCharacterEncoding() == null) {
req.setCharacterEncoding("UTF-8");
if (debug) {
debugMsg("No charset specified in request; forced to UTF-8");
}
}
if (debug && dumpContent) {
resp = new CharArrayWrappedResponse(resp,
getLogger(), debug);
}
String methodName = req.getMethod();
MethodBase method = intf.getMethod(methodName);
if (method == null) {
logIt("No method for '" + methodName + "'");
} else {
method.doMethod(req, resp);
}
} catch (WebdavForbidden wdf) {
sendError(intf, wdf, resp);
} catch (Throwable t) {
serverError = handleException(intf, t, resp, serverError);
} finally {
if (intf != null) {
try {
intf.close();
} catch (Throwable t) {
serverError = handleException(intf, t, resp, serverError);
}
}
try {
tryWait(req, false);
} catch (Throwable t) {}
if (debug && dumpContent &&
(resp instanceof CharArrayWrappedResponse)) {
CharArrayWrappedResponse wresp = (CharArrayWrappedResponse)resp;
if (wresp.getUsedOutputStream()) {
debugMsg("------------------------ response written to output stream -------------------");
} else {
String str = wresp.toString();
debugMsg("------------------------ Dump of response -------------------");
debugMsg(str);
debugMsg("---------------------- End dump of response -----------------");
byte[] bs = str.getBytes();
resp = (HttpServletResponse)wresp.getResponse();
debugMsg("contentLength=" + bs.length);
resp.setContentLength(bs.length);
resp.getOutputStream().write(bs);
}
}
try {
HttpSession sess = req.getSession(false);
if (sess != null) {
sess.invalidate();
}
} catch (Throwable t) {}
}
}
|
public Status getStatus(Method method, Variant variant) {
Status result = null;
if (getMatch() != null && getMatch().size() != 0) {
boolean matched = false;
boolean failed = false;
if (variant != null) {
if (variant.getTag() != null) {
Tag tag;
for (Iterator<Tag> iter = getMatch().iterator(); !matched
&& iter.hasNext();) {
tag = iter.next();
matched = tag.equals(variant.getTag(), false);
}
}
} else {
failed = getMatch().get(0).equals(Tag.ALL);
}
failed = failed || !matched;
if (failed) {
result = Status.CLIENT_ERROR_PRECONDITION_FAILED;
}
}
if (result == null && getNoneMatch() != null
&& getNoneMatch().size() != 0) {
boolean matched = false;
if (variant != null) {
if (variant.getTag() != null) {
Tag tag;
for (Iterator<Tag> iter = getNoneMatch().iterator(); !matched
&& iter.hasNext();) {
tag = iter.next();
matched = tag.equals(variant.getTag(), (Method.GET
.equals(method) || Method.HEAD.equals(method)));
}
if (!matched) {
Date modifiedSince = getModifiedSince();
matched = ((modifiedSince == null)
|| (variant.getModificationDate() == null) || DateUtils
.after(modifiedSince, variant
.getModificationDate()));
}
}
} else {
matched = getNoneMatch().get(0).equals(Tag.ALL);
}
if (matched) {
if (Method.GET.equals(method) || Method.HEAD.equals(method)) {
result = Status.REDIRECTION_NOT_MODIFIED;
} else {
result = Status.CLIENT_ERROR_PRECONDITION_FAILED;
}
}
}
if (result == null && getModifiedSince() != null) {
Date modifiedSince = getModifiedSince();
boolean isModifiedSince = ((modifiedSince == null)
|| (variant.getModificationDate() == null) || DateUtils
.after(modifiedSince, variant.getModificationDate()));
if (!isModifiedSince) {
result = Status.REDIRECTION_NOT_MODIFIED;
}
}
if (result == null && getUnmodifiedSince() != null) {
Date unModifiedSince = getUnmodifiedSince();
boolean isUnModifiedSince = ((unModifiedSince == null)
|| (variant.getModificationDate() == null) || DateUtils
.after(variant.getModificationDate(), unModifiedSince));
if (!isUnModifiedSince) {
result = Status.CLIENT_ERROR_PRECONDITION_FAILED;
}
}
return result;
}
| public Status getStatus(Method method, Variant variant) {
Status result = null;
if (getMatch() != null && getMatch().size() != 0) {
boolean matched = false;
boolean failed = false;
if (variant != null) {
if (variant.getTag() != null) {
Tag tag;
for (Iterator<Tag> iter = getMatch().iterator(); !matched
&& iter.hasNext();) {
tag = iter.next();
matched = tag.equals(variant.getTag(), false);
}
}
} else {
failed = getMatch().get(0).equals(Tag.ALL);
}
failed = failed || !matched;
if (failed) {
result = Status.CLIENT_ERROR_PRECONDITION_FAILED;
}
}
if (result == null && getNoneMatch() != null
&& getNoneMatch().size() != 0) {
boolean matched = false;
if (variant != null) {
if (variant.getTag() != null) {
Tag tag;
for (Iterator<Tag> iter = getNoneMatch().iterator(); !matched
&& iter.hasNext();) {
tag = iter.next();
matched = tag.equals(variant.getTag(), (Method.GET
.equals(method) || Method.HEAD.equals(method)));
}
if (!matched) {
Date modifiedSince = getModifiedSince();
matched = ((modifiedSince == null)
|| (variant.getModificationDate() == null) || DateUtils
.after(modifiedSince, variant
.getModificationDate()));
}
}
} else {
matched = getNoneMatch().get(0).equals(Tag.ALL);
}
if (matched) {
if (Method.GET.equals(method) || Method.HEAD.equals(method)) {
result = Status.REDIRECTION_NOT_MODIFIED;
} else {
result = Status.CLIENT_ERROR_PRECONDITION_FAILED;
}
}
}
if (result == null && getModifiedSince() != null) {
if (variant != null) {
Date modifiedSince = getModifiedSince();
boolean isModifiedSince = ((modifiedSince == null)
|| (variant.getModificationDate() == null) || DateUtils
.after(modifiedSince, variant.getModificationDate()));
if (!isModifiedSince) {
result = Status.REDIRECTION_NOT_MODIFIED;
}
}
}
if (result == null && getUnmodifiedSince() != null) {
if (variant != null) {
Date unModifiedSince = getUnmodifiedSince();
boolean isUnModifiedSince = ((unModifiedSince == null)
|| (variant.getModificationDate() == null) || DateUtils
.after(variant.getModificationDate(), unModifiedSince));
if (!isUnModifiedSince) {
result = Status.CLIENT_ERROR_PRECONDITION_FAILED;
}
}
}
return result;
}
|
public void bind(final JClass jClass, final XMLBindingComponent component,
final String mode) {
Annotated annotated = component.getAnnotated();
String xPath = XPathHelper.getSchemaLocation(annotated, true);
String localXPath = getLocalXPath(xPath);
String untypedXPath = xPath;
String localName = getLocalName(xPath);
String typedLocalName = localName;
if (annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
String typexPath = XPathHelper.getSchemaLocation(element.getType());
xPath += "[" + typexPath + "]";
typedLocalName += "[" + typexPath + "]";
} else if (annotated instanceof Group) {
Group group = (Group) annotated;
if (group.getOrder().getType() == Order.CHOICE
&& !_globalElements.contains("/" + localXPath)) {
xPath += "/#choice";
}
}
ExtendedBinding binding = component.getBinding();
if (binding != null) {
if (binding.existsExclusion(typedLocalName)) {
Exclude exclusion = binding.getExclusion(typedLocalName);
if (exclusion.getClassName() != null) {
LOG.info("Dealing with exclusion for local element " + xPath
+ " as per binding file.");
jClass.changeLocalName(exclusion.getClassName());
}
return;
}
if (binding.existsForce(localName)) {
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
LOG.info("Changing class name for local element " + xPath
+ " as per binding file (force).");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
return;
}
}
String jClassLocalName = jClass.getLocalName();
String expectedClassNameDerivedFromXPath = JavaNaming.toJavaClassName(localName);
if (!jClassLocalName.equals(expectedClassNameDerivedFromXPath)) {
if (component.createGroupItem()) {
xPath += "/#item";
}
_xpathToJClass.put(xPath, jClass);
return;
}
if (mode.equals("field")) {
if (annotated instanceof ModelGroup) {
ModelGroup group = (ModelGroup) annotated;
final boolean isReference = group.isReference();
if (isReference) {
return;
}
}
if (annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
final boolean isReference = element.isReference();
if (isReference) {
ElementDecl referredElement = element.getReference();
Enumeration possibleSubstitutes = referredElement
.getSubstitutionGroupMembers();
if (possibleSubstitutes.hasMoreElements()) {
XMLType referredType = referredElement.getType();
String xPathType = XPathHelper.getSchemaLocation(referredType);
JClass typeJClass = (JClass) _xpathToJClass
.get(xPathType);
if (typeJClass != null) {
jClass.changeLocalName(typeJClass.getLocalName());
} else {
XMLBindingComponent temp = component;
temp.setView(referredType);
jClass.changeLocalName(temp.getJavaClassName());
}
}
return;
}
}
}
final boolean alreadyProcessed = _xpathToJClass.containsKey(xPath);
if (alreadyProcessed) {
JClass jClassAlreadyProcessed = (JClass) _xpathToJClass.get(xPath);
jClass.changeLocalName(jClassAlreadyProcessed.getLocalName());
return;
}
_xpathToJClass.put(xPath, jClass);
LOG.debug("Binding JClass[" + jClass.getName() + "] for XML schema structure " + xPath);
final boolean isGlobalElement = _globalElements.contains(untypedXPath);
if (isGlobalElement) {
return;
}
if (mode.equals("field") && annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
final boolean isReference = element.isReference();
if (isReference) {
ElementDecl referredElement = element.getReference();
Enumeration possibleSubstitutes = referredElement
.getSubstitutionGroupMembers();
if (possibleSubstitutes.hasMoreElements()) {
String typeXPath = XPathHelper
.getSchemaLocation(referredElement);
JClass referredJClass = (JClass) _xpathToJClass
.get(typeXPath + "_class");
jClass.changeLocalName(referredJClass.getSuperClass()
.getLocalName());
}
return;
}
}
final boolean conflictExistsWithGlobalElement = _globalElements
.contains("/" + localXPath);
if (conflictExistsWithGlobalElement) {
LOG.info("Resolving conflict for local element " + xPath + " against global element.");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
return;
}
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
if (localNamesList == null) {
String typedJClassName = (String) _typedLocalNames.get(typedLocalName);
if (typedJClassName == null) {
_typedLocalNames.put(typedLocalName, jClass.getName());
}
} else {
LOG.info("Resolving conflict for local element " + xPath
+ " against another local element of the same name.");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
}
}
| public void bind(final JClass jClass, final XMLBindingComponent component,
final String mode) {
Annotated annotated = component.getAnnotated();
String xPath = XPathHelper.getSchemaLocation(annotated, true);
String localXPath = getLocalXPath(xPath);
String untypedXPath = xPath;
String localName = getLocalName(xPath);
String typedLocalName = localName;
if (annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
String typexPath = XPathHelper.getSchemaLocation(element.getType());
xPath += "[" + typexPath + "]";
typedLocalName += "[" + typexPath + "]";
} else if (annotated instanceof Group) {
Group group = (Group) annotated;
if (group.getOrder().getType() == Order.CHOICE
&& !_globalElements.contains("/" + localXPath)) {
xPath += "/#choice";
}
}
ExtendedBinding binding = component.getBinding();
if (binding != null) {
if (binding.existsExclusion(typedLocalName)) {
Exclude exclusion = binding.getExclusion(typedLocalName);
if (exclusion.getClassName() != null) {
LOG.info("Dealing with exclusion for local element " + xPath
+ " as per binding file.");
jClass.changeLocalName(exclusion.getClassName());
}
return;
}
if (binding.existsForce(localName)) {
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
LOG.info("Changing class name for local element " + xPath
+ " as per binding file (force).");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
return;
}
}
String jClassLocalName = jClass.getLocalName();
String expectedClassNameDerivedFromXPath = JavaNaming.toJavaClassName(localName);
if (!jClassLocalName.equals(expectedClassNameDerivedFromXPath)) {
if (component.createGroupItem()) {
xPath += "/#item";
}
_xpathToJClass.put(xPath, jClass);
return;
}
if (mode.equals("field")) {
if (annotated instanceof ModelGroup) {
ModelGroup group = (ModelGroup) annotated;
final boolean isReference = group.isReference();
if (isReference) {
return;
}
}
if (annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
final boolean isReference = element.isReference();
if (isReference) {
ElementDecl referredElement = element.getReference();
Enumeration possibleSubstitutes = referredElement
.getSubstitutionGroupMembers();
if (possibleSubstitutes.hasMoreElements()) {
XMLType referredType = referredElement.getType();
String xPathType = XPathHelper.getSchemaLocation(referredType);
JClass typeJClass = (JClass) _xpathToJClass
.get(xPathType);
if (typeJClass != null) {
jClass.changeLocalName(typeJClass.getLocalName());
} else {
XMLBindingComponent temp = component;
temp.setView(referredType);
jClass.changeLocalName(temp.getJavaClassName());
component.setView(annotated);
}
}
return;
}
}
}
final boolean alreadyProcessed = _xpathToJClass.containsKey(xPath);
if (alreadyProcessed) {
JClass jClassAlreadyProcessed = (JClass) _xpathToJClass.get(xPath);
jClass.changeLocalName(jClassAlreadyProcessed.getLocalName());
return;
}
_xpathToJClass.put(xPath, jClass);
LOG.debug("Binding JClass[" + jClass.getName() + "] for XML schema structure " + xPath);
final boolean isGlobalElement = _globalElements.contains(untypedXPath);
if (isGlobalElement) {
return;
}
if (mode.equals("field") && annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
final boolean isReference = element.isReference();
if (isReference) {
ElementDecl referredElement = element.getReference();
Enumeration possibleSubstitutes = referredElement
.getSubstitutionGroupMembers();
if (possibleSubstitutes.hasMoreElements()) {
String typeXPath = XPathHelper
.getSchemaLocation(referredElement);
JClass referredJClass = (JClass) _xpathToJClass
.get(typeXPath + "_class");
jClass.changeLocalName(referredJClass.getSuperClass()
.getLocalName());
}
return;
}
}
final boolean conflictExistsWithGlobalElement = _globalElements
.contains("/" + localXPath);
if (conflictExistsWithGlobalElement) {
LOG.info("Resolving conflict for local element " + xPath + " against global element.");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
return;
}
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
if (localNamesList == null) {
String typedJClassName = (String) _typedLocalNames.get(typedLocalName);
if (typedJClassName == null) {
_typedLocalNames.put(typedLocalName, jClass.getName());
}
} else {
LOG.info("Resolving conflict for local element " + xPath
+ " against another local element of the same name.");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
}
}
|
public Domain generateDomain(DatabaseMeta databaseMeta, List<LogicalRelationship> joinTemplates) {
Domain domain = null;
try {
String locale = LocalizedString.DEFAULT_LOCALE;
this.generator.setLocale(locale);
this.generator.setDatabaseMeta(databaseMeta);
this.generator.setModelName(datasourceName);
List<SchemaTable> schemas = new ArrayList<SchemaTable>();
for (LogicalRelationship joinTemplate : joinTemplates) {
schemas.add(new SchemaTable("", joinTemplate.getFromTable().getName(locale)));
schemas.add(new SchemaTable("", joinTemplate.getToTable().getName(locale)));
}
SchemaTable tableNames[] = new SchemaTable[schemas.size()];
tableNames = schemas.toArray(tableNames);
this.generator.setTableNames(tableNames);
domain = this.generator.generateDomain();
domain.setId(datasourceName);
ModelerWorkspaceHelper helper = new ModelerWorkspaceHelper(locale);
ModelerWorkspace workspace = new ModelerWorkspace(helper);
workspace.setModelName(datasourceName);
workspace.setDomain(domain);
LogicalModel logicalModel = domain.getLogicalModels().get(0);
logicalModel.setName(new LocalizedString(locale, datasourceName));
logicalModel.setDescription(new LocalizedString(locale, "This is the data model for "
+ datasourceName));
LogicalTable businessTable = logicalModel.getLogicalTables().get(0);
businessTable.setName(new LocalizedString(locale, datasourceName));
for (LogicalRelationship joinTemplate : joinTemplates) {
String lTable = joinTemplate.getFromTable().getName(locale);
String rTable = joinTemplate.getToTable().getName(locale);
LogicalTable fromTable = null;
LogicalColumn fromColumn = null;
LogicalTable toTable = null;
LogicalColumn toColumn = null;
for (LogicalTable logicalTable : logicalModel.getLogicalTables()) {
if (logicalTable.getName(locale).equals(lTable)) {
fromTable = logicalTable;
for (LogicalColumn logicalColumn : fromTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getFromColumn().getName(locale))) {
fromColumn = logicalColumn;
}
}
}
if (logicalTable.getName(locale).equals(rTable)) {
toTable = logicalTable;
for (LogicalColumn logicalColumn : toTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getToColumn().getName(locale))) {
toColumn = logicalColumn;
}
}
}
}
LogicalRelationship logicalRelationship = new LogicalRelationship();
logicalRelationship.setRelationshipType(RelationshipType._1_1);
logicalRelationship.setFromTable(fromTable);
logicalRelationship.setFromColumn(fromColumn);
logicalRelationship.setToTable(toTable);
logicalRelationship.setToColumn(toColumn);
logicalModel.addLogicalRelationship(logicalRelationship);
}
helper.autoModelMultiTableRelational(workspace);
workspace.setModelName(datasourceName);
helper.populateDomain(workspace);
} catch (PentahoMetadataException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (ModelerException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
}
return domain;
}
| public Domain generateDomain(DatabaseMeta databaseMeta, List<LogicalRelationship> joinTemplates) {
Domain domain = null;
try {
String locale = LocalizedString.DEFAULT_LOCALE;
this.generator.setLocale(locale);
this.generator.setDatabaseMeta(databaseMeta);
this.generator.setModelName(datasourceName);
List<SchemaTable> schemas = new ArrayList<SchemaTable>();
for (LogicalRelationship joinTemplate : joinTemplates) {
schemas.add(new SchemaTable("", joinTemplate.getFromTable().getName(locale)));
schemas.add(new SchemaTable("", joinTemplate.getToTable().getName(locale)));
}
SchemaTable tableNames[] = new SchemaTable[schemas.size()];
tableNames = schemas.toArray(tableNames);
this.generator.setTableNames(tableNames);
domain = this.generator.generateDomain();
domain.setId(datasourceName);
ModelerWorkspaceHelper helper = new ModelerWorkspaceHelper(locale);
ModelerWorkspace workspace = new ModelerWorkspace(helper);
workspace.setModelName(datasourceName);
workspace.setDomain(domain);
LogicalModel logicalModel = domain.getLogicalModels().get(0);
logicalModel.setName(new LocalizedString(locale, datasourceName));
logicalModel.setDescription(new LocalizedString(locale, "This is the data model for "
+ datasourceName));
for(LogicalTable businessTable : logicalModel.getLogicalTables()) {
businessTable.setName(new LocalizedString(locale, businessTable.getPhysicalTable().getName(locale)));
}
for (LogicalRelationship joinTemplate : joinTemplates) {
String lTable = joinTemplate.getFromTable().getName(locale);
String rTable = joinTemplate.getToTable().getName(locale);
LogicalTable fromTable = null;
LogicalColumn fromColumn = null;
LogicalTable toTable = null;
LogicalColumn toColumn = null;
for (LogicalTable logicalTable : logicalModel.getLogicalTables()) {
if (logicalTable.getName(locale).equals(lTable)) {
fromTable = logicalTable;
for (LogicalColumn logicalColumn : fromTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getFromColumn().getName(locale))) {
fromColumn = logicalColumn;
}
}
}
if (logicalTable.getName(locale).equals(rTable)) {
toTable = logicalTable;
for (LogicalColumn logicalColumn : toTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getToColumn().getName(locale))) {
toColumn = logicalColumn;
}
}
}
}
LogicalRelationship logicalRelationship = new LogicalRelationship();
logicalRelationship.setRelationshipType(RelationshipType._1_1);
logicalRelationship.setFromTable(fromTable);
logicalRelationship.setFromColumn(fromColumn);
logicalRelationship.setToTable(toTable);
logicalRelationship.setToColumn(toColumn);
logicalModel.addLogicalRelationship(logicalRelationship);
}
helper.autoModelMultiTableRelational(workspace);
workspace.setModelName(datasourceName);
helper.populateDomain(workspace);
} catch (PentahoMetadataException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (ModelerException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
}
return domain;
}
|
public void actionPerformed(ActionEvent e) {
Doc d = actionContext.get(ActionContextKeys.ACTIVE_DOC);
if (! d.isBackedByFile()) {
fileSaveAsAction.actionPerformed(e);
} else {
d.save();
}
}
| public void actionPerformed(ActionEvent e) {
Doc d = actionContext.get(ActionContextKeys.ACTIVE_DOC);
if (! d.isBackedByFile()) {
fileSaveAsAction.setActionContext(actionContext);
fileSaveAsAction.actionPerformed(e);
} else {
d.save();
}
}
|
public void run() {
if (logger == null) {
logger = WaarpInternalLoggerFactory.getLogger(RequestTransfer.class);
}
DbTaskRunner runner = null;
try {
runner = new DbTaskRunner(DbConstant.admin.session, null, null,
specialId, requester, requested);
logger.info("Found previous Runner: "+runner.toString());
} catch (WaarpDatabaseException e) {
R66Future futureInfo = new R66Future(true);
RequestInformation requestInformation = new RequestInformation(futureInfo, srequested, null, null, (byte) -1, specialId, true, networkTransaction);
requestInformation.run();
futureInfo.awaitUninterruptibly();
if (futureInfo.isSuccess()) {
R66Result r66result = futureInfo.getResult();
ValidPacket info = (ValidPacket) r66result.other;
String xml = info.getSheader();
Document document;
try {
document = DocumentHelper.parseText(xml);
} catch (DocumentException e1) {
logger.error("Cannot find the transfer");
future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e1), null, true,
ErrorCode.Internal, null));
future.setFailure(e);
return;
}
try {
runner = DbTaskRunner.fromXml(DbConstant.admin.session, document.getRootElement(), true);
logger.info("Get Runner from remote: "+runner.toString());
if (runner.getSpecialId() == DbConstant.ILLEGALVALUE) {
logger.error("Cannot find the transfer");
future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true,
ErrorCode.Internal, null));
future.setFailure(e);
return;
}
} catch (OpenR66ProtocolBusinessException e1) {
logger.error("Cannot find the transfer");
future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e1), null, true,
ErrorCode.Internal, null));
future.setFailure(e);
return;
}
} else {
logger.error("Cannot find the transfer");
future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true,
ErrorCode.Internal, null));
future.setFailure(e);
return;
}
}
if (cancel || stop || restart) {
if (cancel) {
if (runner.isAllDone()) {
setDone(runner);
logger.info("Transfer already finished: " + runner.toString());
future.setResult(new R66Result(null, true, ErrorCode.TransferOk, runner));
future.getResult().runner = runner;
future.setSuccess();
return;
} else {
ErrorCode code = sendValid(runner, LocalPacketFactory.CANCELPACKET);
switch (code) {
case CompleteOk:
logger.info("Transfer cancel requested and done: {}",
runner);
break;
case TransferOk:
logger.info("Transfer cancel requested but already finished: {}",
runner);
break;
default:
logger.info("Transfer cancel requested but internal error: {}",
runner);
break;
}
}
} else if (stop) {
ErrorCode code = sendValid(runner, LocalPacketFactory.STOPPACKET);
switch (code) {
case CompleteOk:
logger.info("Transfer stop requested and done: {}", runner);
break;
case TransferOk:
logger.info("Transfer stop requested but already finished: {}",
runner);
break;
default:
logger.info("Transfer stop requested but internal error: {}",
runner);
break;
}
} else if (restart) {
ErrorCode code = sendValid(runner, LocalPacketFactory.VALIDPACKET);
switch (code) {
case QueryStillRunning:
logger.info(
"Transfer restart requested but already active and running: {}",
runner);
break;
case Running:
logger.info("Transfer restart requested but already running: {}",
runner);
break;
case PreProcessingOk:
logger.info("Transfer restart requested and restarted: {}",
runner);
break;
case CompleteOk:
logger.info("Transfer restart requested but already finished: {}",
runner);
break;
case RemoteError:
logger.info("Transfer restart requested but remote error: {}",
runner);
break;
case PassThroughMode:
logger.info("Transfer not restarted since it is in PassThrough mode: {}",
runner);
break;
default:
logger.info("Transfer restart requested but internal error: {}",
runner);
break;
}
}
} else {
logger.info("Transfer information:\n " + runner.toShortString());
future.setResult(new R66Result(null, true, runner.getErrorInfo(), runner));
future.setSuccess();
}
}
| public void run() {
if (logger == null) {
logger = WaarpInternalLoggerFactory.getLogger(RequestTransfer.class);
}
DbTaskRunner runner = null;
try {
runner = new DbTaskRunner(DbConstant.admin.session, null, null,
specialId, requester, requested);
logger.info("Found previous Runner: "+runner.toString());
} catch (WaarpDatabaseException e) {
R66Future futureInfo = new R66Future(true);
RequestInformation requestInformation = new RequestInformation(futureInfo, srequested, null, null, (byte) -1, specialId, true, networkTransaction);
requestInformation.run();
futureInfo.awaitUninterruptibly();
if (futureInfo.isSuccess()) {
R66Result r66result = futureInfo.getResult();
ValidPacket info = (ValidPacket) r66result.other;
String xml = info.getSheader();
Document document;
try {
document = DocumentHelper.parseText(xml);
} catch (DocumentException e1) {
logger.error("Cannot find the transfer");
future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e1), null, true,
ErrorCode.Internal, null));
future.setFailure(e);
return;
}
try {
runner = DbTaskRunner.fromXml(DbConstant.admin.session, document.getRootElement(), true);
logger.info("Get Runner from remote: "+runner.toString());
if (runner.getSpecialId() == DbConstant.ILLEGALVALUE || ! runner.isSender()) {
logger.error("Cannot find the transfer");
future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true,
ErrorCode.Internal, null));
future.setFailure(e);
return;
}
if (runner.isAllDone()) {
logger.error("Transfer already finished");
future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true,
ErrorCode.Internal, null));
future.setFailure(e);
return;
}
} catch (OpenR66ProtocolBusinessException e1) {
logger.error("Cannot find the transfer");
future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e1), null, true,
ErrorCode.Internal, null));
future.setFailure(e);
return;
}
} else {
logger.error("Cannot find the transfer");
future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true,
ErrorCode.Internal, null));
future.setFailure(e);
return;
}
}
if (cancel || stop || restart) {
if (cancel) {
if (runner.isAllDone()) {
setDone(runner);
logger.info("Transfer already finished: " + runner.toString());
future.setResult(new R66Result(null, true, ErrorCode.TransferOk, runner));
future.getResult().runner = runner;
future.setSuccess();
return;
} else {
ErrorCode code = sendValid(runner, LocalPacketFactory.CANCELPACKET);
switch (code) {
case CompleteOk:
logger.info("Transfer cancel requested and done: {}",
runner);
break;
case TransferOk:
logger.info("Transfer cancel requested but already finished: {}",
runner);
break;
default:
logger.info("Transfer cancel requested but internal error: {}",
runner);
break;
}
}
} else if (stop) {
ErrorCode code = sendValid(runner, LocalPacketFactory.STOPPACKET);
switch (code) {
case CompleteOk:
logger.info("Transfer stop requested and done: {}", runner);
break;
case TransferOk:
logger.info("Transfer stop requested but already finished: {}",
runner);
break;
default:
logger.info("Transfer stop requested but internal error: {}",
runner);
break;
}
} else if (restart) {
ErrorCode code = sendValid(runner, LocalPacketFactory.VALIDPACKET);
switch (code) {
case QueryStillRunning:
logger.info(
"Transfer restart requested but already active and running: {}",
runner);
break;
case Running:
logger.info("Transfer restart requested but already running: {}",
runner);
break;
case PreProcessingOk:
logger.info("Transfer restart requested and restarted: {}",
runner);
break;
case CompleteOk:
logger.info("Transfer restart requested but already finished: {}",
runner);
break;
case RemoteError:
logger.info("Transfer restart requested but remote error: {}",
runner);
break;
case PassThroughMode:
logger.info("Transfer not restarted since it is in PassThrough mode: {}",
runner);
break;
default:
logger.info("Transfer restart requested but internal error: {}",
runner);
break;
}
}
} else {
logger.info("Transfer information:\n " + runner.toShortString());
future.setResult(new R66Result(null, true, runner.getErrorInfo(), runner));
future.setSuccess();
}
}
|
public void testUpdateGame() {
System.out.println(model);
Player player = model.getPlayers().get(0);
double stepSize = Parameters.INSTANCE.getPlayerStepSize();
double pD = 0.2;
FPosition prevPos = new FPosition(0, 0);
boolean test1;
boolean test2;
prevPos = player.getGamePosition();
model.updateGame(player, PlayerAction.MOVE_WEST);
test1 = Math.abs(prevPos.getX() - stepSize - player.getGamePosition().getX()) < 0.01 &&
Math.abs(prevPos.getY() - player.getGamePosition().getY()) < 0.01;
while(player.getGamePosition().getX() - (int)player.getGamePosition().getX() - stepSize > pD) {
model.updateGame(player, PlayerAction.MOVE_WEST);
}
prevPos = player.getGamePosition();
model.updateGame(player, PlayerAction.MOVE_WEST);
test2 = (prevPos.getX() == player.getGamePosition().getX() &&
prevPos.getY() == player.getGamePosition().getY());
assertTrue(test1);
}
| public void testUpdateGame() {
System.out.println(model);
Player player = model.getPlayers().get(0);
double stepSize = Parameters.INSTANCE.getPlayerStepSize();
double pD = 0.2;
FPosition prevPos = new FPosition(0, 0);
boolean test1;
boolean test2;
prevPos = player.getGamePosition();
model.updateGame(player, PlayerAction.MOVE_WEST);
test1 = Math.abs(prevPos.getX() - stepSize - player.getGamePosition().getX()) < 0.01 &&
Math.abs(prevPos.getY() - player.getGamePosition().getY()) < 0.01;
while(player.getGamePosition().getX() - (int)player.getGamePosition().getX() - stepSize > pD) {
model.updateGame(player, PlayerAction.MOVE_WEST);
}
prevPos = player.getGamePosition();
model.updateGame(player, PlayerAction.MOVE_WEST);
test2 = (prevPos.getX() == player.getGamePosition().getX() &&
prevPos.getY() == player.getGamePosition().getY());
assertTrue(test1 && test2);
}
|
private List<Area<Type>> get(int x, int y, int z, boolean checkY) {
ArrayList<Area<Type>> areas = new ArrayList<Area<Type>>();
if (hasAreas) {
IntervalTree tree = intervalsByRegion.get(new ChunkCoordIntPair(x >> 9, z >> 9));
if (tree != null) {
List<Area<Type>> intervalAreas = tree.get(x);
int size = intervalAreas.size();
for (int i = 0; i < size; i++) {
Area<Type> area = intervalAreas.get(0);
if (z >= area.z1 && z <= area.z2) {
if (checkY && area instanceof Cube) {
Cube cube = (Cube)area;
if (y >= cube.y1 && y <= cube.y2) {
areas.add(area);
}
}
else {
areas.add(area);
}
}
}
}
}
return areas;
}
| private List<Area<Type>> get(int x, int y, int z, boolean checkY) {
ArrayList<Area<Type>> areas = new ArrayList<Area<Type>>();
if (hasAreas) {
IntervalTree tree = intervalsByRegion.get(new ChunkCoordIntPair(x >> 9, z >> 9));
if (tree != null) {
List<Area<Type>> intervalAreas = tree.get(x);
int size = intervalAreas.size();
for (int i = 0; i < size; i++) {
Area<Type> area = intervalAreas.get(i);
if (z >= area.z1 && z <= area.z2) {
if (checkY && area instanceof Cube) {
Cube cube = (Cube)area;
if (y >= cube.y1 && y <= cube.y2) {
areas.add(area);
}
}
else {
areas.add(area);
}
}
}
}
}
return areas;
}
|
private static Crypto loadClass(String cryptoClassName, Properties properties) {
Class cryptogenClass = null;
Crypto crypto = null;
try {
cryptogenClass = java.lang.Class.forName(cryptoClassName);
} catch (ClassNotFoundException e) {
throw new RuntimeException(cryptoClassName + " Not Found");
}
log.info("Using Crypto Engine [" + cryptoClassName + "]");
try {
Class[] classes = new Class[]{Properties.class};
Constructor c = cryptogenClass.getConstructor(classes);
crypto = (Crypto) c.newInstance(new Object[]{properties});
return crypto;
} catch (java.lang.reflect.InvocationTargetException e) {
if(e.getCause() != null) {
e.getCause().printStackTrace();
log.error(e.getCause());
}
e.printStackTrace();
log.error(e);
} catch (java.lang.Exception e) {
e.printStackTrace();
log.error(e);
}
try {
crypto = (Crypto) cryptogenClass.newInstance();
return crypto;
} catch (java.lang.Exception e) {
e.printStackTrace();
log.error(e);
throw new RuntimeException(cryptoClassName + " cannot create instance");
}
}
| private static Crypto loadClass(String cryptoClassName, Properties properties) {
Class cryptogenClass = null;
Crypto crypto = null;
try {
cryptogenClass = java.lang.Class.forName(cryptoClassName);
} catch (ClassNotFoundException e) {
throw new RuntimeException(cryptoClassName + " Not Found");
}
log.info("Using Crypto Engine [" + cryptoClassName + "]");
try {
Class[] classes = new Class[]{Properties.class};
Constructor c = cryptogenClass.getConstructor(classes);
crypto = (Crypto) c.newInstance(new Object[]{properties});
return crypto;
} catch (java.lang.Exception e) {
e.printStackTrace();
log.error("Unable to instantiate (1): " + cryptoClassName, e);
}
try {
crypto = (Crypto) cryptogenClass.newInstance();
return crypto;
} catch (java.lang.Exception e) {
e.printStackTrace();
log.error("Unable to instantiate (2): " + cryptoClassName, e);
throw new RuntimeException(cryptoClassName + " cannot create instance");
}
}
|
public void actionPerformed(ActionEvent e) {
int currentNetworkCount = Cytoscape.getNetworkSet().size();
if (currentNetworkCount != 0) {
String warning = "Current session will be lost.\nDo you want to continue?";
int result = JOptionPane.showConfirmDialog(Cytoscape.getDesktop(), warning, "Caution!",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE, null);
if (result == JOptionPane.YES_OPTION) {
Cytoscape.setSessionState(Cytoscape.SESSION_OPENED);
Cytoscape.createNewSession();
Cytoscape.getDesktop().setTitle("Cytoscape Desktop (New Session)");
Cytoscape.setSessionState(Cytoscape.SESSION_NEW);
} else {
return;
}
}
}
| public void actionPerformed(ActionEvent e) {
String warning = "Current session (all networks/attributes) will be lost.\nDo you want to continue?";
int result = JOptionPane.showConfirmDialog(Cytoscape.getDesktop(), warning, "Caution!",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE, null);
if (result == JOptionPane.YES_OPTION) {
Cytoscape.setSessionState(Cytoscape.SESSION_OPENED);
Cytoscape.createNewSession();
Cytoscape.getDesktop().setTitle("Cytoscape Desktop (New Session)");
Cytoscape.setSessionState(Cytoscape.SESSION_NEW);
} else {
return;
}
}
|
public List<Usuari> getUsuarisByFilter (String id, String nif, String nombre, String apellidos, String perfil)
throws DAOException {
getConnectionDB();
List<Usuari> result = new LinkedList<Usuari>();
String sql = QUERY_USUARIS_BY_FILTER;
if (id.length() > 0)
sql += " AND id = " + id;
if (nif.length() > 0)
sql += " AND nif = '" + nif +"'";
if ((nombre.length() > 0))
sql += " AND nombre = '" + nombre +"'";
if (apellidos.length() > 0)
sql += " AND apellidos = '" + apellidos +"'";
if (perfil.length() > 0)
sql += " AND perfil = '" + perfil +"'";
getConnectionDB();
Statement stm = createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = null;
try {
rs = stm.executeQuery(sql);
while (rs.next()){
result.add(
new Usuari(rs.getInt("id"), rs.getInt("taller"), rs.getString("usuari"), rs.getString("perfil"),
rs.getString("nif"), rs.getString("nom"), rs.getString("cognoms"),
rs.getString("contrasenya"), rs.getBoolean("actiu"), rs.getDate("dataAlta"), rs.getDate("dataModificacio"),
rs.getDate("dataBaixa"), rs.getInt("reparacionsAssignades")));
}
return result;
} catch (SQLException e) {
throw new DAOException(DAOException.ERR_SQL, e.getMessage(), e);
} finally {
if (stm!=null) {
try {
stm.close();
} catch (SQLException e) {
throw new DAOException(DAOException.ERR_RESOURCE_CLOSED, e.getMessage(), e);
}
}
if (rs!=null) {
try {
rs.close();
} catch (SQLException e) {
throw new DAOException(DAOException.ERR_RESOURCE_CLOSED, e.getMessage(), e);
}
}
}
}
| public List<Usuari> getUsuarisByFilter (String id, String nif, String nombre, String apellidos, String perfil)
throws DAOException {
getConnectionDB();
List<Usuari> result = new LinkedList<Usuari>();
String sql = QUERY_USUARIS_BY_FILTER;
if (id.length() > 0)
sql += " AND id = " + id;
if (nif.length() > 0)
sql += " AND nif = '" + nif +"'";
if ((nombre.length() > 0))
sql += " AND nom = '" + nombre +"'";
if (apellidos.length() > 0)
sql += " AND cognoms = '" + apellidos +"'";
if (perfil.length() > 0)
sql += " AND perfil = '" + perfil +"'";
getConnectionDB();
Statement stm = createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = null;
try {
rs = stm.executeQuery(sql);
while (rs.next()){
result.add(
new Usuari(rs.getInt("id"), rs.getInt("taller"), rs.getString("usuari"), rs.getString("perfil"),
rs.getString("nif"), rs.getString("nom"), rs.getString("cognoms"),
rs.getString("contrasenya"), rs.getBoolean("actiu"), rs.getDate("dataAlta"), rs.getDate("dataModificacio"),
rs.getDate("dataBaixa"), rs.getInt("reparacionsAssignades")));
}
return result;
} catch (SQLException e) {
throw new DAOException(DAOException.ERR_SQL, e.getMessage(), e);
} finally {
if (stm!=null) {
try {
stm.close();
} catch (SQLException e) {
throw new DAOException(DAOException.ERR_RESOURCE_CLOSED, e.getMessage(), e);
}
}
if (rs!=null) {
try {
rs.close();
} catch (SQLException e) {
throw new DAOException(DAOException.ERR_RESOURCE_CLOSED, e.getMessage(), e);
}
}
}
}
|
public int run(String[] args) throws Exception {
Configuration conf = getConf();
HadoopUtils.setPool(conf, "di.nonsla");
HadoopUtils.setMapAttempts(conf, 1);
adjustConfigurationForHive(conf);
Job job = new Job(conf, "hive-io-writing");
if (job.getJar() == null) {
job.setJarByClass(getClass());
}
job.setMapperClass(SampleMapper.class);
job.setInputFormatClass(SampleInputFormat.class);
job.setMapOutputKeyClass(NullWritable.class);
job.setMapOutputValueClass(HiveWritableRecord.class);
job.setOutputFormatClass(SampleOutputFormat.class);
job.setNumReduceTasks(0);
job.submit();
return job.waitForCompletion(true) ? 0 : 1;
}
| public int run(String[] args) throws Exception
{
Configuration conf = getConf();
HadoopUtils.setPool(conf, "di.nonsla");
HadoopUtils.setMapAttempts(conf, 1);
adjustConfigurationForHive(conf);
HiveTools.setupJob(conf);
Job job = new Job(conf, "hive-io-writing");
if (job.getJar() == null) {
job.setJarByClass(getClass());
}
job.setMapperClass(SampleMapper.class);
job.setInputFormatClass(SampleInputFormat.class);
job.setMapOutputKeyClass(NullWritable.class);
job.setMapOutputValueClass(HiveWritableRecord.class);
job.setOutputFormatClass(SampleOutputFormat.class);
job.setNumReduceTasks(0);
job.submit();
return job.waitForCompletion(true) ? 0 : 1;
}
|
public void createControl(Composite parent2) {
Composite top = new Composite(parent2, SWT.NULL);
top.setLayout(new GridLayout());
GridData data = new GridData(GridData.FILL_BOTH);
data.widthHint = 50;
top.setLayoutData(data);
setControl(top);
if (participant.getSubscriber().roots().length == 0) {
Label l = new Label(top, SWT.NULL);
l.setText(Policy.bind("GlobalRefreshResourceSelectionPage.4"));
setPageComplete(false);
} else {
Label l = new Label(top, SWT.NULL);
l.setText(Policy.bind("GlobalRefreshResourceSelectionPage.5"));
fViewer = new ContainerCheckedTreeViewer(top, SWT.BORDER);
data = new GridData(GridData.FILL_HORIZONTAL);
data.heightHint = 100;
fViewer.getControl().setLayoutData(data);
fViewer.setContentProvider(new MyContentProvider());
fViewer.setLabelProvider( new DecoratingLabelProvider(
new MyLabelProvider(),
PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()));
fViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
updateOKStatus();
}
});
fViewer.setSorter(new ResourceSorter(ResourceSorter.NAME));
fViewer.setInput(participant);
Group scopeGroup = new Group(top, SWT.NULL);
scopeGroup.setText(Policy.bind("GlobalRefreshResourceSelectionPage.6"));
GridLayout layout = new GridLayout();
layout.numColumns = 4;
layout.makeColumnsEqualWidth = false;
scopeGroup.setLayout(layout);
data = new GridData(GridData.FILL_HORIZONTAL);
data.widthHint = 50;
scopeGroup.setLayoutData(data);
participantScope = new Button(scopeGroup, SWT.RADIO);
participantScope.setText(Policy.bind("GlobalRefreshResourceSelectionPage.7"));
participantScope.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateParticipantScope();
}
});
selectedResourcesScope = new Button(scopeGroup, SWT.RADIO);
selectedResourcesScope.setText(Policy.bind("GlobalRefreshResourceSelectionPage.8"));
selectedResourcesScope.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateSelectedResourcesScope();
}
});
enclosingProjectsScope = new Button(scopeGroup, SWT.RADIO);
enclosingProjectsScope.setText(Policy.bind("GlobalRefreshResourceSelectionPage.9"));
enclosingProjectsScope.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateEnclosingProjectScope();
}
});
data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
data.horizontalIndent = 15;
data.horizontalSpan = 2;
enclosingProjectsScope.setLayoutData(data);
workingSetScope = new Button(scopeGroup, SWT.RADIO);
workingSetScope.setText(Policy.bind("GlobalRefreshResourceSelectionPage.10"));
workingSetScope.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if(workingSetScope.getSelection()) {
updateWorkingSetScope();
}
}
});
workingSetLabel = new Text(scopeGroup, SWT.BORDER);
workingSetLabel.setEditable(false);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 2;
workingSetLabel.setLayoutData(data);
Button selectWorkingSetButton = new Button(scopeGroup, SWT.NULL);
selectWorkingSetButton.setText(Policy.bind("GlobalRefreshResourceSelectionPage.11"));
selectWorkingSetButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
selectWorkingSetAction();
}
});
data = new GridData(GridData.HORIZONTAL_ALIGN_END);
selectWorkingSetButton.setLayoutData(data);
Dialog.applyDialogFont(selectWorkingSetButton);
initializeScopingHint();
}
Dialog.applyDialogFont(top);
}
| public void createControl(Composite parent2) {
Composite top = new Composite(parent2, SWT.NULL);
top.setLayout(new GridLayout());
GridData data = new GridData(GridData.FILL_BOTH);
data.widthHint = 50;
top.setLayoutData(data);
setControl(top);
if (participant.getSubscriber().roots().length == 0) {
Label l = new Label(top, SWT.NULL);
l.setText(Policy.bind("GlobalRefreshResourceSelectionPage.4"));
setPageComplete(false);
} else {
Label l = new Label(top, SWT.NULL);
l.setText(Policy.bind("GlobalRefreshResourceSelectionPage.5"));
fViewer = new ContainerCheckedTreeViewer(top, SWT.BORDER);
data = new GridData(GridData.FILL_BOTH);
data.heightHint = 100;
fViewer.getControl().setLayoutData(data);
fViewer.setContentProvider(new MyContentProvider());
fViewer.setLabelProvider( new DecoratingLabelProvider(
new MyLabelProvider(),
PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()));
fViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
updateOKStatus();
}
});
fViewer.setSorter(new ResourceSorter(ResourceSorter.NAME));
fViewer.setInput(participant);
Group scopeGroup = new Group(top, SWT.NULL);
scopeGroup.setText(Policy.bind("GlobalRefreshResourceSelectionPage.6"));
GridLayout layout = new GridLayout();
layout.numColumns = 4;
layout.makeColumnsEqualWidth = false;
scopeGroup.setLayout(layout);
data = new GridData(GridData.FILL_HORIZONTAL);
data.widthHint = 50;
scopeGroup.setLayoutData(data);
participantScope = new Button(scopeGroup, SWT.RADIO);
participantScope.setText(Policy.bind("GlobalRefreshResourceSelectionPage.7"));
participantScope.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateParticipantScope();
}
});
selectedResourcesScope = new Button(scopeGroup, SWT.RADIO);
selectedResourcesScope.setText(Policy.bind("GlobalRefreshResourceSelectionPage.8"));
selectedResourcesScope.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateSelectedResourcesScope();
}
});
enclosingProjectsScope = new Button(scopeGroup, SWT.RADIO);
enclosingProjectsScope.setText(Policy.bind("GlobalRefreshResourceSelectionPage.9"));
enclosingProjectsScope.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateEnclosingProjectScope();
}
});
data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
data.horizontalIndent = 15;
data.horizontalSpan = 2;
enclosingProjectsScope.setLayoutData(data);
workingSetScope = new Button(scopeGroup, SWT.RADIO);
workingSetScope.setText(Policy.bind("GlobalRefreshResourceSelectionPage.10"));
workingSetScope.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if(workingSetScope.getSelection()) {
updateWorkingSetScope();
}
}
});
workingSetLabel = new Text(scopeGroup, SWT.BORDER);
workingSetLabel.setEditable(false);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 2;
workingSetLabel.setLayoutData(data);
Button selectWorkingSetButton = new Button(scopeGroup, SWT.NULL);
selectWorkingSetButton.setText(Policy.bind("GlobalRefreshResourceSelectionPage.11"));
selectWorkingSetButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
selectWorkingSetAction();
}
});
data = new GridData(GridData.HORIZONTAL_ALIGN_END);
selectWorkingSetButton.setLayoutData(data);
Dialog.applyDialogFont(selectWorkingSetButton);
initializeScopingHint();
}
Dialog.applyDialogFont(top);
}
|
protected void paint(Graphics g) {
mLogger.debug("Drawing Trip screen");
if (mKmWidth < 0) {
Font f = g.getFont();
mKmWidth = f.stringWidth("km");
mfontHeight = f.getHeight();
}
Position pos = mParent.getCurrentPosition();
int h = getHeight();
int w = getWidth();
g.setColor(0x00ffffff);
g.fillRect(0, 0, w, h);
g.setColor(0);
int y = 48;
mLcdFont.setFontSize(36);
mLcdFont.drawInt(g, (int)(pos.course), w, y - 6);
g.drawLine(0, y, w, y);
y += 48;
if (mParent.getTarget() == null) {
mLcdFont.drawInvalid(g, 3, w, y - 6);
y += 48;
mLcdFont.drawInvalid(g, 4, w - mKmWidth -1, y - 6);
g.drawString("km", w - 1, y - 3, Graphics.BOTTOM | Graphics.RIGHT);
} else {
float[] result = ProjMath.calcDistanceAndCourse(mParent.center.radlat,
mParent.center.radlon, mParent.getTarget().lat,
mParent.getTarget().lon);
int relHeading = (int)(result[1] - pos.course + 0.5);
if (relHeading < 0)
{
relHeading += 360;
}
mLcdFont.drawInt(g, relHeading, w, y - 6);
g.drawLine(0, y, w, y);
y += 48;
if (result[0] > 10000) {
mLcdFont.drawInt(g, (int)((result[0] / 1000.0f) + 0.5),
w - mKmWidth -1, y - 6);
g.drawString("km", w - 1, y - 3, Graphics.BOTTOM | Graphics.RIGHT);
} else if (result[0] > 1000) {
mLcdFont.drawFloat(g, (int)(((result[0] / 100.0f) + 0.5) /
10.0f), 1, w - mKmWidth - 1, y - 6);
g.drawString("km", w - 1, y - 3, Graphics.BOTTOM | Graphics.RIGHT);
} else {
mLcdFont.drawInt(g, (int)(result[0] + 0.5),
w - mKmWidth - 1, y - 6);
g.drawString("m", w - 1, y - 3, Graphics.BOTTOM | Graphics.RIGHT);
}
}
g.drawLine(0, y, w, y);
if ((mSunCalc == null) ||
( mSunCalc != null
&& Math.abs(ProjMath.getDistance(mParent.center.radlat,
mParent.center.radlon,
mSunCalc.getLatitude() * MoreMath.FAC_DECTORAD,
mSunCalc.getLongitude() * MoreMath.FAC_DECTORAD
) ) > 10000)
) {
if (mSunCalc == null) {
mSunCalc = new SunCalc();
}
mSunCalc.setLatitude(mParent.center.radlat * MoreMath.FAC_RADTODEC);
mSunCalc.setLongitude(mParent.center.radlon * MoreMath.FAC_RADTODEC);
Calendar nowCal = Calendar.getInstance();
mSunCalc.setYear( nowCal.get( Calendar.YEAR ) );
mSunCalc.setMonth( nowCal.get( Calendar.MONTH ) + 1 );
mSunCalc.setDay( nowCal.get( Calendar.DAY_OF_MONTH ) );
int tzone = nowCal.getTimeZone().getOffset( 1,
nowCal.get(Calendar.YEAR), nowCal.get(Calendar.MONTH),
nowCal.get(Calendar.DAY_OF_MONTH),
nowCal.get(Calendar.DAY_OF_WEEK), 0);
mSunCalc.setTimeZoneOffset( tzone / 3600000 );
mSunRiseset = mSunCalc.calcRiseSet( SunCalc.SUNRISE_SUNSET );
mLogger.info("SunCalc result: " + mSunCalc.toString());
}
y += 24;
g.drawLine(w >> 1, y - 24, w >> 1, h);
if (mSunRiseset != null) {
g.drawString("Sunrise: " + mSunCalc.formatTime(mSunRiseset[SunCalc.RISE]),
(w >> 1) - 3, y, Graphics.BOTTOM | Graphics.RIGHT);
g.drawString("Sunset: " + mSunCalc.formatTime(mSunRiseset[SunCalc.SET]),
w - 3, y, Graphics.BOTTOM | Graphics.RIGHT);
} else {
g.drawString("Sunrise: N/A", (w >> 1) - 3, y,
Graphics.BOTTOM | Graphics.RIGHT);
g.drawString("Sunset: N/A", w - 3, y,
Graphics.BOTTOM | Graphics.RIGHT);
}
}
| protected void paint(Graphics g) {
mLogger.debug("Drawing Trip screen");
if (mKmWidth < 0) {
Font f = g.getFont();
mKmWidth = f.stringWidth("km");
mfontHeight = f.getHeight();
}
Position pos = mParent.getCurrentPosition();
int h = getHeight();
int w = getWidth();
g.setColor(0x00ffffff);
g.fillRect(0, 0, w, h);
g.setColor(0);
int y = 48;
mLcdFont.setFontSize(36);
mLcdFont.drawInt(g, (int)(pos.course), w, y - 6);
g.drawLine(0, y, w, y);
y += 48;
if (mParent.getTarget() == null) {
mLcdFont.drawInvalid(g, 3, w, y - 6);
y += 48;
mLcdFont.drawInvalid(g, 4, w - mKmWidth -1, y - 6);
g.drawString("km", w - 1, y - 3, Graphics.BOTTOM | Graphics.RIGHT);
} else {
float[] result = ProjMath.calcDistanceAndCourse(mParent.center.radlat,
mParent.center.radlon, mParent.getTarget().lat,
mParent.getTarget().lon);
int relHeading = (int)(result[1] - pos.course + 0.5);
if (relHeading < 0)
{
relHeading += 360;
}
mLcdFont.drawInt(g, relHeading, w, y - 6);
g.drawLine(0, y, w, y);
y += 48;
if (result[0] > 100000) {
mLcdFont.drawInt(g, (int)((result[0] / 1000.0f) + 0.5),
w - mKmWidth -1, y - 6);
g.drawString("km", w - 1, y - 3, Graphics.BOTTOM | Graphics.RIGHT);
} else if (result[0] > 1000) {
mLcdFont.drawFloat(g, (int)((result[0] / 100.0f) + 0.5) /
10.0f, 1, w - mKmWidth - 1, y - 6);
g.drawString("km", w - 1, y - 3, Graphics.BOTTOM | Graphics.RIGHT);
} else {
mLcdFont.drawInt(g, (int)(result[0] + 0.5),
w - mKmWidth - 1, y - 6);
g.drawString("m", w - 1, y - 3, Graphics.BOTTOM | Graphics.RIGHT);
}
}
g.drawLine(0, y, w, y);
if ((mSunCalc == null) ||
( mSunCalc != null
&& Math.abs(ProjMath.getDistance(mParent.center.radlat,
mParent.center.radlon,
mSunCalc.getLatitude() * MoreMath.FAC_DECTORAD,
mSunCalc.getLongitude() * MoreMath.FAC_DECTORAD
) ) > 10000)
) {
if (mSunCalc == null) {
mSunCalc = new SunCalc();
}
mSunCalc.setLatitude(mParent.center.radlat * MoreMath.FAC_RADTODEC);
mSunCalc.setLongitude(mParent.center.radlon * MoreMath.FAC_RADTODEC);
Calendar nowCal = Calendar.getInstance();
mSunCalc.setYear( nowCal.get( Calendar.YEAR ) );
mSunCalc.setMonth( nowCal.get( Calendar.MONTH ) + 1 );
mSunCalc.setDay( nowCal.get( Calendar.DAY_OF_MONTH ) );
int tzone = nowCal.getTimeZone().getOffset( 1,
nowCal.get(Calendar.YEAR), nowCal.get(Calendar.MONTH),
nowCal.get(Calendar.DAY_OF_MONTH),
nowCal.get(Calendar.DAY_OF_WEEK), 0);
mSunCalc.setTimeZoneOffset( tzone / 3600000 );
mSunRiseset = mSunCalc.calcRiseSet( SunCalc.SUNRISE_SUNSET );
mLogger.info("SunCalc result: " + mSunCalc.toString());
}
y += 24;
g.drawLine(w >> 1, y - 24, w >> 1, h);
if (mSunRiseset != null) {
g.drawString("Sunrise: " + mSunCalc.formatTime(mSunRiseset[SunCalc.RISE]),
(w >> 1) - 3, y, Graphics.BOTTOM | Graphics.RIGHT);
g.drawString("Sunset: " + mSunCalc.formatTime(mSunRiseset[SunCalc.SET]),
w - 3, y, Graphics.BOTTOM | Graphics.RIGHT);
} else {
g.drawString("Sunrise: N/A", (w >> 1) - 3, y,
Graphics.BOTTOM | Graphics.RIGHT);
g.drawString("Sunset: N/A", w - 3, y,
Graphics.BOTTOM | Graphics.RIGHT);
}
}
|
public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
if (!ExportUtils.testIsOkForRecord(test)) {
return;
}
test.resetStatus();
if(isRecording()) {
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
setRunning(false);
} else {
setRunning(true);
TransitionNode firstPage = test.getStartPoint().getFirstNodeFromOutTransitions();
if (firstPage != null) {
if (firstPage.getFirstNodeFromOutTransitions() != null && selectedPage == null) {
UserInfo.showWarnDialog("Please select a Page/State to record from (test is not empty).");
setRunning(false);
return;
}
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt(), new Shell());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
if (selectedNodeNeedsToForwardBrowser() || test.getStartPoint() instanceof ExtensionStartPoint) {
UserInfo.setStatusLine("Test browser is forwarded to the selected state. Please wait...");
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (45 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
runner.setActiveEditor(action, (IEditorPart) testEditor);
runner.setCustomCompletedMessage("Recording can begin (test browser is forwarded). Result: $result.");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
if (selectedPage != null) {
if (!ModelUtil.isOnPathToNode(test.getStartPoint(), selectedPage)) {
ErrorHandler.logAndShowErrorDialogAndThrow("Cannot find path from start point to selected page");
}
runner.setTargetPage(selectedPage);
}
runner.setPreSelectedTest(test);
runner.run(action);
}
cubicRecorder.setEnabled(true);
if (selectedPage != null) {
cubicRecorder.setCursor(selectedPage);
}
guiAwareRecorder.setEnabled(true);
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
setRunning(false);
return;
}
}
}
| public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
if (!ExportUtils.testIsOkForRecord(test)) {
return;
}
test.resetStatus();
if(isRecording()) {
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
setRunning(false);
} else {
setRunning(true);
TransitionNode firstPage = test.getStartPoint().getFirstNodeFromOutTransitions();
if (firstPage != null) {
if (firstPage.getFirstNodeFromOutTransitions() != null && selectedPage == null) {
UserInfo.showWarnDialog("Please select a Page/State to record from (test is not empty).");
setRunning(false);
return;
}
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt(), new Shell());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
if (selectedNodeNeedsToForwardBrowser() || test.getStartPoint() instanceof ExtensionStartPoint) {
UserInfo.setStatusLine("Test browser is forwarded to the selected state. Please wait...");
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (45 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
runner.setActivePart(action, (IEditorPart) testEditor);
runner.setCustomCompletedMessage("Recording can begin (test browser is forwarded). Result: $result.");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
if (selectedPage != null) {
if (!ModelUtil.isOnPathToNode(test.getStartPoint(), selectedPage)) {
ErrorHandler.logAndShowErrorDialogAndThrow("Cannot find path from start point to selected page");
}
runner.setTargetPage(selectedPage);
}
runner.setPreSelectedTest(test);
runner.run(action);
}
cubicRecorder.setEnabled(true);
if (selectedPage != null) {
cubicRecorder.setCursor(selectedPage);
}
guiAwareRecorder.setEnabled(true);
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
setRunning(false);
return;
}
}
}
|
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
_checkBox.setPreferredSize(new Dimension(_checkBox.getPreferredSize().width, 0));
applyComponentOrientation(list.getComponentOrientation());
Object actualValue;
if (list instanceof CheckBoxList) {
CheckBoxListSelectionModel selectionModel = ((CheckBoxList) list).getCheckBoxListSelectionModel();
if (selectionModel != null) {
boolean enabled = list.isEnabled()
&& ((CheckBoxList) list).isCheckBoxEnabled()
&& ((CheckBoxList) list).isCheckBoxEnabled(index);
if (!enabled && !isSelected) {
if (getBackground() != null) {
setForeground(getBackground().darker());
}
}
_checkBox.setEnabled(enabled);
_checkBox.setSelected(selectionModel.isSelectedIndex(index));
}
actualValue = value;
}
else if (list instanceof CheckBoxListWithSelectable) {
if (value instanceof Selectable) {
_checkBox.setSelected(((Selectable) value).isSelected());
boolean enabled = list.isEnabled() && ((Selectable) value).isEnabled() && ((CheckBoxListWithSelectable) list).isCheckBoxEnabled();
if (!enabled && !isSelected) {
setForeground(getBackground().darker());
}
_checkBox.setEnabled(enabled);
}
else {
boolean enabled = list.isEnabled();
if (!enabled && !isSelected) {
setForeground(getBackground().darker());
}
_checkBox.setEnabled(enabled);
}
if (value instanceof DefaultSelectable) {
actualValue = ((DefaultSelectable) value).getObject();
}
else {
actualValue = value;
}
}
else {
throw new IllegalArgumentException("CheckBoxListCellRenderer should only be used for CheckBoxList.");
}
if (_actualListRenderer != null) {
JComponent listCellRendererComponent = (JComponent) _actualListRenderer.getListCellRendererComponent(list, actualValue, index, isSelected, cellHasFocus);
if (list instanceof CheckBoxListWithSelectable) {
if (!((CheckBoxListWithSelectable) list).isCheckBoxVisible(index)) {
return listCellRendererComponent;
}
}
if (list instanceof CheckBoxList) {
if (!((CheckBoxList) list).isCheckBoxVisible(index)) {
return listCellRendererComponent;
}
}
Border border = listCellRendererComponent.getBorder();
setBorder(border);
listCellRendererComponent.setBorder(BorderFactory.createEmptyBorder());
if (getComponentCount() == 2) {
remove(1);
}
add(listCellRendererComponent);
setBackground(listCellRendererComponent.getBackground());
listCellRendererComponent.setBackground(null);
setForeground(listCellRendererComponent.getForeground());
listCellRendererComponent.setForeground(null);
}
else {
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
if (getComponentCount() == 2) {
remove(1);
}
add(_label);
customizeDefaultCellRenderer(actualValue);
setFont(list.getFont());
}
return this;
}
| public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
_checkBox.setPreferredSize(new Dimension(_checkBox.getPreferredSize().width, 0));
applyComponentOrientation(list.getComponentOrientation());
Object actualValue;
if (list instanceof CheckBoxList) {
CheckBoxListSelectionModel selectionModel = ((CheckBoxList) list).getCheckBoxListSelectionModel();
if (selectionModel != null) {
boolean enabled = list.isEnabled()
&& ((CheckBoxList) list).isCheckBoxEnabled()
&& ((CheckBoxList) list).isCheckBoxEnabled(index);
if (!enabled && !isSelected) {
if (getBackground() != null) {
setForeground(getBackground().darker());
}
}
_checkBox.setEnabled(enabled);
_checkBox.setSelected(selectionModel.isSelectedIndex(index));
}
actualValue = value;
}
else if (list instanceof CheckBoxListWithSelectable) {
if (value instanceof Selectable) {
_checkBox.setSelected(((Selectable) value).isSelected());
boolean enabled = list.isEnabled() && ((Selectable) value).isEnabled() && ((CheckBoxListWithSelectable) list).isCheckBoxEnabled();
if (!enabled && !isSelected) {
setForeground(getBackground().darker());
}
_checkBox.setEnabled(enabled);
}
else {
boolean enabled = list.isEnabled();
if (!enabled && !isSelected) {
setForeground(getBackground().darker());
}
_checkBox.setEnabled(enabled);
}
if (value instanceof DefaultSelectable) {
actualValue = ((DefaultSelectable) value).getObject();
}
else {
actualValue = value;
}
}
else {
throw new IllegalArgumentException("CheckBoxListCellRenderer should only be used for CheckBoxList.");
}
if (_actualListRenderer != null) {
JComponent listCellRendererComponent = (JComponent) _actualListRenderer.getListCellRendererComponent(list, actualValue, index, isSelected, cellHasFocus);
if (list instanceof CheckBoxListWithSelectable) {
if (!((CheckBoxListWithSelectable) list).isCheckBoxVisible(index)) {
return listCellRendererComponent;
}
}
if (list instanceof CheckBoxList) {
if (!((CheckBoxList) list).isCheckBoxVisible(index)) {
return listCellRendererComponent;
}
}
Border border = listCellRendererComponent.getBorder();
setBorder(border);
listCellRendererComponent.setBorder(BorderFactory.createEmptyBorder());
if (getComponentCount() == 2) {
remove(1);
}
add(listCellRendererComponent);
setBackground(listCellRendererComponent.getBackground());
listCellRendererComponent.setBackground(null);
setForeground(listCellRendererComponent.getForeground());
listCellRendererComponent.setForeground(null);
listCellRendererComponent.setEnabled(_checkBox.isEnabled());
}
else {
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
if (getComponentCount() == 2) {
remove(1);
}
add(_label);
customizeDefaultCellRenderer(actualValue);
setFont(list.getFont());
}
return this;
}
|
public void testIsInvalidMessage() {
PreservationRequest pr = new PreservationRequest();
pr.UUID = UUID.randomUUID().toString();
pr.Preservation_profile = "simple";
pr.Update_URI = "http://localhost/update";
assertTrue(pr.isMessageValid());
pr.Update_URI = null;
assertFalse(pr.isMessageValid());
}
| public void testIsInvalidMessage() {
PreservationRequest pr = new PreservationRequest();
pr.UUID = UUID.randomUUID().toString();
pr.Preservation_profile = "simple";
pr.Update_URI = "http://localhost/update";
pr.Model = "Work";
assertTrue(pr.isMessageValid());
pr.Update_URI = null;
assertFalse(pr.isMessageValid());
}
|
private void createClasspathProperty() {
final StringBuffer sb = new StringBuffer();
sb.append(projectmy.getBuild().getOutputDirectory()).append(':');
for (final Object o : projectmy.getRuntimeArtifacts()) {
final Artifact artifact = (Artifact)o;
sb.append(artifact.getFile().getAbsolutePath()).append(':');
}
final File[] jars = libLocalDir.listFiles(
new FileFilter() {
@Override
public boolean accept(final File pathname) {
return pathname.getName().toLowerCase().endsWith(".jar");
}
});
for (final File jar : jars) {
if (getLog().isDebugEnabled()) {
getLog().debug("add jar: " + jar);
}
sb.append(jar.getAbsolutePath()).append(':');
}
sb.deleteCharAt(sb.length() - 1);
final String classpath = sb.toString();
if (getLog().isInfoEnabled()) {
getLog().info("created classpath: " + classpath);
}
projectmy.getProperties().put(PROP_CIDS_CLASSPATH, classpath);
}
| private void createClasspathProperty() {
final StringBuffer sb = new StringBuffer();
sb.append(projectmy.getBuild().getOutputDirectory()).append(':');
for (final Object o : projectmy.getRuntimeArtifacts()) {
final Artifact artifact = (Artifact)o;
sb.append(artifact.getFile().getAbsolutePath()).append(':');
}
if (libLocalDir.exists()) {
final File[] jars = libLocalDir.listFiles(
new FileFilter() {
@Override
public boolean accept(final File pathname) {
return pathname.getName().toLowerCase().endsWith(".jar");
}
});
if (jars == null) {
if (getLog().isWarnEnabled()) {
getLog().warn("an I/O error occured while fetching jars from lib local folder: " + libLocalDir);
}
} else {
for (final File jar : jars) {
if (getLog().isDebugEnabled()) {
getLog().debug("add jar: " + jar);
}
sb.append(jar.getAbsolutePath()).append(':');
}
}
} else {
if (getLog().isWarnEnabled()) {
getLog().warn("lib local dir property does not denote an existing filename: " + libLocalDir);
}
}
sb.deleteCharAt(sb.length() - 1);
final String classpath = sb.toString();
if (getLog().isInfoEnabled()) {
getLog().info("created classpath: " + classpath);
}
projectmy.getProperties().put(PROP_CIDS_CLASSPATH, classpath);
}
|
private void imageLoaded(URL url, File path) {
if (imageWidth == 0 || imageHeight == 0)
return;
Bitmap img = BitmapFactory.decodeFile(path.getPath());
if (img == null) {
return;
}
img = Bitmap.createScaledBitmap(img, imageWidth, imageHeight, true);
imageCache.put(url, img);
if (currentImage.equals(url))
currentBitmap = img;
}
| private void imageLoaded(URL url, File path) {
if (imageWidth == 0 || imageHeight == 0)
return;
Bitmap img = null;
try {
img = BitmapFactory.decodeFile(path.getPath());
if (img == null) {
return;
}
} catch (OutOfMemoryError e) {
return;
}
img = Bitmap.createScaledBitmap(img, imageWidth, imageHeight, true);
imageCache.put(url, img);
if (currentImage.equals(url))
currentBitmap = img;
}
|
public void testGaussian() throws Throwable
{
ActivationGaussian activation = new ActivationGaussian(0.0,1.0);
Assert.assertFalse(activation.hasDerivative());
ActivationGaussian clone = (ActivationGaussian)activation.clone();
Assert.assertNotNull(clone);
double[] input = { 0.0 };
activation.activationFunction(input,0,input.length);
Assert.assertEquals(1.0,input[0],0.1);
input[0] = activation.derivativeFunction(input[0],input[0]);
Assert.assertEquals(0,(int)(input[0]*100),0.1);
}
| public void testGaussian() throws Throwable
{
ActivationGaussian activation = new ActivationGaussian(0.0,1.0);
Assert.assertFalse(!activation.hasDerivative());
ActivationGaussian clone = (ActivationGaussian)activation.clone();
Assert.assertNotNull(clone);
double[] input = { 0.0 };
activation.activationFunction(input,0,input.length);
Assert.assertEquals(1.0,input[0],0.1);
input[0] = activation.derivativeFunction(input[0],input[0]);
Assert.assertEquals(0,(int)(input[0]*100),0.1);
}
|
public void evaluatePolicy()
throws Exception {
entering("evaluatePolicy", null);
log(logLevel, "evaluatePolicy ", null);
log(logLevel, "evaluatePolicy ", initSetup);
log(logLevel, "evaluatePolicy", "mapIdentity" + mapIdentity);
log(logLevel, "evaluatePolicy", "mapscenario" +
mapScenario);
log(logLevel, "evaluatePolicy", "mapexecute" +
mapExecute);
log(logLevel, "evaluatePolicy", "env parameters" +
mapEnvParams);
Reporter.log("evaluatePolicy" + mapScenario);
Reporter.log("evaluatePolicy" + mapExecute);
Reporter.log("evaluatePolicy" +
mapEnvParams);
try {
usertoken = getToken((String)mapExecute.get("username"),
(String)mapExecute.get("password"),
(String)mapExecute.get("realmname"));
PolicyEvaluator pe = new PolicyEvaluator("iPlanetAMWebAgent" +
"Service");
Set actions = new HashSet();
actions.add((String)mapExecute.get("action"));
boolean expectedResult = Boolean.valueOf((String)mapExecute.
get("result"));
boolean pResult = pe.isAllowed(usertoken, (String)mapExecute.
get("resourcename"), (String)mapExecute.get("action"),
mapEnvParams);
PolicyDecision pd = pe.getPolicyDecision(usertoken,
(String)mapExecute.get("resourcename"), actions,
mapEnvParams);
log(logLevel, "evaluatePolicy", "decision" + pResult);
log(logLevel, "evaluatePolicy", pd.toXML());
assert (pResult == expectedResult);
}catch (Exception e) {
log(Level.SEVERE, "evaluatePolicy", e.getMessage(), null);
e.printStackTrace();
throw e;
}finally {
destroyToken(usertoken);
}
exiting("evaluatePolicy");
}
| public void evaluatePolicy()
throws Exception {
entering("evaluatePolicy", null);
log(logLevel, "evaluatePolicy ", null);
log(logLevel, "evaluatePolicy ", initSetup);
log(logLevel, "evaluatePolicy", "mapIdentity" + mapIdentity);
log(logLevel, "evaluatePolicy", "mapscenario" +
mapScenario);
log(logLevel, "evaluatePolicy", "mapexecute" +
mapExecute);
log(logLevel, "evaluatePolicy", "env parameters" +
mapEnvParams);
Reporter.log("evaluatePolicy" + mapScenario);
Reporter.log("evaluatePolicy" + mapExecute);
Reporter.log("evaluatePolicy" +
mapEnvParams);
try {
usertoken = getToken((String)mapExecute.get("username"),
(String)mapExecute.get("password"),
(String)mapExecute.get("realmname"));
if (mapIdentity.containsKey("test" + initSetup +
".Identity." + "spcount")){
Integer spCount = new Integer((String)mapIdentity.get
("test" + initSetup + ".Identity.spcount"));
if (spCount > 0 ) {
pc.setProperty(usertoken, mapIdentity, initSetup);
}
}
PolicyEvaluator pe = new PolicyEvaluator("iPlanetAMWebAgent" +
"Service");
Set actions = new HashSet();
actions.add((String)mapExecute.get("action"));
boolean expectedResult = Boolean.valueOf((String)mapExecute.
get("result"));
boolean pResult = pe.isAllowed(usertoken, (String)mapExecute.
get("resourcename"), (String)mapExecute.get("action"),
mapEnvParams);
PolicyDecision pd = pe.getPolicyDecision(usertoken,
(String)mapExecute.get("resourcename"), actions,
mapEnvParams);
log(logLevel, "evaluatePolicy", "decision" + pResult);
log(logLevel, "evaluatePolicy", pd.toXML());
assert (pResult == expectedResult);
}catch (Exception e) {
log(Level.SEVERE, "evaluatePolicy", e.getMessage(), null);
e.printStackTrace();
throw e;
}finally {
destroyToken(usertoken);
}
exiting("evaluatePolicy");
}
|
protected void onCreate(Bundle RandomVariableName) {
super.onCreate(RandomVariableName);
setContentView(R.layout.splash);
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openStartingPoint = new Intent("com.example.thenewboston.MENU");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
| protected void onCreate(Bundle Splash) {
super.onCreate(Splash);
setContentView(R.layout.splash);
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openMainActivity = new Intent("com.c1.charityworkout.mainActivity");
startActivity(openMainActivity);
}
}
};
timer.start();
}
|
public void execute() throws BuildException
{
initArgs();
if (dataFile != null)
{
addArg("--datafile");
addArg(dataFile);
}
if (toDir != null)
{
addArg("--destination");
addArg(toDir.toString());
}
if (ignoreRegex != null)
{
addArg("--ignore");
addArg(ignoreRegex.getRegex());
}
Set filenames = new HashSet();
Iterator iter = fileSets.iterator();
while (iter.hasNext())
{
FileSet fileSet = (FileSet)iter.next();
addArg("--basedir");
addArg(baseDir(fileSet));
filenames.addAll(Arrays.asList(getFilenames(fileSet)));
}
addFilenames((String[])filenames.toArray(new String[filenames.size()]));
saveArgs();
if (getJava().executeJava() != 0)
{
throw new BuildException();
}
unInitArgs();
}
| public void execute() throws BuildException
{
initArgs();
if (dataFile != null)
{
addArg("--datafile");
addArg(dataFile);
}
if (toDir != null)
{
addArg("--destination");
addArg(toDir.toString());
}
if (ignoreRegex != null)
{
addArg("--ignore");
addArg(ignoreRegex.getRegex());
}
Set filenames = new HashSet();
Iterator iter = fileSets.iterator();
while (iter.hasNext())
{
FileSet fileSet = (FileSet)iter.next();
addArg("--basedir");
addArg(baseDir(fileSet));
filenames.addAll(Arrays.asList(getFilenames(fileSet)));
}
addFilenames((String[])filenames.toArray(new String[filenames.size()]));
saveArgs();
if (getJava().executeJava() != 0)
{
throw new BuildException("Error instrumenting classes. See messages above.");
}
unInitArgs();
}
|
public void postInit(FMLPostInitializationEvent event) {
if (Loader.isModLoaded("EnderStorage")) {
ItemStack obsidian = new ItemStack(Block.obsidian);
ItemStack enderChest = null;
try {
Class clazz = Class.forName("codechicken.enderstorage.EnderStorage");
enderChest = new ItemStack((Block)clazz.getDeclaredField("blockEnderChest").get(clazz), 1, OreDictionary.WILDCARD_VALUE);
} catch(Exception ex) {
}
if (enderChest != null) {
GameRegistry.addRecipe(Upgrade.CROSS_DIMENSIONAL.toItemStack(), "C", "U", "D", 'C', enderChest, 'D', obsidian, 'U', Upgrade.BLANK.toItemStack());
GameRegistry.addRecipe(Upgrade.CROSS_DIMENSIONAL.toItemStack(), "D", "U", "C", 'C', enderChest, 'D', obsidian, 'U', Upgrade.BLANK.toItemStack());
} else {
IOLogger.warn("Tried to get Ender Storage EnderChest, but failed!");
}
}
if (Loader.isModLoaded("BuildCraft|Core")) {
String[] pipeTypes = new String[] {"Wood", "Cobblestone", "Stone", "Quartz", "Iron", "Gold", "Diamond"};
ItemStack[] pipes = new ItemStack[pipeTypes.length];
boolean failed = false;
try {
Class clazz = Class.forName("buildcraft.BuildCraftTransport");
for (int i=0; i<pipeTypes.length; i++) {
pipes[i] = new ItemStack((Item)clazz.getDeclaredField("pipePower" + pipeTypes[i]).get(clazz));
}
} catch(Exception ex) {
IOLogger.warn("Tried to get Buildcraft power pipes, but failed! Buildcraft support will not be available!");
IOLogger.warn("Reason: " + ex.getMessage());
failed = true;
}
if (!failed) {
for (ItemStack pipe : pipes) {
GameRegistry.addRecipe(Upgrade.POWER_MJ.toItemStack(), "C", "U", "C", 'C', pipe, 'U', Upgrade.BLANK.toItemStack());
}
}
}
if (Loader.isModLoaded("IC2")) {
String[] cableTypes = new String[] {"copper", "insulatedCopper", "gold", "insulatedGold", "iron", "insulatedIron", "insulatedTin", "glassFiber", "tin"};
ItemStack[] cables = new ItemStack[cableTypes.length];
boolean failed = false;
try {
for (int i=0; i<cableTypes.length; i++) {
cables[i] = Items.getItem(cableTypes[i] + "CableItem");
}
} catch(Exception ex) {
IOLogger.warn("Tried to get IC2 power cables, but failed! IC2 support will not be available!");
IOLogger.warn("Reason: " + ex.getMessage());
failed = true;
}
if (!failed) {
for (ItemStack cable : cables) {
GameRegistry.addRecipe(Upgrade.POWER_EU.toItemStack(), "C", "U", "C", 'C', cable, 'U', Upgrade.BLANK.toItemStack());
}
}
}
if (Loader.isModLoaded("ThermalExpansion")) {
final String conduitPrefix = "conduitEnergy";
String[] conduitStrings = new String[] {"Basic", "Hardened", "Reinforced"};
ItemStack[] conduits = new ItemStack[conduitStrings.length];
boolean failed = false;
try {
Class clazz = Class.forName("thermalexpansion.block.conduit.BlockConduit");
for (int i=0; i<conduitStrings.length; i++) {
conduits[i] = (ItemStack) clazz.getDeclaredField(conduitPrefix + conduitStrings[i]).get(clazz);
}
} catch(Exception ex) {
IOLogger.warn("Tried to get Thermal Expansion power conduits, but failed! Thermal Expansion support will not be available!");
IOLogger.warn("Reason: " + ex.getMessage());
failed = true;
}
if (!failed) {
for (ItemStack conduit : conduits) {
GameRegistry.addRecipe(Upgrade.POWER_RF.toItemStack(), "C", "U", "C", 'C', conduit, 'U', Upgrade.BLANK.toItemStack());
}
}
}
List<Block> conductorBlocks = new ArrayList<Block>();
for (Block block : Block.blocksList) {
if (block instanceof BlockConductor) conductorBlocks.add(block);
}
if (conductorBlocks.size() > 0) {
for (Block block : conductorBlocks) {
GameRegistry.addRecipe(Upgrade.POWER_UE.toItemStack(), "C", "U", "C", 'C', block, 'U', Upgrade.BLANK.toItemStack());
}
}
}
| public void postInit(FMLPostInitializationEvent event) {
if (Loader.isModLoaded("EnderStorage")) {
ItemStack obsidian = new ItemStack(Block.obsidian);
ItemStack enderChest = null;
try {
Class clazz = Class.forName("codechicken.enderstorage.EnderStorage");
enderChest = new ItemStack((Block)clazz.getDeclaredField("blockEnderChest").get(clazz), 1, OreDictionary.WILDCARD_VALUE);
} catch(Exception ex) {
}
if (enderChest != null) {
GameRegistry.addRecipe(Upgrade.CROSS_DIMENSIONAL.toItemStack(), "C", "U", "D", 'C', enderChest, 'D', obsidian, 'U', Upgrade.BLANK.toItemStack());
GameRegistry.addRecipe(Upgrade.CROSS_DIMENSIONAL.toItemStack(), "D", "U", "C", 'C', enderChest, 'D', obsidian, 'U', Upgrade.BLANK.toItemStack());
} else {
IOLogger.warn("Tried to get Ender Storage EnderChest, but failed!");
}
}
if (Loader.isModLoaded("BuildCraft|Core")) {
String[] pipeTypes = new String[] {"Wood", "Cobblestone", "Stone", "Quartz", "Iron", "Gold", "Diamond"};
ItemStack[] pipes = new ItemStack[pipeTypes.length];
boolean failed = false;
try {
Class clazz = Class.forName("buildcraft.BuildCraftTransport");
for (int i=0; i<pipeTypes.length; i++) {
pipes[i] = new ItemStack((Item)clazz.getDeclaredField("pipePower" + pipeTypes[i]).get(clazz));
}
} catch(Exception ex) {
IOLogger.warn("Tried to get Buildcraft power pipes, but failed! Buildcraft support will not be available!");
IOLogger.warn("Reason: " + ex.getMessage());
failed = true;
}
if (!failed) {
for (ItemStack pipe : pipes) {
GameRegistry.addRecipe(Upgrade.POWER_MJ.toItemStack(), "C", "U", "C", 'C', pipe, 'U', Upgrade.BLANK.toItemStack());
}
}
}
if (Loader.isModLoaded("IC2")) {
String[] cableTypes = new String[] {"copper", "insulatedCopper", "gold", "insulatedGold", "iron", "insulatedIron", "insulatedTin", "glassFiber", "tin"};
ItemStack[] cables = new ItemStack[cableTypes.length];
boolean failed = false;
try {
for (int i=0; i<cableTypes.length; i++) {
cables[i] = Items.getItem(cableTypes[i] + "CableItem");
}
} catch(Exception ex) {
IOLogger.warn("Tried to get IC2 power cables, but failed! IC2 support will not be available!");
IOLogger.warn("Reason: " + ex.getMessage());
failed = true;
}
if (!failed) {
for (ItemStack cable : cables) {
GameRegistry.addRecipe(Upgrade.POWER_EU.toItemStack(), "C", "U", "C", 'C', cable, 'U', Upgrade.BLANK.toItemStack());
}
}
}
if (Loader.isModLoaded("ThermalExpansion")) {
final String conduitPrefix = "conduitEnergy";
String[] conduitStrings = new String[] {"Basic", "Hardened", "Reinforced"};
ItemStack[] conduits = new ItemStack[conduitStrings.length];
boolean failed = false;
try {
Class clazz = Class.forName("thermalexpansion.part.conduit.ItemConduitPart");
for (int i=0; i<conduitStrings.length; i++) {
conduits[i] = (ItemStack) clazz.getDeclaredField(conduitPrefix + conduitStrings[i]).get(clazz);
}
} catch(Exception ex) {
IOLogger.warn("Tried to get Thermal Expansion power conduits, but failed! Thermal Expansion support will not be available!");
IOLogger.warn("Reason: " + ex.getMessage());
failed = true;
}
if (!failed) {
for (ItemStack conduit : conduits) {
GameRegistry.addRecipe(Upgrade.POWER_RF.toItemStack(), "C", "U", "C", 'C', conduit, 'U', Upgrade.BLANK.toItemStack());
}
}
}
List<Block> conductorBlocks = new ArrayList<Block>();
for (Block block : Block.blocksList) {
if (block instanceof BlockConductor) conductorBlocks.add(block);
}
if (conductorBlocks.size() > 0) {
for (Block block : conductorBlocks) {
GameRegistry.addRecipe(Upgrade.POWER_UE.toItemStack(), "C", "U", "C", 'C', block, 'U', Upgrade.BLANK.toItemStack());
}
}
}
|
public void doSchedule() {
long start = System.currentTimeMillis();
logger.log(Level.INFO, MonitorUtil.parseTime(start, true)
+ " -> START: Scheduled send alert mail ...");
String alertName = MonitorConstant.ALERTSTORE_DEFAULT_NAME + ": "
+ MonitorUtil.parseTime(start, false);
SystemDAO sysDAO = new SystemDaoImpl();
AlertDao alertDAO = new AlertDaoImpl();
ArrayList<SystemMonitor> systems = sysDAO
.listSystemsFromMemcache(false);
MailService mailService = new MailService();
MailMonitorDAO mailDAO = new MailMonitorDaoImpl();
UtilityDAO utilDAO = new UtilityDaoImpl();
if (systems != null && systems.size() > 0) {
ArrayList<UserMonitor> listUsers = utilDAO.listAllUsers();
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
ArrayList<GroupMonitor> groups = user.getGroups();
for (int j = 0; j < groups.size(); j++) {
for (int k = 0; k < systems.size(); k++) {
SystemMonitor sys = systems.get(k);
String groupName = sys.getGroupEmail();
if (groupName.equals(groups.get(j).getName())) {
user.addSystem(sys);
}
}
}
}
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
ArrayList<SystemMonitor> allSystem = listUsers.get(i)
.getSystems();
if (allSystem != null) {
for (int j = 0; j < allSystem.size(); j++) {
SystemMonitor tempSys = allSystem.get(j);
AlertStoreMonitor alertstore = alertDAO
.getLastestAlertStore(tempSys);
if (alertstore != null) {
alertstore.setName(alertName);
alertstore.setTimeStamp(new Date(start));
NotifyMonitor notify = null;
try {
notify = sysDAO.getNotifyOption(tempSys
.getCode());
} catch (Exception e) {
notify = new NotifyMonitor();
}
alertstore.fixAlertList(notify);
if (alertstore.getAlerts().size() > 0) {
user.addAlertStore(alertstore);
}
}
}
}
}
if (listUsers != null && listUsers.size() > 0) {
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
if (user.getStores() != null && user.getStores().size() > 0) {
MailConfigMonitor config = mailDAO.getMailConfig(user
.getId());
try {
String content = MailService.parseContent(
user.getStores(), config);
mailService.sendMail(alertName, content, config);
logger.log(Level.INFO, "send mail" + content);
} catch (Exception e) {
logger.log(Level.INFO, "Can not send mail"
+ e.getMessage().toString());
}
}
}
for (SystemMonitor sys : systems) {
AlertStoreMonitor store = alertDAO
.getLastestAlertStore(sys);
alertDAO.putAlertStore(store);
alertDAO.clearTempStore(sys);
}
}
for (SystemMonitor sys : systems) {
AlertStoreMonitor asm = alertDAO.getLastestAlertStore(sys);
if (asm == null) {
asm = new AlertStoreMonitor();
}
asm.setCpuUsage(sys.getLastestCpuUsage());
asm.setMemUsage(sys.getLastestMemoryUsage());
asm.setSysId(sys.getId());
asm.setName(alertName);
asm.setTimeStamp(new Date(start));
alertDAO.putAlertStore(asm);
alertDAO.clearTempStore(sys);
}
} else {
logger.log(Level.INFO, "NO SYSTEM FOUND");
}
long end = System.currentTimeMillis();
long time = end - start;
logger.log(Level.INFO, MonitorUtil.parseTime(end, true)
+ " -> END: Scheduled send alert mail. Time executed: " + time
+ " ms");
}
| public void doSchedule() {
long start = System.currentTimeMillis();
logger.log(Level.INFO, MonitorUtil.parseTime(start, true)
+ " -> START: Scheduled send alert mail ...");
String alertName = MonitorConstant.ALERTSTORE_DEFAULT_NAME + ": "
+ MonitorUtil.parseTime(start, false);
SystemDAO sysDAO = new SystemDaoImpl();
AlertDao alertDAO = new AlertDaoImpl();
ArrayList<SystemMonitor> systems = sysDAO
.listSystemsFromMemcache(false);
MailService mailService = new MailService();
MailMonitorDAO mailDAO = new MailMonitorDaoImpl();
UtilityDAO utilDAO = new UtilityDaoImpl();
if (systems != null && systems.size() > 0) {
ArrayList<UserMonitor> listUsers = utilDAO.listAllUsers();
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
ArrayList<GroupMonitor> groups = user.getGroups();
for (int j = 0; j < groups.size(); j++) {
for (int k = 0; k < systems.size(); k++) {
SystemMonitor sys = systems.get(k);
String groupName = sys.getGroupEmail();
if (groupName.equals(groups.get(j).getName())) {
user.addSystem(sys);
}
}
}
}
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
ArrayList<SystemMonitor> allSystem = listUsers.get(i)
.getSystems();
if (allSystem != null) {
for (int j = 0; j < allSystem.size(); j++) {
SystemMonitor tempSys = allSystem.get(j);
AlertStoreMonitor alertstore = alertDAO
.getLastestAlertStore(tempSys);
if (alertstore != null) {
alertstore.setName(alertName);
alertstore.setTimeStamp(new Date(start));
NotifyMonitor notify = null;
try {
notify = sysDAO.getNotifyOption(tempSys
.getCode());
} catch (Exception e) {
}
if (notify == null) {
notify = new NotifyMonitor();
}
alertstore.fixAlertList(notify);
if (alertstore.getAlerts().size() > 0) {
user.addAlertStore(alertstore);
}
}
}
}
}
if (listUsers != null && listUsers.size() > 0) {
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
if (user.getStores() != null && user.getStores().size() > 0) {
MailConfigMonitor config = mailDAO.getMailConfig(user
.getId());
try {
String content = MailService.parseContent(
user.getStores(), config);
mailService.sendMail(alertName, content, config);
logger.log(Level.INFO, "send mail" + content);
} catch (Exception e) {
logger.log(Level.INFO, "Can not send mail"
+ e.getMessage().toString());
}
}
}
for (SystemMonitor sys : systems) {
AlertStoreMonitor store = alertDAO
.getLastestAlertStore(sys);
alertDAO.putAlertStore(store);
alertDAO.clearTempStore(sys);
}
}
for (SystemMonitor sys : systems) {
AlertStoreMonitor asm = alertDAO.getLastestAlertStore(sys);
if (asm == null) {
asm = new AlertStoreMonitor();
}
asm.setCpuUsage(sys.getLastestCpuUsage());
asm.setMemUsage(sys.getLastestMemoryUsage());
asm.setSysId(sys.getId());
asm.setName(alertName);
asm.setTimeStamp(new Date(start));
alertDAO.putAlertStore(asm);
alertDAO.clearTempStore(sys);
}
} else {
logger.log(Level.INFO, "NO SYSTEM FOUND");
}
long end = System.currentTimeMillis();
long time = end - start;
logger.log(Level.INFO, MonitorUtil.parseTime(end, true)
+ " -> END: Scheduled send alert mail. Time executed: " + time
+ " ms");
}
|
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
int len = args.length;
if (len == 0) return true;
int startIndex = 0;
long delay = -1;
if (args[0].trim().toLowerCase().startsWith("-delay=")){
startIndex = 1;
try{
delay = Long.parseLong(args[0].substring(7));
} catch(NumberFormatException nEx){
getServer().getLogger().severe(msgLabel+" Bad delay definition ("+args[0]+") on command: "+getCmdLine(args, 0));
return false;
}
}
if ( startIndex >= len) return true;
scheduleCmd(getCmdLine(args, startIndex), delay);
return true;
}
| public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (!sender.isOp() && !sender.hasPermission("delayedcommand.use")){
sender.sendMessage("You do not have permission to use this!");
return true;
}
int len = args.length;
if (len == 0) return true;
int startIndex = 0;
long delay = -1;
if (args[0].trim().toLowerCase().startsWith("-delay=")){
startIndex = 1;
try{
delay = Long.parseLong(args[0].substring(7));
} catch(NumberFormatException nEx){
getServer().getLogger().severe(msgLabel+" Bad delay definition ("+args[0]+") on command: "+getCmdLine(args, 0));
return false;
}
}
if ( startIndex >= len) return true;
scheduleCmd(getCmdLine(args, startIndex), delay);
return true;
}
|
public void changeSittingTaskForOcelots(LivingEvent.LivingUpdateEvent evt) {
if (evt.entityLiving instanceof EntityOcelot && evt.entityLiving.ticksExisted < 5)
{
EntityOcelot ocelot = (EntityOcelot) evt.entityLiving;
@SuppressWarnings("unchecked")
List<EntityAITaskEntry> tasks = ocelot.tasks.field_75782_a;
for (int i=0; i<tasks.size(); i++)
{
EntityAITaskEntry task = tasks.get(i);
if (task.priority == 6 && (task.action instanceof EntityAIOcelotSit) && !(task.action instanceof IronChestAIOcelotSit))
{
task.action = new IronChestAIOcelotSit(ocelot, 0.4F);
}
}
}
}
| public void changeSittingTaskForOcelots(LivingEvent.LivingUpdateEvent evt) {
if (evt.entityLiving.ticksExisted < 5 && evt.entityLiving instanceof EntityOcelot)
{
EntityOcelot ocelot = (EntityOcelot) evt.entityLiving;
@SuppressWarnings("unchecked")
List<EntityAITaskEntry> tasks = ocelot.tasks.field_75782_a;
for (int i=0; i<tasks.size(); i++)
{
EntityAITaskEntry task = tasks.get(i);
if (task.priority == 6 && (task.action instanceof EntityAIOcelotSit) && !(task.action instanceof IronChestAIOcelotSit))
{
task.action = new IronChestAIOcelotSit(ocelot, 0.4F);
}
}
}
}
|
public void onCreate() {
super.onCreate();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.enableLogging()
.memoryCacheSize(41943040)
.discCacheSize(104857600)
.threadPoolSize(10)
.build();
ImageLoader.getInstance().init(config);
}
| public void onCreate() {
super.onCreate();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.memoryCacheSize(41943040)
.discCacheSize(104857600)
.threadPoolSize(10)
.build();
ImageLoader.getInstance().init(config);
}
|
private void printHelp(String cmd) {
String summary = "hadoop fs is the command to execute fs commands. " +
"The full syntax is: \n\n" +
"hadoop fs [-fs <local | file system URI>] [-conf <configuration file>]\n\t" +
"[-D <property=value>] [-ls <path>] [-lsr <path>] [-du <path>]\n\t" +
"[-dus <path>] [-mv <src> <dst>] [-cp <src> <dst>] [-rm <src>]\n\t" +
"[-rmr <src>] [-put <localsrc> ... <dst>] [-copyFromLocal <localsrc> ... <dst>]\n\t" +
"[-moveFromLocal <localsrc> ... <dst>] [" +
GET_SHORT_USAGE + "\n\t" +
"[-getmerge <src> <localdst> [addnl]] [-cat <src>]\n\t" +
"[" + COPYTOLOCAL_SHORT_USAGE + "] [-moveToLocal <src> <localdst>]\n\t" +
"[-mkdir <path>] [-report] [" + SETREP_SHORT_USAGE + "]\n\t" +
"[-touchz <path>] [-test -[ezd] <path>] [-stat [format] <path>]\n\t" +
"[-tail [-f] <path>] [-text <path>]\n\t" +
"[" + FsShellPermissions.CHMOD_USAGE + "]\n\t" +
"[" + FsShellPermissions.CHOWN_USAGE + "]\n\t" +
"[" + FsShellPermissions.CHGRP_USAGE + "]\n\t" +
"[" + Count.USAGE + "]\n\t" +
"[-help [cmd]]\n";
String conf ="-conf <configuration file>: Specify an application configuration file.";
String D = "-D <property=value>: Use value for given property.";
String fs = "-fs [local | <file system URI>]: \tSpecify the file system to use.\n" +
"\t\tIf not specified, the current configuration is used, \n" +
"\t\ttaken from the following, in increasing precedence: \n" +
"\t\t\thadoop-default.xml inside the hadoop jar file \n" +
"\t\t\thadoop-default.xml in $HADOOP_CONF_DIR \n" +
"\t\t\thadoop-site.xml in $HADOOP_CONF_DIR \n" +
"\t\t'local' means use the local file system as your DFS. \n" +
"\t\t<file system URI> specifies a particular file system to \n" +
"\t\tcontact. This argument is optional but if used must appear\n" +
"\t\tappear first on the command line. Exactly one additional\n" +
"\t\targument must be specified. \n";
String ls = "-ls <path>: \tList the contents that match the specified file pattern. If\n" +
"\t\tpath is not specified, the contents of /user/<currentUser>\n" +
"\t\twill be listed. Directory entries are of the form \n" +
"\t\t\tdirName (full path) <dir> \n" +
"\t\tand file entries are of the form \n" +
"\t\t\tfileName(full path) <r n> size \n" +
"\t\twhere n is the number of replicas specified for the file \n" +
"\t\tand size is the size of the file, in bytes.\n";
String lsr = "-lsr <path>: \tRecursively list the contents that match the specified\n" +
"\t\tfile pattern. Behaves very similarly to hadoop fs -ls,\n" +
"\t\texcept that the data is shown for all the entries in the\n" +
"\t\tsubtree.\n";
String du = "-du <path>: \tShow the amount of space, in bytes, used by the files that \n" +
"\t\tmatch the specified file pattern. Equivalent to the unix\n" +
"\t\tcommand \"du -sb <path>/*\" in case of a directory, \n" +
"\t\tand to \"du -b <path>\" in case of a file.\n" +
"\t\tThe output is in the form \n" +
"\t\t\tname(full path) size (in bytes)\n";
String dus = "-dus <path>: \tShow the amount of space, in bytes, used by the files that \n" +
"\t\tmatch the specified file pattern. Equivalent to the unix\n" +
"\t\tcommand \"du -sb\" The output is in the form \n" +
"\t\t\tname(full path) size (in bytes)\n";
String mv = "-mv <src> <dst>: Move files that match the specified file pattern <src>\n" +
"\t\tto a destination <dst>. When moving multiple files, the \n" +
"\t\tdestination must be a directory. \n";
String cp = "-cp <src> <dst>: Copy files that match the file pattern <src> to a \n" +
"\t\tdestination. When copying multiple files, the destination\n" +
"\t\tmust be a directory. \n";
String rm = "-rm <src>: \tDelete all files that match the specified file pattern.\n" +
"\t\tEquivlent to the Unix command \"rm <src>\"\n";
String rmr = "-rmr <src>: \tRemove all directories which match the specified file \n" +
"\t\tpattern. Equivlent to the Unix command \"rm -rf <src>\"\n";
String put = "-put <localsrc> ... <dst>: \tCopy files " +
"from the local file system \n\t\tinto fs. \n";
String copyFromLocal = "-copyFromLocal <localsrc> ... <dst>:" +
" Identical to the -put command.\n";
String moveFromLocal = "-moveFromLocal <localsrc> ... <dst>:" +
" Same as -put, except that the source is\n\t\tdeleted after it's copied.\n";
String get = GET_SHORT_USAGE
+ ": Copy files that match the file pattern <src> \n" +
"\t\tto the local name. <src> is kept. When copying mutiple, \n" +
"\t\tfiles, the destination must be a directory. \n";
String getmerge = "-getmerge <src> <localdst>: Get all the files in the directories that \n" +
"\t\tmatch the source file pattern and merge and sort them to only\n" +
"\t\tone file on local fs. <src> is kept.\n";
String cat = "-cat <src>: \tFetch all files that match the file pattern <src> \n" +
"\t\tand display their content on stdout.\n";
String copyToLocal = COPYTOLOCAL_SHORT_USAGE
+ ": Identical to the -get command.\n";
String moveToLocal = "-moveToLocal <src> <localdst>: Not implemented yet \n";
String mkdir = "-mkdir <path>: \tCreate a directory in specified location. \n";
String setrep = SETREP_SHORT_USAGE
+ ": Set the replication level of a file. \n"
+ "\t\tThe -R flag requests a recursive change of replication level \n"
+ "\t\tfor an entire tree.\n";
String touchz = "-touchz <path>: Write a timestamp in yyyy-MM-dd HH:mm:ss format\n" +
"\t\tin a file at <path>. An error is returned if the file exists with non-zero length\n";
String test = "-test -[ezd] <path>: If file { exists, has zero length, is a directory\n" +
"\t\tthen return 1, else return 0.\n";
String stat = "-stat [format] <path>: Print statistics about the file/directory at <path>\n" +
"\t\tin the specified format. Format accepts filesize in blocks (%b), filename (%n),\n" +
"\t\tblock size (%o), replication (%r), modification date (%y, %Y)\n";
String tail = TAIL_USAGE
+ ": Show the last 1KB of the file. \n"
+ "\t\tThe -f option shows apended data as the file grows. \n";
String chmod = FsShellPermissions.CHMOD_USAGE + "\n" +
"\t\tChanges permissions of a file.\n" +
"\t\tThis works similar to shell's chmod with a few exceptions.\n\n" +
"\t-R\tmodifies the files recursively. This is the only option\n" +
"\t\tcurrently supported.\n\n" +
"\tMODE\tMode is same as mode used for chmod shell command.\n" +
"\t\tOnly letters recognized are 'rwxX'. E.g.: a+r,g-w,+rwx,o=r\n\n" +
"\tOCTALMODE Mode specifed in 3 digits. Unlike shell command,\n" +
"\t\tthis requires all three digits.\n" +
"\t\tE.g.: 754 is same as u=rwx,g=rw,o=r\n\n" +
"\t\tIf none of 'augo' is specified, 'a' is assumed and unlike\n" +
"\t\tshell command, no umask is applied\n";
String chown = FsShellPermissions.CHOWN_USAGE + "\n" +
"\t\tChanges owner and group of a file.\n" +
"\t\tThis is similar to shell's chown with a few exceptions.\n\n" +
"\t-R\tmodifies the files recursively. This is the only option\n" +
"\t\tcurrently supported.\n\n" +
"\t\tIf only owner or group is specified then only owner or\n" +
"\t\tgroup is modified.\n\n" +
"\t\tThe owner and group names may only cosists of digits, alphabet,\n"+
"\t\tand any of '-_.@/' i.e. [-_.@/a-zA-Z0-9]. The names are case\n" +
"\t\tsensitive.\n\n" +
"\t\tWARNING: Avoid using '.' to separate user name and group though\n" +
"\t\tLinux allows it. If user names have dots in them and you are\n" +
"\t\tusing local file system, you might see surprising results since\n" +
"\t\tshell command 'chown' is used for local files.\n";
String chgrp = FsShellPermissions.CHGRP_USAGE + "\n" +
"\t\tThis is equivalent to -chown ... :GROUP ...\n";
String help = "-help [cmd]: \tDisplays help for given command or all commands if none\n" +
"\t\tis specified.\n";
if ("fs".equals(cmd)) {
System.out.println(fs);
} else if ("conf".equals(cmd)) {
System.out.println(conf);
} else if ("D".equals(cmd)) {
System.out.println(D);
} else if ("ls".equals(cmd)) {
System.out.println(ls);
} else if ("lsr".equals(cmd)) {
System.out.println(lsr);
} else if ("du".equals(cmd)) {
System.out.println(du);
} else if ("dus".equals(cmd)) {
System.out.println(dus);
} else if ("rm".equals(cmd)) {
System.out.println(rm);
} else if ("rmr".equals(cmd)) {
System.out.println(rmr);
} else if ("mkdir".equals(cmd)) {
System.out.println(mkdir);
} else if ("mv".equals(cmd)) {
System.out.println(mv);
} else if ("cp".equals(cmd)) {
System.out.println(cp);
} else if ("put".equals(cmd)) {
System.out.println(put);
} else if ("copyFromLocal".equals(cmd)) {
System.out.println(copyFromLocal);
} else if ("moveFromLocal".equals(cmd)) {
System.out.println(moveFromLocal);
} else if ("get".equals(cmd)) {
System.out.println(get);
} else if ("getmerge".equals(cmd)) {
System.out.println(getmerge);
} else if ("copyToLocal".equals(cmd)) {
System.out.println(copyToLocal);
} else if ("moveToLocal".equals(cmd)) {
System.out.println(moveToLocal);
} else if ("cat".equals(cmd)) {
System.out.println(cat);
} else if ("get".equals(cmd)) {
System.out.println(get);
} else if ("setrep".equals(cmd)) {
System.out.println(setrep);
} else if ("touchz".equals(cmd)) {
System.out.println(touchz);
} else if ("test".equals(cmd)) {
System.out.println(test);
} else if ("stat".equals(cmd)) {
System.out.println(stat);
} else if ("tail".equals(cmd)) {
System.out.println(tail);
} else if ("chmod".equals(cmd)) {
System.out.println(chmod);
} else if ("chown".equals(cmd)) {
System.out.println(chown);
} else if ("chgrp".equals(cmd)) {
System.out.println(chgrp);
} else if (Count.NAME.equals(cmd)) {
System.out.println(Count.DESCRIPTION);
} else if ("help".equals(cmd)) {
System.out.println(help);
} else {
System.out.println(summary);
System.out.println(fs);
System.out.println(ls);
System.out.println(lsr);
System.out.println(du);
System.out.println(dus);
System.out.println(mv);
System.out.println(cp);
System.out.println(rm);
System.out.println(rmr);
System.out.println(put);
System.out.println(copyFromLocal);
System.out.println(moveFromLocal);
System.out.println(get);
System.out.println(getmerge);
System.out.println(cat);
System.out.println(copyToLocal);
System.out.println(moveToLocal);
System.out.println(mkdir);
System.out.println(setrep);
System.out.println(chmod);
System.out.println(chown);
System.out.println(chgrp);
System.out.println(Count.DESCRIPTION);
System.out.println(help);
}
}
| private void printHelp(String cmd) {
String summary = "hadoop fs is the command to execute fs commands. " +
"The full syntax is: \n\n" +
"hadoop fs [-fs <local | file system URI>] [-conf <configuration file>]\n\t" +
"[-D <property=value>] [-ls <path>] [-lsr <path>] [-du <path>]\n\t" +
"[-dus <path>] [-mv <src> <dst>] [-cp <src> <dst>] [-rm <src>]\n\t" +
"[-rmr <src>] [-put <localsrc> ... <dst>] [-copyFromLocal <localsrc> ... <dst>]\n\t" +
"[-moveFromLocal <localsrc> ... <dst>] [" +
GET_SHORT_USAGE + "\n\t" +
"[-getmerge <src> <localdst> [addnl]] [-cat <src>]\n\t" +
"[" + COPYTOLOCAL_SHORT_USAGE + "] [-moveToLocal <src> <localdst>]\n\t" +
"[-mkdir <path>] [-report] [" + SETREP_SHORT_USAGE + "]\n\t" +
"[-touchz <path>] [-test -[ezd] <path>] [-stat [format] <path>]\n\t" +
"[-tail [-f] <path>] [-text <path>]\n\t" +
"[" + FsShellPermissions.CHMOD_USAGE + "]\n\t" +
"[" + FsShellPermissions.CHOWN_USAGE + "]\n\t" +
"[" + FsShellPermissions.CHGRP_USAGE + "]\n\t" +
"[" + Count.USAGE + "]\n\t" +
"[-help [cmd]]\n";
String conf ="-conf <configuration file>: Specify an application configuration file.";
String D = "-D <property=value>: Use value for given property.";
String fs = "-fs [local | <file system URI>]: \tSpecify the file system to use.\n" +
"\t\tIf not specified, the current configuration is used, \n" +
"\t\ttaken from the following, in increasing precedence: \n" +
"\t\t\thadoop-default.xml inside the hadoop jar file \n" +
"\t\t\thadoop-default.xml in $HADOOP_CONF_DIR \n" +
"\t\t\thadoop-site.xml in $HADOOP_CONF_DIR \n" +
"\t\t'local' means use the local file system as your DFS. \n" +
"\t\t<file system URI> specifies a particular file system to \n" +
"\t\tcontact. This argument is optional but if used must appear\n" +
"\t\tappear first on the command line. Exactly one additional\n" +
"\t\targument must be specified. \n";
String ls = "-ls <path>: \tList the contents that match the specified file pattern. If\n" +
"\t\tpath is not specified, the contents of /user/<currentUser>\n" +
"\t\twill be listed. Directory entries are of the form \n" +
"\t\t\tdirName (full path) <dir> \n" +
"\t\tand file entries are of the form \n" +
"\t\t\tfileName(full path) <r n> size \n" +
"\t\twhere n is the number of replicas specified for the file \n" +
"\t\tand size is the size of the file, in bytes.\n";
String lsr = "-lsr <path>: \tRecursively list the contents that match the specified\n" +
"\t\tfile pattern. Behaves very similarly to hadoop fs -ls,\n" +
"\t\texcept that the data is shown for all the entries in the\n" +
"\t\tsubtree.\n";
String du = "-du <path>: \tShow the amount of space, in bytes, used by the files that \n" +
"\t\tmatch the specified file pattern. Equivalent to the unix\n" +
"\t\tcommand \"du -sb <path>/*\" in case of a directory, \n" +
"\t\tand to \"du -b <path>\" in case of a file.\n" +
"\t\tThe output is in the form \n" +
"\t\t\tname(full path) size (in bytes)\n";
String dus = "-dus <path>: \tShow the amount of space, in bytes, used by the files that \n" +
"\t\tmatch the specified file pattern. Equivalent to the unix\n" +
"\t\tcommand \"du -sb\" The output is in the form \n" +
"\t\t\tname(full path) size (in bytes)\n";
String mv = "-mv <src> <dst>: Move files that match the specified file pattern <src>\n" +
"\t\tto a destination <dst>. When moving multiple files, the \n" +
"\t\tdestination must be a directory. \n";
String cp = "-cp <src> <dst>: Copy files that match the file pattern <src> to a \n" +
"\t\tdestination. When copying multiple files, the destination\n" +
"\t\tmust be a directory. \n";
String rm = "-rm <src>: \tDelete all files that match the specified file pattern.\n" +
"\t\tEquivlent to the Unix command \"rm <src>\"\n";
String rmr = "-rmr <src>: \tRemove all directories which match the specified file \n" +
"\t\tpattern. Equivlent to the Unix command \"rm -rf <src>\"\n";
String put = "-put <localsrc> ... <dst>: \tCopy files " +
"from the local file system \n\t\tinto fs. \n";
String copyFromLocal = "-copyFromLocal <localsrc> ... <dst>:" +
" Identical to the -put command.\n";
String moveFromLocal = "-moveFromLocal <localsrc> ... <dst>:" +
" Same as -put, except that the source is\n\t\tdeleted after it's copied.\n";
String get = GET_SHORT_USAGE
+ ": Copy files that match the file pattern <src> \n" +
"\t\tto the local name. <src> is kept. When copying mutiple, \n" +
"\t\tfiles, the destination must be a directory. \n";
String getmerge = "-getmerge <src> <localdst>: Get all the files in the directories that \n" +
"\t\tmatch the source file pattern and merge and sort them to only\n" +
"\t\tone file on local fs. <src> is kept.\n";
String cat = "-cat <src>: \tFetch all files that match the file pattern <src> \n" +
"\t\tand display their content on stdout.\n";
String copyToLocal = COPYTOLOCAL_SHORT_USAGE
+ ": Identical to the -get command.\n";
String moveToLocal = "-moveToLocal <src> <localdst>: Not implemented yet \n";
String mkdir = "-mkdir <path>: \tCreate a directory in specified location. \n";
String setrep = SETREP_SHORT_USAGE
+ ": Set the replication level of a file. \n"
+ "\t\tThe -R flag requests a recursive change of replication level \n"
+ "\t\tfor an entire tree.\n";
String touchz = "-touchz <path>: Write a timestamp in yyyy-MM-dd HH:mm:ss format\n" +
"\t\tin a file at <path>. An error is returned if the file exists with non-zero length\n";
String test = "-test -[ezd] <path>: If file { exists, has zero length, is a directory\n" +
"\t\tthen return 1, else return 0.\n";
String stat = "-stat [format] <path>: Print statistics about the file/directory at <path>\n" +
"\t\tin the specified format. Format accepts filesize in blocks (%b), filename (%n),\n" +
"\t\tblock size (%o), replication (%r), modification date (%y, %Y)\n";
String tail = TAIL_USAGE
+ ": Show the last 1KB of the file. \n"
+ "\t\tThe -f option shows apended data as the file grows. \n";
String chmod = FsShellPermissions.CHMOD_USAGE + "\n" +
"\t\tChanges permissions of a file.\n" +
"\t\tThis works similar to shell's chmod with a few exceptions.\n\n" +
"\t-R\tmodifies the files recursively. This is the only option\n" +
"\t\tcurrently supported.\n\n" +
"\tMODE\tMode is same as mode used for chmod shell command.\n" +
"\t\tOnly letters recognized are 'rwxX'. E.g. a+r,g-w,+rwx,o=r\n\n" +
"\tOCTALMODE Mode specifed in 3 digits. Unlike shell command,\n" +
"\t\tthis requires all three digits.\n" +
"\t\tE.g. 754 is same as u=rwx,g=rx,o=r\n\n" +
"\t\tIf none of 'augo' is specified, 'a' is assumed and unlike\n" +
"\t\tshell command, no umask is applied.\n";
String chown = FsShellPermissions.CHOWN_USAGE + "\n" +
"\t\tChanges owner and group of a file.\n" +
"\t\tThis is similar to shell's chown with a few exceptions.\n\n" +
"\t-R\tmodifies the files recursively. This is the only option\n" +
"\t\tcurrently supported.\n\n" +
"\t\tIf only owner or group is specified then only owner or\n" +
"\t\tgroup is modified.\n\n" +
"\t\tThe owner and group names may only cosists of digits, alphabet,\n"+
"\t\tand any of '-_.@/' i.e. [-_.@/a-zA-Z0-9]. The names are case\n" +
"\t\tsensitive.\n\n" +
"\t\tWARNING: Avoid using '.' to separate user name and group though\n" +
"\t\tLinux allows it. If user names have dots in them and you are\n" +
"\t\tusing local file system, you might see surprising results since\n" +
"\t\tshell command 'chown' is used for local files.\n";
String chgrp = FsShellPermissions.CHGRP_USAGE + "\n" +
"\t\tThis is equivalent to -chown ... :GROUP ...\n";
String help = "-help [cmd]: \tDisplays help for given command or all commands if none\n" +
"\t\tis specified.\n";
if ("fs".equals(cmd)) {
System.out.println(fs);
} else if ("conf".equals(cmd)) {
System.out.println(conf);
} else if ("D".equals(cmd)) {
System.out.println(D);
} else if ("ls".equals(cmd)) {
System.out.println(ls);
} else if ("lsr".equals(cmd)) {
System.out.println(lsr);
} else if ("du".equals(cmd)) {
System.out.println(du);
} else if ("dus".equals(cmd)) {
System.out.println(dus);
} else if ("rm".equals(cmd)) {
System.out.println(rm);
} else if ("rmr".equals(cmd)) {
System.out.println(rmr);
} else if ("mkdir".equals(cmd)) {
System.out.println(mkdir);
} else if ("mv".equals(cmd)) {
System.out.println(mv);
} else if ("cp".equals(cmd)) {
System.out.println(cp);
} else if ("put".equals(cmd)) {
System.out.println(put);
} else if ("copyFromLocal".equals(cmd)) {
System.out.println(copyFromLocal);
} else if ("moveFromLocal".equals(cmd)) {
System.out.println(moveFromLocal);
} else if ("get".equals(cmd)) {
System.out.println(get);
} else if ("getmerge".equals(cmd)) {
System.out.println(getmerge);
} else if ("copyToLocal".equals(cmd)) {
System.out.println(copyToLocal);
} else if ("moveToLocal".equals(cmd)) {
System.out.println(moveToLocal);
} else if ("cat".equals(cmd)) {
System.out.println(cat);
} else if ("get".equals(cmd)) {
System.out.println(get);
} else if ("setrep".equals(cmd)) {
System.out.println(setrep);
} else if ("touchz".equals(cmd)) {
System.out.println(touchz);
} else if ("test".equals(cmd)) {
System.out.println(test);
} else if ("stat".equals(cmd)) {
System.out.println(stat);
} else if ("tail".equals(cmd)) {
System.out.println(tail);
} else if ("chmod".equals(cmd)) {
System.out.println(chmod);
} else if ("chown".equals(cmd)) {
System.out.println(chown);
} else if ("chgrp".equals(cmd)) {
System.out.println(chgrp);
} else if (Count.NAME.equals(cmd)) {
System.out.println(Count.DESCRIPTION);
} else if ("help".equals(cmd)) {
System.out.println(help);
} else {
System.out.println(summary);
System.out.println(fs);
System.out.println(ls);
System.out.println(lsr);
System.out.println(du);
System.out.println(dus);
System.out.println(mv);
System.out.println(cp);
System.out.println(rm);
System.out.println(rmr);
System.out.println(put);
System.out.println(copyFromLocal);
System.out.println(moveFromLocal);
System.out.println(get);
System.out.println(getmerge);
System.out.println(cat);
System.out.println(copyToLocal);
System.out.println(moveToLocal);
System.out.println(mkdir);
System.out.println(setrep);
System.out.println(chmod);
System.out.println(chown);
System.out.println(chgrp);
System.out.println(Count.DESCRIPTION);
System.out.println(help);
}
}
|
public void printResultsToFile(int ontology, RealMatrix matrix, GOTerm[][] axis, String outputName, ArrayList<String> notes, ArrayList<GOTerm> targetGoIDs, String[] geneIDs) throws IOException {
validateOutputLocation(outputName);
File outputFileName;
Pattern p = Pattern.compile("\\.*");
Matcher matcher = p.matcher(outputName);
boolean addExtension = !matcher.matches();
switch (ontology) {
case 0:
if (addExtension) {
outputFileName = new File(outputName + "_BP.txt");
} else {
outputFileName = new File(outputName);
}
break;
case 1:
if (addExtension) {
outputFileName = new File(outputName + "_MF.txt");
} else {
outputFileName = new File(outputName);
}
break;
default:
if (addExtension) {
outputFileName = new File(outputName + "_CC.txt");
} else {
outputFileName = new File(outputName);
}
}
Map<Integer, Set<Integer>> goTermIds = new HashMap<Integer, Set<Integer>>();
goTermIds.put(0, getTermsForOntology(targetGoIDs, "biological_process"));
goTermIds.put(1, getTermsForOntology(targetGoIDs, "molecular_function"));
goTermIds.put(2, getTermsForOntology(targetGoIDs, "cellular_component"));
Set<Integer> goIds = goTermIds.get(ontology);
try {
if (matrix != null) {
logger.showMessage("Printing results for Ontology : " + ontologies[ontology]);
BufferedWriter out = new BufferedWriter(new FileWriter(outputFileName), 32768);
for (String note : notes) {
out.write("! ");
out.write(note);
out.newLine();
}
logger.showMessage("Notes printed");
String[] temp = new String[matrix.getRowDimension()];
logger.showMessage("Row dimension of the matrix: " + matrix.getRowDimension());
int ind = 0;
if (targetGoIDs != null && !targetGoIDs.isEmpty()) {
int termsWritten = 0;
for (GOTerm term : targetGoIDs) {
if (goIds.contains(term.getNumericId())) {
if (termsWritten > 0) {
out.write("\t");
}
temp[ind] = term.getGOid();
out.write(temp[ind]);
ind++;
termsWritten++;
}
}
} else if (geneIDs != null) {
int genesWritten = 0;
for (String term : geneIDs) {
if (genesWritten > 0) {
out.write("\t");
}
out.write(term);
temp[ind] = term;
ind++;
++genesWritten;
}
} else {
int termsWritten = 0;
for (GOTerm term : axis[ontology]) {
if (termsWritten > 0) {
out.write("\t");
}
out.write(term.getGOid() + "");
temp[ind] = term.getGOid();
ind++;
++termsWritten;
}
}
out.newLine();
final int n = matrix.getRowDimension();
final int m = matrix.getColumnDimension();
logger.showMessage("Printing contents: " + n + " " + m);
for (int i = 0; i < n; i++) {
out.write(temp[i]);
out.write("\t");
for (int j = 0; j < m; j++) {
out.write("" + (float) matrix.getEntry(i, j));
if (j != m - 1) {
out.write("\t");
}
}
out.newLine();
}
out.close();
logger.log("Printing complete; Output File: " + outputFileName);
System.out.println("Printing COMPLETE; Output File: " + outputFileName);
} else {
logger.showMessage("\n ERROR: the specified annotation file has not enough data to produce a semantic similarity matrix for this ontology.\n");
logger.showMessage(" This may be due to one of the following facts:\n\n");
logger.showMessage(" - There are not many annotations (possibly none) with the specified evidence codes (try adding more, especially IEA).");
logger.showMessage(" - The organism has annotations, but the subset of GO terms you selected contains no annotation (try being less restrictive).");
logger.showMessage(" - There are not many genes (possibly none) annotated to valid entries (try selecting a different organism).");
logger.showMessage(" - The organism has annotations, but the subset of genes you selected contains no associated GO terms (try being less restrictive).");
logger.showMessage(" We cannot do much for solving your problem. We recommend you to select a better organism,");
logger.showMessage(" or maybe download GOssTo in its Java version from our webpage ( http://www.paccanarolab.org/gossto/ ),");
logger.showMessage(" and tweak it a bit to cope with this annotation file.\n\n");
BufferedWriter out = new BufferedWriter(new FileWriter(outputFileName), 32768);
out.write("ERROR: the specified annotation file has not enough data to produce a semantic similarity matrix for this ontology.");
out.newLine();
out.newLine();
out.write("This may be due to one of the following facts:");
out.newLine();
out.write("- There are not many annotations (possibly none) with the specified evidence codes (try adding more, especially IEA).");
out.newLine();
out.write("- The organism has annotations, but the subset of GO terms you selected contains no annotation (try being less restrictive).");
out.newLine();
out.write("- There are not many genes (possibly none) annotated to valid entries (try selecting a different organism).");
out.newLine();
out.write("- The organism has annotations, but the subset of genes you selected contains no associated GO terms (try being less restrictive).");
out.newLine();
out.write("We cannot do much for solving your problem. We recommend you to select a better organism,");
out.newLine();
out.write("or maybe download GOssTo in its Java version from our webpage ( http://www.paccanarolab.org/gossto/ ),");
out.write(" and tweak it a bit to cope with this annotation file.");
out.close();
}
} catch (java.lang.OutOfMemoryError oome) {
logger.logAndCloseWriter("############## ERROR: Out of memory Error of type: " + oome.getMessage());
System.err.println("ERROR: Java has run out of memory. Memory Type: " + oome.getMessage());
System.exit(-1);
}
}
| public void printResultsToFile(int ontology, RealMatrix matrix, GOTerm[][] axis, String outputName, ArrayList<String> notes, ArrayList<GOTerm> targetGoIDs, String[] geneIDs) throws IOException {
validateOutputLocation(outputName);
File outputFileName;
Pattern p = Pattern.compile("\\.*");
Matcher matcher = p.matcher(outputName);
boolean addExtension = !matcher.matches();
switch (ontology) {
case 0:
if (addExtension) {
outputFileName = new File(outputName + "_BP.txt");
} else {
outputFileName = new File(outputName);
}
break;
case 1:
if (addExtension) {
outputFileName = new File(outputName + "_MF.txt");
} else {
outputFileName = new File(outputName);
}
break;
default:
if (addExtension) {
outputFileName = new File(outputName + "_CC.txt");
} else {
outputFileName = new File(outputName);
}
}
Map<Integer, Set<Integer>> goTermIds = new HashMap<Integer, Set<Integer>>();
goTermIds.put(0, getTermsForOntology(targetGoIDs, "biological_process"));
goTermIds.put(1, getTermsForOntology(targetGoIDs, "molecular_function"));
goTermIds.put(2, getTermsForOntology(targetGoIDs, "cellular_component"));
Set<Integer> goIds = goTermIds.get(ontology);
try {
if (matrix != null) {
logger.showMessage("Printing results for Ontology : " + ontologies[ontology]);
BufferedWriter out = new BufferedWriter(new FileWriter(outputFileName), 32768);
for (String note : notes) {
out.write("! ");
out.write(note);
out.newLine();
}
logger.showMessage("Notes printed");
String[] temp = new String[matrix.getRowDimension()];
logger.showMessage("Row dimension of the matrix: " + matrix.getRowDimension());
int ind = 0;
if (targetGoIDs != null && !targetGoIDs.isEmpty()) {
int termsWritten = 0;
for (GOTerm term : targetGoIDs) {
if (goIds.contains(term.getNumericId())) {
if (termsWritten > 0) {
out.write("\t");
}
temp[ind] = term.getGOid();
out.write(temp[ind]);
ind++;
termsWritten++;
}
}
} else if (geneIDs != null) {
int genesWritten = 0;
for (String term : geneIDs) {
if (genesWritten > 0) {
out.write("\t");
}
out.write(term);
temp[ind] = term;
ind++;
++genesWritten;
}
} else {
int termsWritten = 0;
for (GOTerm term : axis[ontology]) {
if (termsWritten > 0) {
out.write("\t");
}
out.write(term.getGOid() + "");
temp[ind] = term.getGOid();
ind++;
++termsWritten;
}
}
out.newLine();
final int n = matrix.getRowDimension();
final int m = matrix.getColumnDimension();
logger.showMessage("Printing contents: " + n + " " + m);
for (int i = 0; i < n; i++) {
out.write(temp[i]);
out.write("\t");
for (int j = 0; j < m; j++) {
out.write("" + (float) matrix.getEntry(i, j));
if (j != m - 1) {
out.write("\t");
}
}
out.newLine();
}
out.close();
logger.log("Printing complete; Output File: " + outputFileName);
System.out.println("Printing COMPLETE; Output File: " + outputFileName);
} else {
logger.showMessage("\n ERROR: the specified annotation file has not enough data to produce a semantic similarity matrix for this ontology.\n");
logger.showMessage(" This may be due to one of the following facts:\n\n");
logger.showMessage(" - There are not enough annotations (possibly none) with the specified evidence codes (try adding more, especially IEA).");
logger.showMessage(" - The organism has annotations, but the subset of GO terms you selected contains no annotation (try being less restrictive).");
logger.showMessage(" - There are not enough genes (possibly none) annotated to valid entries (try selecting a different organism).");
logger.showMessage(" - The organism has annotations, but the subset of genes you selected contains no associated GO terms (try being less restrictive).");
logger.showMessage(" We cannot do much for solving your problem. We recommend you to select a better organism,");
logger.showMessage(" or maybe download GOssTo in its Java version from our webpage ( http://www.paccanarolab.org/gossto/ ),");
logger.showMessage(" and tweak it a bit to cope with this annotation file.\n\n");
BufferedWriter out = new BufferedWriter(new FileWriter(outputFileName), 32768);
out.write("ERROR: the specified annotation file has not enough data to produce a semantic similarity matrix for this ontology.");
out.newLine();
out.newLine();
out.write("This may be due to one of the following facts:");
out.newLine();
out.write("- There are not enough annotations (possibly none) with the specified evidence codes (try adding more, especially IEA).");
out.newLine();
out.write("- The organism has annotations, but the subset of GO terms you selected contains no annotation (try being less restrictive).");
out.newLine();
out.write("- There are not enough genes (possibly none) annotated to valid entries (try selecting a different organism).");
out.newLine();
out.write("- The organism has annotations, but the subset of genes you selected contains no associated GO terms (try being less restrictive).");
out.newLine();
out.write("We cannot do much for solving your problem. We recommend you to select a better organism,");
out.newLine();
out.write("or maybe download GOssTo in its Java version from our webpage ( http://www.paccanarolab.org/gossto/ ),");
out.write(" and tweak it a bit to cope with this annotation file.");
out.close();
}
} catch (java.lang.OutOfMemoryError oome) {
logger.logAndCloseWriter("############## ERROR: Out of memory Error of type: " + oome.getMessage());
System.err.println("ERROR: Java has run out of memory. Memory Type: " + oome.getMessage());
System.exit(-1);
}
}
|
protected void updateAndRender(int delta) throws SlickException {
storedDelta += delta;
input.poll(width, height);
SoundStore.get().poll(delta);
if (storedDelta >= minimumLogicInterval) {
try {
if (maximumLogicInterval != 0) {
long cycles = storedDelta / maximumLogicInterval;
for (int i=0;i<cycles;i++) {
game.update(this, (int) maximumLogicInterval);
}
game.update(this, (int) (delta % maximumLogicInterval));
} else {
game.update(this, (int) storedDelta);
}
storedDelta = 0;
} catch (Throwable e) {
Log.error(e);
throw new SlickException("Game.update() failure - check the game code.");
}
}
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glLoadIdentity();
graphics.resetFont();
graphics.resetLineWidth();
graphics.setAntiAlias(false);
try {
game.render(this, graphics);
} catch (Throwable e) {
Log.error(e);
throw new SlickException("Game.render() failure - check the game code.");
}
graphics.resetTransform();
if (showFPS) {
defaultFont.drawString(10, 10, "FPS: "+recordedFPS);
}
if (targetFPS != -1) {
Display.sync2(targetFPS);
}
}
| protected void updateAndRender(int delta) throws SlickException {
storedDelta += delta;
input.poll(width, height);
SoundStore.get().poll(delta);
if (storedDelta >= minimumLogicInterval) {
try {
if (maximumLogicInterval != 0) {
long cycles = storedDelta / maximumLogicInterval;
for (int i=0;i<cycles;i++) {
game.update(this, (int) maximumLogicInterval);
}
game.update(this, (int) (delta % maximumLogicInterval));
} else {
game.update(this, (int) storedDelta);
}
storedDelta = 0;
} catch (Throwable e) {
Log.error(e);
throw new SlickException("Game.update() failure - check the game code.");
}
}
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glLoadIdentity();
graphics.resetFont();
graphics.resetLineWidth();
graphics.setAntiAlias(false);
try {
game.render(this, graphics);
} catch (Throwable e) {
Log.error(e);
throw new SlickException("Game.render() failure - check the game code.");
}
graphics.resetTransform();
if (showFPS) {
defaultFont.drawString(10, 10, "FPS: "+recordedFPS);
}
if (targetFPS != -1) {
Display.sync(targetFPS);
}
}
|
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column )
{
boldFont = getFont().deriveFont( Font.BOLD );
AssertionListEntry entry = ( AssertionListEntry )value;
String type = TestAssertionRegistry.getInstance().getAssertionTypeForName( entry.getName() );
boolean canAssert = assertable != null ? TestAssertionRegistry.getInstance().canAssert( type, assertable )
: true;
String str = entry.getName();
JLabel label = new JLabel( str );
label.setFont( boldFont );
JLabel desc = new JLabel( ( ( AssertionListEntry )value ).getDescription() );
JLabel disabledInfo = new JLabel( "Not applicable with selected Source and Property" );
boolean disable = !categoriesList.isEnabled() || !canAssert;
if( disable )
{
label.setForeground( Color.LIGHT_GRAY );
desc.setForeground( Color.LIGHT_GRAY );
disabledInfo.setForeground( Color.LIGHT_GRAY );
}
SimpleForm form = new SimpleForm();
form.addComponent( label );
if( !isHideDescriptionSelected() )
{
form.addComponent( desc );
if( disable )
{
form.addComponent( disabledInfo );
}
getAssertionsTable().setRowHeight( 60 );
}
else
{
if( disable )
{
form.addComponent( disabledInfo );
}
getAssertionsTable().setRowHeight( 40 );
}
return form.getPanel();
}
| public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column )
{
boldFont = getFont().deriveFont( Font.BOLD );
AssertionListEntry entry = ( AssertionListEntry )value;
String type = TestAssertionRegistry.getInstance().getAssertionTypeForName( entry.getName() );
boolean canAssert = assertable != null ? TestAssertionRegistry.getInstance().canAssert( type, assertable )
: true;
String str = entry.getName();
JLabel label = new JLabel( str );
label.setFont( boldFont );
JLabel desc = new JLabel( ( ( AssertionListEntry )value ).getDescription() );
JLabel disabledInfo = new JLabel( "Not applicable with selected Source and Property" );
boolean disable = !categoriesList.isEnabled() || !canAssert;
if( disable )
{
label.setForeground( Color.LIGHT_GRAY );
desc.setForeground( Color.LIGHT_GRAY );
disabledInfo.setForeground( Color.LIGHT_GRAY );
}
SimpleForm form = new SimpleForm();
form.addComponent( label );
if( !isHideDescriptionSelected() )
{
form.addComponent( desc );
if( disable )
{
form.addComponent( disabledInfo );
}
getAssertionsTable().setRowHeight( 60 );
}
else
{
if( disable )
{
form.addComponent( disabledInfo );
}
getAssertionsTable().setRowHeight( 40 );
}
if( isSelected )
{
form.getPanel().setBackground( Color.LIGHT_GRAY );
}
else
{
form.getPanel().setBackground( Color.WHITE );
}
return form.getPanel();
}
|
public void init(Base red, Base blue) {
for (int img_x = 0; img_x < map_img.getWidth(); img_x++) {
List<Ground> row = new ArrayList<Ground>(width);
for (int img_y = 0; img_y < map_img.getWidth(); img_y++) {
int pixel = map_img.getRGB(img_y, img_x);
Ground ground = Ground.Void;
switch (pixel) {
case 0xff3a9d3a:
ground = Ground.Grass;
break;
case 0xff375954:
ground = Ground.Swamp;
break;
case 0xffe8d35e:
ground = Ground.Sand;
break;
case 0xff323f05:
ground = Ground.Forest;
break;
case 0xff0000ff:
ground = Ground.Grass;
blue.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2));
break;
case 0xff787878:
ground = Ground.Rocks;
break;
case 0xffffffff:
ground = Ground.Grass;
break;
case 0xffff0000:
ground = Ground.Grass;
red.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2));
break;
case 0xff3674db:
ground = Ground.Water;
break;
default:
throw new RuntimeException("Map broken. Unknown color: "+Integer.toHexString(pixel));
}
row.add(img_y, ground);
for (int i = 0; i < TILE_SIZE; i++) {
for (int j = 0; j < TILE_SIZE; j++) {
offscreen.setRGB(img_x*TILE_SIZE+i, img_y*TILE_SIZE+j, pixel);
}
}
}
tiles.add(row);
}
}
| public void init(Base red, Base blue) {
for (int img_x = 0; img_x < map_img.getWidth(); img_x++) {
List<Ground> row = new ArrayList<Ground>(width);
for (int img_y = 0; img_y < map_img.getWidth(); img_y++) {
int pixel = map_img.getRGB(img_x, img_y);
Ground ground = Ground.Void;
switch (pixel) {
case 0xff3a9d3a:
ground = Ground.Grass;
break;
case 0xff375954:
ground = Ground.Swamp;
break;
case 0xffe8d35e:
ground = Ground.Sand;
break;
case 0xff323f05:
ground = Ground.Forest;
break;
case 0xff0000ff:
ground = Ground.Grass;
blue.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2));
break;
case 0xff787878:
ground = Ground.Rocks;
break;
case 0xffffffff:
ground = Ground.Grass;
break;
case 0xffff0000:
ground = Ground.Grass;
red.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2));
break;
case 0xff3674db:
ground = Ground.Water;
break;
default:
throw new RuntimeException("Map broken. Unknown color: "+Integer.toHexString(pixel));
}
row.add(img_y, ground);
for (int i = 0; i < TILE_SIZE; i++) {
for (int j = 0; j < TILE_SIZE; j++) {
offscreen.setRGB(img_x*TILE_SIZE+i, img_y*TILE_SIZE+j, pixel);
}
}
}
tiles.add(row);
}
}
|
public static void doNewPage(String actionz, String otherUrlId, String otherLanguage) {
String urlId = otherUrlId;
Page page = null;
PageRef pageRef = null;
String tagsString = params.get("pageReference.tags");
if (urlId != null && !urlId.equals("")) {
page = Page.getPageByUrlId(urlId);
}
if (page != null) {
pageRef = page.pageReference;
} else {
pageRef = PageController.doNewPageRef("edit", otherUrlId, otherLanguage);
}
urlId = params.get("page.urlId");
Set<Tag> tags = new TreeSet<Tag>();
if (tagsString != null && !tagsString.isEmpty()) {
for (String tag : Arrays.asList(tagsString.split(","))) {
tags.add(Tag.findOrCreateByName(tag));
}
}
pageRef.tags = tags;
if (!actionz.equals("edit")) {
page = new Page();
}
page.pageReference = pageRef;
page.urlId = urlId;
page.title = params.get("page.title");
page.content = params.get("page.content");
page.language = params.get("page.language", Locale.class);
page.published = (params.get("page.published") == null) ? Boolean.FALSE : Boolean.TRUE;
validation.valid(page);
if (Validation.hasErrors()) {
params.flash();
Validation.keep();
if (actionz.equals("edit")) {
PageController.edit(otherUrlId, otherLanguage);
} else if (actionz.equals("translate")) {
PageController.translate(otherUrlId, otherLanguage);
} else {
PageController.newPage();
}
}
page.pageReference.save();
page.save();
if (page.published) {
PageViewer.page(urlId);
} else {
PageViewer.index();
}
}
| public static void doNewPage(String actionz, String otherUrlId, String otherLanguage) {
String urlId = otherUrlId;
Page page = null;
PageRef pageRef = null;
String tagsString = params.get("pageReference.tags");
if (urlId != null && !urlId.equals("")) {
page = Page.getPageByUrlId(urlId);
}
if (page != null) {
pageRef = page.pageReference;
} else {
pageRef = PageController.doNewPageRef(actionz, otherUrlId, otherLanguage);
}
urlId = params.get("page.urlId");
Set<Tag> tags = new TreeSet<Tag>();
if (tagsString != null && !tagsString.isEmpty()) {
for (String tag : Arrays.asList(tagsString.split(","))) {
tags.add(Tag.findOrCreateByName(tag));
}
}
pageRef.tags = tags;
if (!actionz.equals("edit")) {
page = new Page();
}
page.pageReference = pageRef;
page.urlId = urlId;
page.title = params.get("page.title");
page.content = params.get("page.content");
page.language = params.get("page.language", Locale.class);
page.published = (params.get("page.published") == null) ? Boolean.FALSE : Boolean.TRUE;
validation.valid(page);
if (Validation.hasErrors()) {
params.flash();
Validation.keep();
if (actionz.equals("edit")) {
PageController.edit(otherUrlId, otherLanguage);
} else if (actionz.equals("translate")) {
PageController.translate(otherUrlId, otherLanguage);
} else {
PageController.newPage();
}
}
page.pageReference.save();
page.save();
if (page.published) {
PageViewer.page(urlId);
} else {
PageViewer.index();
}
}
|
public void onEnable()
{
p = this;
getServer().getPluginManager().registerEvents(new CommonMobListener(), this);
getConfig();
boolean somethingEnabled = false;
for (int i = 0; i < Component.values().length; ++i)
{
if (Component.values()[i].i().initializeConfig())
{
somethingEnabled = true;
}
}
if (!somethingEnabled)
{
getLogger().warning("No components enabled :(");
return;
}
biomeSpecificMobs = false;
biomeSpecificMobs = getConfig().getBoolean("BiomeSpecificMobs", biomeSpecificMobs);
versionCheckEnabled = getConfig().getBoolean("EnableVersionCheck", true);
AbstractConfig.set(getConfig(), "EnableVersionCheck", versionCheckEnabled);
autoUpdateEnabled = getConfig().getBoolean("EnableAutoUpdater", false);
AbstractConfig.set(getConfig(), "EnableAutoUpdater", autoUpdateEnabled);
AbstractConfig.copyHeader(getConfig(), "Config_Header.txt", "Global Config\n"
+ "\nValid EntityTypes:\n" + ExtendedEntityType.getExtendedEntityList());
integration.integrate();
Component.enableComponents();
getCommand("mm").setExecutor(new MMCommandListener());
AbstractConfig.set(getConfig(), "Integration", getConfig().getConfigurationSection("Integration"));
AbstractConfig.set(getConfig(), "Version", getDescription().getVersion());
saveConfig();
if (versionCheckEnabled || autoUpdateEnabled)
{
Updater.UpdateType type;
if (!autoUpdateEnabled)
{
type = Updater.UpdateType.NO_DOWNLOAD;
}
else
{
type = Updater.UpdateType.DEFAULT;
}
updater = new Updater(this, "mobmanager", this.getFile(), type, true);
}
else
{
updater = null;
}
startMetrics();
}
| public void onEnable()
{
p = this;
getServer().getPluginManager().registerEvents(new CommonMobListener(), this);
getConfig();
boolean somethingEnabled = false;
for (int i = 0; i < Component.values().length; ++i)
{
if (Component.values()[i].i().initializeConfig())
{
somethingEnabled = true;
}
}
if (!somethingEnabled)
{
getLogger().warning("No components enabled :(");
return;
}
biomeSpecificMobs = false;
biomeSpecificMobs = getConfig().getBoolean("BiomeSpecificMobs", biomeSpecificMobs);
versionCheckEnabled = getConfig().getBoolean("EnableVersionCheck", true);
AbstractConfig.set(getConfig(), "EnableVersionCheck", versionCheckEnabled);
autoUpdateEnabled = getConfig().getBoolean("EnableAutoUpdater", false);
AbstractConfig.set(getConfig(), "EnableAutoUpdater", autoUpdateEnabled);
AbstractConfig.copyHeader(getConfig(), "Config_Header.txt", "Global Config\n"
+ "\nValid EntityTypes:\n" + ExtendedEntityType.getExtendedEntityList());
integration.integrate();
Component.enableComponents();
getCommand("mm").setExecutor(new MMCommandListener());
AbstractConfig.set(getConfig(), "Integration", getConfig().getConfigurationSection("Integration"));
AbstractConfig.set(getConfig(), "Version", getDescription().getVersion());
saveConfig();
if (versionCheckEnabled || autoUpdateEnabled)
{
Updater.UpdateType type;
if (!autoUpdateEnabled)
{
type = Updater.UpdateType.NO_DOWNLOAD;
}
else
{
type = Updater.UpdateType.DEFAULT;
}
updater = new Updater(this, 48713, this.getFile(), type, true);
}
else
{
updater = null;
}
startMetrics();
}
|
public double calculateRate(Temperature T, Pressure P) {
int index1 = -1; int index2 = -1;
for (int i = 0; i < pressures.length - 1; i++) {
if (pressures[i].getBar() <= P.getBar() && P.getBar() <= pressures[i+1].getBar()) {
index1 = i; index2 = i + 1;
}
}
if (P.getPa() < pressures[0].getPa())
{
Logger.warning(String.format("Tried to evaluate rate coefficient at P=%s Atm, which is below minimum for this PLOG rate.",P.getAtm()));
Logger.warning(String.format("Using rate for minimum %s Atm instead", pressures[0].getAtm() ));
return kinetics[0].calculateRate(T);
}
if (P.getPa() > pressures[pressures.length].getPa())
{
Logger.warning(String.format("Tried to evaluate rate coefficient at P=%s Atm, which is above maximum for this PLOG rate.",P.getAtm()));
Logger.warning(String.format("Using rate for maximum %s Atm instead", pressures[pressures.length].getAtm() ));
return kinetics[pressures.length].calculateRate(T);
}
double logk1 = Math.log10(kinetics[index1].calculateRate(T));
double logk2 = Math.log10(kinetics[index2].calculateRate(T));
double logP0 = Math.log10(P.getBar());
double logP1 = Math.log10(pressures[index1].getBar());
double logP2 = Math.log10(pressures[index2].getBar());
double logk0 = logk1 + (logk2 - logk1) / (logP2 - logP1) * (logP0 - logP1);
return Math.pow(10, logk0);
}
| public double calculateRate(Temperature T, Pressure P) {
int index1 = -1; int index2 = -1;
for (int i = 0; i < pressures.length - 1; i++) {
if (pressures[i].getBar() <= P.getBar() && P.getBar() <= pressures[i+1].getBar()) {
index1 = i;
index2 = i + 1;
break;
}
}
if (P.getPa() < pressures[0].getPa())
{
Logger.warning(String.format("Tried to evaluate rate coefficient at P=%s Atm, which is below minimum for this PLOG rate.",P.getAtm()));
Logger.warning(String.format("Using rate for minimum %s Atm instead", pressures[0].getAtm() ));
return kinetics[0].calculateRate(T);
}
if (P.getPa() > pressures[pressures.length-1].getPa())
{
Logger.warning(String.format("Tried to evaluate rate coefficient at P=%s Atm, which is above maximum for this PLOG rate.",P.getAtm()));
Logger.warning(String.format("Using rate for maximum %s Atm instead", pressures[pressures.length-1].getAtm() ));
return kinetics[pressures.length].calculateRate(T);
}
double logk1 = Math.log10(kinetics[index1].calculateRate(T));
double logk2 = Math.log10(kinetics[index2].calculateRate(T));
double logP0 = Math.log10(P.getBar());
double logP1 = Math.log10(pressures[index1].getBar());
double logP2 = Math.log10(pressures[index2].getBar());
double logk0 = logk1 + (logk2 - logk1) / (logP2 - logP1) * (logP0 - logP1);
return Math.pow(10, logk0);
}
|
public static ImmutableInstruction20t of(Instruction20t instruction) {
if (instruction instanceof ImmutableInstruction20t) {
return (ImmutableInstruction20t)instruction;
}
return new ImmutableInstruction20t(
instruction.getOpcode(),
(byte)instruction.getCodeOffset());
}
| public static ImmutableInstruction20t of(Instruction20t instruction) {
if (instruction instanceof ImmutableInstruction20t) {
return (ImmutableInstruction20t)instruction;
}
return new ImmutableInstruction20t(
instruction.getOpcode(),
instruction.getCodeOffset());
}
|
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result = null;
mTransferWasRequested = false;
if (!mLocalFile.isDown()) {
requestForDownload(mLocalFile);
result = new RemoteOperationResult(ResultCode.OK);
} else {
if (mServerFile == null) {
String remotePath = mLocalFile.getRemotePath();
ReadRemoteFileOperation operation = new ReadRemoteFileOperation(remotePath);
result = operation.execute(client);
if (result.isSuccess()){
mServerFile = FileStorageUtils.fillOCFile(result.getData().get(0));
mServerFile.setLastSyncDateForProperties(System.currentTimeMillis());
}
}
if (result.isSuccess()) {
boolean serverChanged = false;
serverChanged = (mServerFile.getModificationTimestamp() != mLocalFile.getModificationTimestampAtLastSyncForData());
boolean localChanged = (mLocalFile.getLocalModificationTimestamp() > mLocalFile.getLastSyncDateForData());
if (localChanged && serverChanged) {
result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
} else if (localChanged) {
if (mSyncFileContents) {
requestForUpload(mLocalFile);
} else {
}
result = new RemoteOperationResult(ResultCode.OK);
} else if (serverChanged) {
if (mSyncFileContents) {
requestForDownload(mLocalFile);
} else {
mServerFile.setKeepInSync(mLocalFile.keepInSync());
mServerFile.setLastSyncDateForData(mLocalFile.getLastSyncDateForData());
mServerFile.setStoragePath(mLocalFile.getStoragePath());
mServerFile.setParentId(mLocalFile.getParentId());
mStorageManager.saveFile(mServerFile);
}
result = new RemoteOperationResult(ResultCode.OK);
} else {
result = new RemoteOperationResult(ResultCode.OK);
}
}
}
Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() + ": " + result.getLogMessage());
return result;
}
private void requestForUpload(OCFile file) {
Intent i = new Intent(mContext, FileUploader.class);
i.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
i.putExtra(FileUploader.KEY_FILE, file);
i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
i.putExtra(FileUploader.KEY_FORCE_OVERWRITE, true);
mContext.startService(i);
mTransferWasRequested = true;
}
private void requestForDownload(OCFile file) {
Intent i = new Intent(mContext, FileDownloader.class);
i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
i.putExtra(FileDownloader.EXTRA_FILE, file);
mContext.startService(i);
mTransferWasRequested = true;
}
public boolean transferWasRequested() {
return mTransferWasRequested;
}
public OCFile getLocalFile() {
return mLocalFile;
}
}
| protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result = null;
mTransferWasRequested = false;
if (!mLocalFile.isDown()) {
requestForDownload(mLocalFile);
result = new RemoteOperationResult(ResultCode.OK);
} else {
if (mServerFile == null) {
String remotePath = mLocalFile.getRemotePath();
ReadRemoteFileOperation operation = new ReadRemoteFileOperation(remotePath);
result = operation.execute(client);
if (result.isSuccess()){
mServerFile = FileStorageUtils.fillOCFile(result.getData().get(0));
mServerFile.setLastSyncDateForProperties(System.currentTimeMillis());
}
}
if (mServerFile != null) {
boolean serverChanged = false;
serverChanged = (mServerFile.getModificationTimestamp() != mLocalFile.getModificationTimestampAtLastSyncForData());
boolean localChanged = (mLocalFile.getLocalModificationTimestamp() > mLocalFile.getLastSyncDateForData());
if (localChanged && serverChanged) {
result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
} else if (localChanged) {
if (mSyncFileContents) {
requestForUpload(mLocalFile);
} else {
}
result = new RemoteOperationResult(ResultCode.OK);
} else if (serverChanged) {
if (mSyncFileContents) {
requestForDownload(mLocalFile);
} else {
mServerFile.setKeepInSync(mLocalFile.keepInSync());
mServerFile.setLastSyncDateForData(mLocalFile.getLastSyncDateForData());
mServerFile.setStoragePath(mLocalFile.getStoragePath());
mServerFile.setParentId(mLocalFile.getParentId());
mStorageManager.saveFile(mServerFile);
}
result = new RemoteOperationResult(ResultCode.OK);
} else {
result = new RemoteOperationResult(ResultCode.OK);
}
}
}
Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() + ": " + result.getLogMessage());
return result;
}
private void requestForUpload(OCFile file) {
Intent i = new Intent(mContext, FileUploader.class);
i.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
i.putExtra(FileUploader.KEY_FILE, file);
i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
i.putExtra(FileUploader.KEY_FORCE_OVERWRITE, true);
mContext.startService(i);
mTransferWasRequested = true;
}
private void requestForDownload(OCFile file) {
Intent i = new Intent(mContext, FileDownloader.class);
i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
i.putExtra(FileDownloader.EXTRA_FILE, file);
mContext.startService(i);
mTransferWasRequested = true;
}
public boolean transferWasRequested() {
return mTransferWasRequested;
}
public OCFile getLocalFile() {
return mLocalFile;
}
}
|
public Event convert(Event event) {
if (event == null)
throw new InvalidParameterException("Event cannot be null");
IResource res = event.getResource();
if (res == null)
return event;
ISkeleton skel = res.getSkeleton();
if (!(skel == null)) {
return event;
}
if (!(skel instanceof GenericSkeleton)) {
return event;
}
if (res instanceof IReferenceable) {
if (((IReferenceable) res).isReferent()) {
writer.addToReferents(event);
return event;
}
}
MultiEvent me = new MultiEvent();
processResource(res, me);
switch (event.getEventType()) {
case START_DOCUMENT:
StartDocument sd = (StartDocument) res;
sd.setMultilingual(false);
case END_DOCUMENT:
case START_SUBDOCUMENT:
case END_SUBDOCUMENT:
case START_GROUP:
case END_GROUP:
res.setSkeleton(null);
me.addEvent(event, 0);
break;
case TEXT_UNIT:
case DOCUMENT_PART:
break;
default:
return event;
}
return new Event(EventType.MULTI_EVENT, packMultiEvent(me));
}
| public Event convert(Event event) {
if (event == null)
throw new InvalidParameterException("Event cannot be null");
IResource res = event.getResource();
if (res == null)
return event;
ISkeleton skel = res.getSkeleton();
if (skel == null) {
return event;
}
if (!(skel instanceof GenericSkeleton)) {
return event;
}
if (res instanceof IReferenceable) {
if (((IReferenceable) res).isReferent()) {
writer.addToReferents(event);
return event;
}
}
MultiEvent me = new MultiEvent();
processResource(res, me);
switch (event.getEventType()) {
case START_DOCUMENT:
StartDocument sd = (StartDocument) res;
sd.setMultilingual(false);
case END_DOCUMENT:
case START_SUBDOCUMENT:
case END_SUBDOCUMENT:
case START_GROUP:
case END_GROUP:
res.setSkeleton(null);
me.addEvent(event, 0);
break;
case TEXT_UNIT:
case DOCUMENT_PART:
break;
default:
return event;
}
return new Event(EventType.MULTI_EVENT, packMultiEvent(me));
}
|
public String toString(){
enemyCountList = new ArrayList<Pair<String, Integer>>();
Pair<String, Integer> tempPair = new Pair<String, Integer>();
for (int i = 0; i < waveEnemyList.size(); i++){
if (i == 0){
tempPair.key = waveEnemyList.get(i).type;
tempPair.value = 1;
enemyCountList.add(tempPair.clone());
}
if (!typeExists(i)){
tempPair.key = waveEnemyList.get(i).type;
tempPair.value = 1;
enemyCountList.add(tempPair.clone());
}
}
String printedLine = "";
printedLine += ("Time=" + Integer.toString(time));
for (int i = 0; i < enemyCountList.size(); i++){
printedLine += (" " + enemyCountList.get(i));
}
printedLine += ("\n");
for(int i = 0; i < waveEnemyList.size(); i++){
printedLine += waveEnemyList.get(i);
}
return printedLine;
}
| public String toString(){
enemyCountList = new ArrayList<Pair<String, Integer>>();
Pair<String, Integer> tempPair = new Pair<String, Integer>();
for (int i = 0; i < waveEnemyList.size(); i++){
if (i == 0){
tempPair.key = waveEnemyList.get(i).type;
tempPair.value = 1;
enemyCountList.add(tempPair.clone());
}
if (!typeExists(i)){
tempPair.key = waveEnemyList.get(i).type;
tempPair.value = 1;
enemyCountList.add(tempPair.clone());
}
}
String printedLine = "";
printedLine += ("Time=" + Integer.toString(time));
for (int i = 0; i < enemyCountList.size(); i++){
enemyCountList.get(i).value--;
printedLine += (" " + (enemyCountList.get(i)));
}
printedLine += ("\n");
for(int i = 0; i < waveEnemyList.size(); i++){
printedLine += waveEnemyList.get(i);
}
return printedLine;
}
|
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equals("odditem")) {
if (sender.hasPermission("odditem.alias")) {
switch (args.length) {
case 0:
if (sender instanceof Player) {
ItemStack itemStack = ((Player) sender).getItemInHand();
ItemStack temp = new ItemStack(itemStack.getTypeId(), itemStack.getDurability());
if (temp.getTypeId() > 255)
itemStack.setDurability((short) 0);
sender.sendMessage(OddItem.getAliases(temp).toString());
return true;
}
break;
case 1:
try {
sender.sendMessage(OddItem.getAliases(args[0]).toString());
} catch (IllegalArgumentException e) {
sender.sendMessage("[OddItem] No such alias. Similar: " + e.getMessage());
}
return true;
}
} else {
sender.sendMessage("DENIED");
}
} else if (command.getName().equals("odditeminfo")) {
if (sender.hasPermission("odditem.info")) {
sender.sendMessage("[OddItem] " + OddItem.items.itemCount() + " items with " + OddItem.items.aliasCount() + " aliases");
sender.sendMessage("[OddItem] " + OddItem.groups.groupCount() + " groups with " + OddItem.groups.aliasCount() + " aliases");
} else {
sender.sendMessage("DENIED");
}
return true;
} else if (command.getName().equals("odditemreload")) {
if (sender.hasPermission("odditem.reload")) {
sender.sendMessage("[OddItem] Reloading...");
OddItem.clear();
new OddItemConfiguration(oddItemBase).configure();
} else {
sender.sendMessage("DENIED");
}
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equals("odditem")) {
if (sender.hasPermission("odditem.alias")) {
switch (args.length) {
case 0:
if (sender instanceof Player) {
ItemStack itemStack = ((Player) sender).getItemInHand();
ItemStack temp = new ItemStack(itemStack.getTypeId(), itemStack.getDurability());
if (temp.getTypeId() > 255)
temp.setDurability((short) 0);
sender.sendMessage(OddItem.getAliases(temp).toString());
return true;
}
break;
case 1:
try {
sender.sendMessage(OddItem.getAliases(args[0]).toString());
} catch (IllegalArgumentException e) {
sender.sendMessage("[OddItem] No such alias. Similar: " + e.getMessage());
}
return true;
}
} else {
sender.sendMessage("DENIED");
}
} else if (command.getName().equals("odditeminfo")) {
if (sender.hasPermission("odditem.info")) {
sender.sendMessage("[OddItem] " + OddItem.items.itemCount() + " items with " + OddItem.items.aliasCount() + " aliases");
sender.sendMessage("[OddItem] " + OddItem.groups.groupCount() + " groups with " + OddItem.groups.aliasCount() + " aliases");
} else {
sender.sendMessage("DENIED");
}
return true;
} else if (command.getName().equals("odditemreload")) {
if (sender.hasPermission("odditem.reload")) {
sender.sendMessage("[OddItem] Reloading...");
OddItem.clear();
new OddItemConfiguration(oddItemBase).configure();
} else {
sender.sendMessage("DENIED");
}
return true;
}
return false;
}
|
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final Switchboard sb = (Switchboard) env;
sb.localSearchLastAccess = System.currentTimeMillis();
final boolean searchAllowed = sb.getConfigBool("publicSearchpage", true) || sb.verifyAuthentication(header, false);
final boolean authenticated = sb.adminAuthenticated(header) >= 2;
int display = (post == null) ? 0 : post.getInt("display", 0);
if (!authenticated) display = 2;
final boolean browserPopUpTrigger = sb.getConfig(SwitchboardConstants.BROWSER_POP_UP_TRIGGER, "true").equals("true");
if (browserPopUpTrigger) {
final String browserPopUpPage = sb.getConfig(SwitchboardConstants.BROWSER_POP_UP_PAGE, "ConfigBasic.html");
if (browserPopUpPage.startsWith("index") || browserPopUpPage.startsWith("yacysearch")) display = 2;
}
String promoteSearchPageGreeting = env.getConfig(SwitchboardConstants.GREETING, "");
if (env.getConfigBool(SwitchboardConstants.GREETING_NETWORK_NAME, false)) promoteSearchPageGreeting = env.getConfig("network.unit.description", "");
final String client = header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP);
String originalquerystring = (post == null) ? "" : post.get("query", "").trim();
String querystring = originalquerystring.replace('+', ' ');
boolean fetchSnippets = (post != null && post.get("verify", "false").equals("true"));
final serverObjects prop = new serverObjects();
Segment indexSegment = null;
if (post != null && post.containsKey("segment")) {
String segmentName = post.get("segment");
if (sb.indexSegments.segmentExist(segmentName)) {
indexSegment = sb.indexSegments.segment(segmentName);
}
} else {
indexSegment = sb.indexSegments.segment(Segments.Process.PUBLIC);
}
prop.put("promoteSearchPageGreeting", promoteSearchPageGreeting);
prop.put("promoteSearchPageGreeting.homepage", sb.getConfig(SwitchboardConstants.GREETING_HOMEPAGE, ""));
prop.put("promoteSearchPageGreeting.smallImage", sb.getConfig(SwitchboardConstants.GREETING_SMALL_IMAGE, ""));
if (post == null || indexSegment == null || env == null || !searchAllowed) {
prop.put("searchagain", "0");
prop.put("display", display);
prop.put("former", "");
prop.put("count", "10");
prop.put("offset", "0");
prop.put("resource", "global");
prop.put("urlmaskfilter", (post == null) ? ".*" : post.get("urlmaskfilter", ".*"));
prop.put("prefermaskfilter", (post == null) ? "" : post.get("prefermaskfilter", ""));
prop.put("tenant", (post == null) ? "" : post.get("tenant", ""));
prop.put("indexof", "off");
prop.put("constraint", "");
prop.put("cat", "href");
prop.put("depth", "0");
prop.put("verify", (post == null) ? "true" : post.get("verify", "true"));
prop.put("contentdom", "text");
prop.put("contentdomCheckText", "1");
prop.put("contentdomCheckAudio", "0");
prop.put("contentdomCheckVideo", "0");
prop.put("contentdomCheckImage", "0");
prop.put("contentdomCheckApp", "0");
prop.put("excluded", "0");
prop.put("results", "");
prop.put("resultTable", "0");
prop.put("num-results", searchAllowed ? "0" : "4");
prop.put("num-results_totalcount", 0);
prop.put("num-results_offset", 0);
prop.put("num-results_itemsPerPage", 10);
prop.put("geoinfo", "0");
prop.put("rss_queryenc", "");
prop.put("meanCount", 5);
return prop;
}
if (post.containsKey("callback")) {
final String jsonp = post.get("callback")+ "([";
prop.put("jsonp-start", jsonp);
prop.put("jsonp-end", "])");
} else {
prop.put("jsonp-start", "");
prop.put("jsonp-end", "");
}
boolean newsearch = post.hasValue("query") && post.hasValue("former") && !post.get("query","").equalsIgnoreCase(post.get("former",""));
int itemsPerPage = Math.min((authenticated) ? (fetchSnippets ? 100 : 1000) : (fetchSnippets ? 10 : 100), post.getInt("maximumRecords", post.getInt("count", 10)));
int offset = (newsearch) ? 0 : post.getInt("startRecord", post.getInt("offset", 0));
boolean global = post.get("resource", "local").equals("global");
final boolean indexof = (post != null && post.get("indexof","").equals("on"));
String urlmask = null;
String originalUrlMask = null;
if (post.containsKey("urlmask") && post.get("urlmask").equals("no")) {
originalUrlMask = ".*";
} else if (!newsearch && post.containsKey("urlmaskfilter")) {
originalUrlMask = post.get("urlmaskfilter", ".*");
} else {
originalUrlMask = ".*";
}
String prefermask = (post == null) ? "" : post.get("prefermaskfilter", "");
if (prefermask.length() > 0 && prefermask.indexOf(".*") < 0) prefermask = ".*" + prefermask + ".*";
Bitfield constraint = (post != null && post.containsKey("constraint") && post.get("constraint", "").length() > 0) ? new Bitfield(4, post.get("constraint", "______")) : null;
if (indexof) {
constraint = new Bitfield(4);
constraint.set(Condenser.flag_cat_indexof, true);
}
final boolean indexReceiveGranted = sb.getConfigBool(SwitchboardConstants.INDEX_RECEIVE_ALLOW, true) ||
sb.getConfigBool(SwitchboardConstants.INDEX_RECEIVE_AUTODISABLED, true);
global = global && indexReceiveGranted;
final boolean clustersearch = sb.isRobinsonMode() &&
(sb.getConfig("cluster.mode", "").equals("privatecluster") ||
sb.getConfig("cluster.mode", "").equals("publiccluster"));
if (clustersearch) global = true;
if (!global) {
if (authenticated) {
sb.searchQueriesRobinsonFromLocal++;
} else {
sb.searchQueriesRobinsonFromRemote++;
}
}
final ContentDomain contentdom = ContentDomain.contentdomParser(post == null ? "text" : post.get("contentdom", "text"));
if ((contentdom != ContentDomain.TEXT) && (itemsPerPage <= 32)) itemsPerPage = 64;
TreeSet<Long> trackerHandles = sb.localSearchTracker.get(client);
if (trackerHandles == null) trackerHandles = new TreeSet<Long>();
boolean block = false;
if (Domains.matchesList(client, sb.networkBlacklist)) {
global = false;
fetchSnippets = false;
block = true;
Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: BLACKLISTED CLIENT FROM " + client + " gets no permission to search");
} else if (Domains.matchesList(client, sb.networkWhitelist)) {
Log.logInfo("LOCAL_SEARCH", "ACCECC CONTROL: WHITELISTED CLIENT FROM " + client + " gets no search restrictions");
} else if (global || fetchSnippets) {
synchronized (trackerHandles) {
int accInOneSecond = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 1000)).size();
int accInThreeSeconds = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 3000)).size();
int accInOneMinute = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 60000)).size();
int accInTenMinutes = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 600000)).size();
if (accInTenMinutes > 600) {
global = false;
fetchSnippets = false;
block = true;
Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInTenMinutes + " searches in ten minutes, fully blocked (no results generated)");
} else if (accInOneMinute > 200) {
global = false;
fetchSnippets = false;
block = true;
Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInOneMinute + " searches in one minute, fully blocked (no results generated)");
} else if (accInThreeSeconds > 1) {
global = false;
fetchSnippets = false;
Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInThreeSeconds + " searches in three seconds, blocked global search and snippets");
} else if (accInOneSecond > 2) {
global = false;
fetchSnippets = false;
Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInOneSecond + " searches in one second, blocked global search and snippets");
}
}
}
if ((!block) && (post == null || post.get("cat", "href").equals("href"))) {
if (!MemoryControl.request(8000000L, false)) {
indexSegment.urlMetadata().clearCache();
SearchEventCache.cleanupEvents(true);
}
final RankingProfile ranking = sb.getRanking();
if (querystring.indexOf("NEAR") >= 0) {
querystring = querystring.replace("NEAR", "");
ranking.coeff_worddistance = RankingProfile.COEFF_MAX;
}
if (querystring.indexOf("RECENT") >= 0) {
querystring = querystring.replace("RECENT", "");
ranking.coeff_date = RankingProfile.COEFF_MAX;
}
int lrp = querystring.indexOf("LANGUAGE:");
String lr = "";
if (lrp >= 0) {
if (querystring.length() >= (lrp + 11))
lr = querystring.substring(lrp + 9, lrp + 11);
querystring = querystring.replace("LANGUAGE:" + lr, "");
lr = lr.toLowerCase();
}
int inurl = querystring.indexOf("inurl:");
if (inurl >= 0) {
int ftb = querystring.indexOf(' ', inurl);
if (ftb == -1) ftb = querystring.length();
String urlstr = querystring.substring(inurl + 6, ftb);
querystring = querystring.replace("inurl:" + urlstr, "");
if(urlstr.length() > 0) urlmask = ".*" + urlstr + ".*";
}
int filetype = querystring.indexOf("filetype:");
if (filetype >= 0) {
int ftb = querystring.indexOf(' ', filetype);
if (ftb == -1) ftb = querystring.length();
String ft = querystring.substring(filetype + 9, ftb);
querystring = querystring.replace("filetype:" + ft, "");
while (ft.length() > 0 && ft.charAt(0) == '.') ft = ft.substring(1);
if(ft.length() > 0) {
if (urlmask == null) {
urlmask = ".*\\." + ft;
} else {
urlmask = urlmask + ".*\\." + ft;
}
}
}
String tenant = null;
if (post.containsKey("tenant")) {
tenant = post.get("tenant");
if (tenant != null && tenant.length() == 0) tenant = null;
if (tenant != null) {
if (urlmask == null) urlmask = ".*" + tenant + ".*"; else urlmask = ".*" + tenant + urlmask;
}
}
int site = querystring.indexOf("site:");
String sitehash = null;
if (site >= 0) {
int ftb = querystring.indexOf(' ', site);
if (ftb == -1) ftb = querystring.length();
String domain = querystring.substring(site + 5, ftb);
querystring = querystring.replace("site:" + domain, "");
while (domain.length() > 0 && domain.charAt(0) == '.') domain = domain.substring(1);
while (domain.endsWith(".")) domain = domain.substring(0, domain.length() - 1);
sitehash = DigestURI.domhash(domain);
}
int authori = querystring.indexOf("author:");
String authorhash = null;
if (authori >= 0) {
boolean quotes = false;
if (querystring.charAt(authori + 7) == (char) 39) {
quotes = true;
}
String author;
if (quotes) {
int ftb = querystring.indexOf((char) 39, authori + 8);
if (ftb == -1) ftb = querystring.length() + 1;
author = querystring.substring(authori + 8, ftb);
querystring = querystring.replace("author:'" + author + "'", "");
} else {
int ftb = querystring.indexOf(' ', authori);
if (ftb == -1) ftb = querystring.length();
author = querystring.substring(authori + 7, ftb);
querystring = querystring.replace("author:" + author, "");
}
authorhash = new String(Word.word2hash(author));
}
int tld = querystring.indexOf("tld:");
if (tld >= 0) {
int ftb = querystring.indexOf(' ', tld);
if (ftb == -1) ftb = querystring.length();
String domain = querystring.substring(tld + 4, ftb);
querystring = querystring.replace("tld:" + domain, "");
while (domain.length() > 0 && domain.charAt(0) == '.') domain = domain.substring(1);
if (domain.indexOf('.') < 0) domain = "\\." + domain;
if (domain.length() > 0) {
if (urlmask == null) {
urlmask = "[a-zA-Z]*://[^/]*" + domain + "/.*";
} else {
urlmask = "[a-zA-Z]*://[^/]*" + domain + "/.*" + urlmask;
}
}
}
if (urlmask == null || urlmask.length() == 0) urlmask = originalUrlMask;
String language = (post == null) ? lr : post.get("lr", lr);
if (language.startsWith("lang_")) language = language.substring(5);
if (!ISO639.exists(language)) {
String agent = header.get(HeaderFramework.ACCEPT_LANGUAGE);
if (agent == null) agent = System.getProperty("user.language");
language = (agent == null) ? "en" : ISO639.userAgentLanguageDetection(agent);
if (language == null) language = "en";
}
String navigation = (post == null) ? "" : post.get("nav", "");
final TreeSet<String>[] query = QueryParams.cleanQuery(querystring.trim());
int maxDistance = (querystring.indexOf('"') >= 0) ? maxDistance = query.length - 1 : Integer.MAX_VALUE;
final TreeSet<String> filtered = SetTools.joinConstructive(query[0], Switchboard.stopwords);
if (!filtered.isEmpty()) {
SetTools.excludeDestructive(query[0], Switchboard.stopwords);
}
if (post != null && post.containsKey("deleteref")) try {
if (!sb.verifyAuthentication(header, true)) {
prop.put("AUTHENTICATE", "admin log-in");
return prop;
}
final String delHash = post.get("deleteref", "");
indexSegment.termIndex().remove(Word.words2hashesHandles(query[0]), delHash.getBytes());
final HashMap<String, String> map = new HashMap<String, String>();
map.put("urlhash", delHash);
map.put("vote", "negative");
map.put("refid", "");
sb.peers.newsPool.publishMyNews(new yacyNewsDB.Record(sb.peers.mySeed(), yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD, map));
} catch (IOException e) {
Log.logException(e);
}
if (post != null && post.containsKey("recommendref")) {
if (!sb.verifyAuthentication(header, true)) {
prop.put("AUTHENTICATE", "admin log-in");
return prop;
}
final String recommendHash = post.get("recommendref", "");
final URIMetadataRow urlentry = indexSegment.urlMetadata().load(recommendHash.getBytes(), null, 0);
if (urlentry != null) {
final URIMetadataRow.Components metadata = urlentry.metadata();
Document document;
document = LoaderDispatcher.retrieveDocument(metadata.url(), true, 5000, true, false, Long.MAX_VALUE);
if (document != null) {
final HashMap<String, String> map = new HashMap<String, String>();
map.put("url", metadata.url().toNormalform(false, true).replace(',', '|'));
map.put("title", metadata.dc_title().replace(',', ' '));
map.put("description", document.dc_title().replace(',', ' '));
map.put("author", document.dc_creator());
map.put("tags", document.dc_subject(' '));
sb.peers.newsPool.publishMyNews(new yacyNewsDB.Record(sb.peers.mySeed(), yacyNewsPool.CATEGORY_SURFTIPP_ADD, map));
document.close();
}
}
}
final boolean globalsearch = (global) && indexReceiveGranted;
final HandleSet queryHashes = Word.words2hashesHandles(query[0]);
final QueryParams theQuery = new QueryParams(
originalquerystring,
queryHashes,
Word.words2hashesHandles(query[1]),
Word.words2hashesHandles(query[2]),
tenant,
maxDistance,
prefermask,
contentdom,
language,
navigation,
fetchSnippets,
itemsPerPage,
offset,
urlmask,
(clustersearch && globalsearch) ? QueryParams.SEARCHDOM_CLUSTERALL :
((globalsearch) ? QueryParams.SEARCHDOM_GLOBALDHT : QueryParams.SEARCHDOM_LOCAL),
20,
constraint,
true,
sitehash,
authorhash,
DigestURI.TLD_any_zone_filter,
client,
authenticated,
indexSegment,
ranking);
EventTracker.update("SEARCH", new ProfilingGraph.searchEvent(theQuery.id(true), SearchEvent.INITIALIZATION, 0, 0), false, 30000, ProfilingGraph.maxTime);
sb.intermissionAllThreads(3000);
theQuery.filterOut(Switchboard.blueList);
Log.logInfo("LOCAL_SEARCH", "INIT WORD SEARCH: " + theQuery.queryString + ":" + QueryParams.hashSet2hashString(theQuery.queryHashes) + " - " + theQuery.neededResults() + " links to be computed, " + theQuery.displayResults() + " lines to be displayed");
RSSFeed.channels(RSSFeed.LOCALSEARCH).addMessage(new RSSMessage("Local Search Request", theQuery.queryString, ""));
final long timestamp = System.currentTimeMillis();
if (SearchEventCache.getEvent(theQuery.id(false)) == null) {
theQuery.setOffset(0);
offset = 0;
}
final SearchEvent theSearch = SearchEventCache.getEvent(theQuery, sb.peers, sb.crawlResults, (sb.isRobinsonMode()) ? sb.clusterhashes : null, false, sb.loader);
try {Thread.sleep(global ? 100 : 10);} catch (InterruptedException e1) {}
Log.logInfo("LOCAL_SEARCH", "EXIT WORD SEARCH: " + theQuery.queryString + " - " +
(theSearch.getRankingResult().getLocalIndexCount() + theSearch.getRankingResult().getRemoteResourceSize()) + " links found, " +
(System.currentTimeMillis() - timestamp) + " ms");
theQuery.resultcount = theSearch.getRankingResult().getLocalIndexCount() + theSearch.getRankingResult().getRemoteResourceSize();
theQuery.searchtime = System.currentTimeMillis() - timestamp;
theQuery.urlretrievaltime = theSearch.result().getURLRetrievalTime();
theQuery.snippetcomputationtime = theSearch.result().getSnippetComputationTime();
sb.localSearches.add(theQuery);
int meanMax = 0;
if (post != null && post.containsKey("meanCount")) {
try {
meanMax = Integer.parseInt(post.get("meanCount"));
} catch (NumberFormatException e) {}
}
prop.put("meanCount", meanMax);
if (meanMax > 0) {
DidYouMean didYouMean = new DidYouMean(indexSegment.termIndex());
Iterator<String> meanIt = didYouMean.getSuggestions(querystring, 300, 10).iterator();
int meanCount = 0;
String suggestion;
while(meanCount<meanMax && meanIt.hasNext()) {
suggestion = meanIt.next();
prop.put("didYouMean_suggestions_"+meanCount+"_word", suggestion);
prop.put("didYouMean_suggestions_"+meanCount+"_url",
"/yacysearch.html" + "?display=" + display +
"&query=" + suggestion +
"&maximumRecords="+ theQuery.displayResults() +
"&startRecord=" + (0 * theQuery.displayResults()) +
"&resource=" + ((theQuery.isLocal()) ? "local" : "global") +
"&verify=" + ((theQuery.onlineSnippetFetch) ? "true" : "false") +
"&nav=" + theQuery.navigators +
"&urlmaskfilter=" + originalUrlMask.toString() +
"&prefermaskfilter=" + theQuery.prefer.toString() +
"&cat=href&constraint=" + ((theQuery.constraint == null) ? "" : theQuery.constraint.exportB64()) +
"&contentdom=" + theQuery.contentdom() +
"&former=" + theQuery.queryString(true) +
"&meanCount=" + meanMax
);
prop.put("didYouMean_suggestions_"+meanCount+"_sep","|");
meanCount++;
}
prop.put("didYouMean_suggestions_"+(meanCount-1)+"_sep","");
prop.put("didYouMean", meanCount>0 ? 1:0);
prop.put("didYouMean_suggestions", meanCount);
} else {
prop.put("didYouMean", 0);
}
TreeSet<Location> coordinates = LibraryProvider.geoLoc.find(originalquerystring, false);
if (coordinates == null || coordinates.isEmpty() || offset > 0) {
prop.put("geoinfo", "0");
} else {
int i = 0;
for (Location c: coordinates) {
prop.put("geoinfo_loc_" + i + "_lon", Math.round(c.lon() * 10000.0) / 10000.0);
prop.put("geoinfo_loc_" + i + "_lat", Math.round(c.lat() * 10000.0) / 10000.0);
prop.put("geoinfo_loc_" + i + "_name", c.getName());
i++;
if (i >= 10) break;
}
prop.put("geoinfo_loc", i);
prop.put("geoinfo", "1");
}
try {
synchronized (trackerHandles) {
trackerHandles.add(theQuery.handle);
while (trackerHandles.size() > 600) if (!trackerHandles.remove(trackerHandles.first())) break;
}
sb.localSearchTracker.put(client, trackerHandles);
if (sb.localSearchTracker.size() > 1000) sb.localSearchTracker.remove(sb.localSearchTracker.keys().nextElement());
} catch (Exception e) {
Log.logException(e);
}
prop.put("num-results_offset", offset);
prop.put("num-results_itemscount", Formatter.number(0, true));
prop.put("num-results_itemsPerPage", itemsPerPage);
prop.put("num-results_totalcount", Formatter.number(theSearch.getRankingResult().getLocalIndexCount() + theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("num-results_globalresults", (globalsearch) ? "1" : "0");
prop.put("num-results_globalresults_localResourceSize", Formatter.number(theSearch.getRankingResult().getLocalIndexCount(), true));
prop.put("num-results_globalresults_remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("num-results_globalresults_remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true));
prop.put("num-results_globalresults_remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true));
final StringBuilder resnav = new StringBuilder();
final int thispage = offset / theQuery.displayResults();
if (thispage == 0) {
resnav.append("<img src=\"env/grafics/navdl.gif\" alt=\"arrowleft\" width=\"16\" height=\"16\" /> ");
} else {
resnav.append("<a href=\"");
resnav.append(QueryParams.navurl("html", thispage - 1, display, theQuery, originalUrlMask, null, navigation));
resnav.append("\"><img src=\"env/grafics/navdl.gif\" alt=\"arrowleft\" width=\"16\" height=\"16\" /></a> ");
}
final int numberofpages = Math.min(10, Math.max(1 + thispage, 1 + ((theSearch.getRankingResult().getLocalIndexCount() < 11) ? Math.max(30, theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize()) : theSearch.getRankingResult().getLocalIndexCount()) / theQuery.displayResults()));
for (int i = 0; i < numberofpages; i++) {
if (i == thispage) {
resnav.append("<img src=\"env/grafics/navs");
resnav.append(i + 1);
resnav.append(".gif\" alt=\"page");
resnav.append(i + 1);
resnav.append("\" width=\"16\" height=\"16\" /> ");
} else {
resnav.append("<a href=\"");
resnav.append(QueryParams.navurl("html", i, display, theQuery, originalUrlMask, null, navigation));
resnav.append("\"><img src=\"env/grafics/navd");
resnav.append(i + 1);
resnav.append(".gif\" alt=\"page");
resnav.append(i + 1);
resnav.append("\" width=\"16\" height=\"16\" /></a> ");
}
}
if (thispage >= numberofpages) {
resnav.append("<img src=\"env/grafics/navdr.gif\" alt=\"arrowright\" width=\"16\" height=\"16\" />");
} else {
resnav.append("<a href=\"");
resnav.append(QueryParams.navurl("html", thispage + 1, display, theQuery, originalUrlMask, null, navigation));
resnav.append("\"><img src=\"env/grafics/navdr.gif\" alt=\"arrowright\" width=\"16\" height=\"16\" /></a>");
}
String resnavs = resnav.toString();
prop.put("num-results_resnav", resnavs);
prop.put("pageNavBottom", (theSearch.getRankingResult().getLocalIndexCount() - offset > 6) ? 1 : 0);
prop.put("pageNavBottom_resnav", resnavs);
for (int i = 0; i < theQuery.displayResults(); i++) {
prop.put("results_" + i + "_item", offset + i);
prop.put("results_" + i + "_eventID", theQuery.id(false));
prop.put("results_" + i + "_display", display);
}
prop.put("results", theQuery.displayResults());
prop.put("resultTable", (contentdom == ContentDomain.APP || contentdom == ContentDomain.AUDIO || contentdom == ContentDomain.VIDEO) ? 1 : 0);
prop.put("eventID", theQuery.id(false));
if (!filtered.isEmpty()) {
prop.put("excluded", "1");
prop.putHTML("excluded_stopwords", filtered.toString());
} else {
prop.put("excluded", "0");
}
if (prop == null || prop.isEmpty()) {
if (post == null || post.get("query", post.get("search", "")).length() < 3) {
prop.put("num-results", "2");
} else {
prop.put("num-results", "1");
}
} else {
prop.put("num-results", "3");
}
prop.put("cat", "href");
prop.put("depth", "0");
String hostName = header.get("Host", "localhost");
if (hostName.indexOf(':') == -1) hostName += ":" + serverCore.getPortNr(env.getConfig("port", "8080"));
prop.put("searchBaseURL", "http://" + hostName + "/yacysearch.html");
prop.put("rssYacyImageURL", "http://" + hostName + "/env/grafics/yacy.gif");
}
prop.put("searchagain", global ? "1" : "0");
prop.put("display", display);
prop.putHTML("former", originalquerystring);
prop.put("count", itemsPerPage);
prop.put("offset", offset);
prop.put("resource", global ? "global" : "local");
prop.putHTML("urlmaskfilter", originalUrlMask);
prop.putHTML("prefermaskfilter", prefermask);
prop.put("indexof", (indexof) ? "on" : "off");
prop.put("constraint", (constraint == null) ? "" : constraint.exportB64());
prop.put("verify", (fetchSnippets) ? "true" : "false");
prop.put("contentdom", (post == null ? "text" : post.get("contentdom", "text")));
prop.put("searchdomswitches", sb.getConfigBool("search.text", true) || sb.getConfigBool("search.audio", true) || sb.getConfigBool("search.video", true) || sb.getConfigBool("search.image", true) || sb.getConfigBool("search.app", true) ? 1 : 0);
prop.put("searchdomswitches_searchtext", sb.getConfigBool("search.text", true) ? 1 : 0);
prop.put("searchdomswitches_searchaudio", sb.getConfigBool("search.audio", true) ? 1 : 0);
prop.put("searchdomswitches_searchvideo", sb.getConfigBool("search.video", true) ? 1 : 0);
prop.put("searchdomswitches_searchimage", sb.getConfigBool("search.image", true) ? 1 : 0);
prop.put("searchdomswitches_searchapp", sb.getConfigBool("search.app", true) ? 1 : 0);
prop.put("searchdomswitches_searchtext_check", (contentdom == ContentDomain.TEXT) ? "1" : "0");
prop.put("searchdomswitches_searchaudio_check", (contentdom == ContentDomain.AUDIO) ? "1" : "0");
prop.put("searchdomswitches_searchvideo_check", (contentdom == ContentDomain.VIDEO) ? "1" : "0");
prop.put("searchdomswitches_searchimage_check", (contentdom == ContentDomain.IMAGE) ? "1" : "0");
prop.put("searchdomswitches_searchapp_check", (contentdom == ContentDomain.APP) ? "1" : "0");
prop.put("searchdomswitches_display", prop.get("display"));
prop.put("searchdomswitches_count", prop.get("count"));
prop.put("searchdomswitches_urlmaskfilter", prop.get("urlmaskfilter"));
prop.put("searchdomswitches_prefermaskfilter", prop.get("prefermaskfilter"));
prop.put("searchdomswitches_cat", prop.get("cat"));
prop.put("searchdomswitches_constraint", prop.get("constraint"));
prop.put("searchdomswitches_contentdom", prop.get("contentdom"));
prop.put("searchdomswitches_former", prop.get("former"));
prop.put("searchdomswitches_meanCount", prop.get("meanCount"));
prop.putXML("rss_query", originalquerystring);
prop.put("rss_queryenc", originalquerystring.replace(' ', '+'));
sb.localSearchLastAccess = System.currentTimeMillis();
return prop;
}
| public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final Switchboard sb = (Switchboard) env;
sb.localSearchLastAccess = System.currentTimeMillis();
final boolean searchAllowed = sb.getConfigBool("publicSearchpage", true) || sb.verifyAuthentication(header, false);
final boolean authenticated = sb.adminAuthenticated(header) >= 2;
int display = (post == null) ? 0 : post.getInt("display", 0);
if (!authenticated) display = 2;
final boolean browserPopUpTrigger = sb.getConfig(SwitchboardConstants.BROWSER_POP_UP_TRIGGER, "true").equals("true");
if (browserPopUpTrigger) {
final String browserPopUpPage = sb.getConfig(SwitchboardConstants.BROWSER_POP_UP_PAGE, "ConfigBasic.html");
if (browserPopUpPage.startsWith("index") || browserPopUpPage.startsWith("yacysearch")) display = 2;
}
String promoteSearchPageGreeting = env.getConfig(SwitchboardConstants.GREETING, "");
if (env.getConfigBool(SwitchboardConstants.GREETING_NETWORK_NAME, false)) promoteSearchPageGreeting = env.getConfig("network.unit.description", "");
final String client = header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP);
String originalquerystring = (post == null) ? "" : post.get("query", post.get("search", "")).trim();
String querystring = originalquerystring.replace('+', ' ');
boolean fetchSnippets = (post != null && post.get("verify", "false").equals("true"));
final serverObjects prop = new serverObjects();
Segment indexSegment = null;
if (post != null && post.containsKey("segment")) {
String segmentName = post.get("segment");
if (sb.indexSegments.segmentExist(segmentName)) {
indexSegment = sb.indexSegments.segment(segmentName);
}
} else {
indexSegment = sb.indexSegments.segment(Segments.Process.PUBLIC);
}
prop.put("promoteSearchPageGreeting", promoteSearchPageGreeting);
prop.put("promoteSearchPageGreeting.homepage", sb.getConfig(SwitchboardConstants.GREETING_HOMEPAGE, ""));
prop.put("promoteSearchPageGreeting.smallImage", sb.getConfig(SwitchboardConstants.GREETING_SMALL_IMAGE, ""));
if (post == null || indexSegment == null || env == null || !searchAllowed) {
prop.put("searchagain", "0");
prop.put("display", display);
prop.put("former", "");
prop.put("count", "10");
prop.put("offset", "0");
prop.put("resource", "global");
prop.put("urlmaskfilter", (post == null) ? ".*" : post.get("urlmaskfilter", ".*"));
prop.put("prefermaskfilter", (post == null) ? "" : post.get("prefermaskfilter", ""));
prop.put("tenant", (post == null) ? "" : post.get("tenant", ""));
prop.put("indexof", "off");
prop.put("constraint", "");
prop.put("cat", "href");
prop.put("depth", "0");
prop.put("verify", (post == null) ? "true" : post.get("verify", "true"));
prop.put("contentdom", "text");
prop.put("contentdomCheckText", "1");
prop.put("contentdomCheckAudio", "0");
prop.put("contentdomCheckVideo", "0");
prop.put("contentdomCheckImage", "0");
prop.put("contentdomCheckApp", "0");
prop.put("excluded", "0");
prop.put("results", "");
prop.put("resultTable", "0");
prop.put("num-results", searchAllowed ? "0" : "4");
prop.put("num-results_totalcount", 0);
prop.put("num-results_offset", 0);
prop.put("num-results_itemsPerPage", 10);
prop.put("geoinfo", "0");
prop.put("rss_queryenc", "");
prop.put("meanCount", 5);
return prop;
}
if (post.containsKey("callback")) {
final String jsonp = post.get("callback")+ "([";
prop.put("jsonp-start", jsonp);
prop.put("jsonp-end", "])");
} else {
prop.put("jsonp-start", "");
prop.put("jsonp-end", "");
}
boolean newsearch = post.hasValue("query") && post.hasValue("former") && !post.get("query","").equalsIgnoreCase(post.get("former",""));
int itemsPerPage = Math.min((authenticated) ? (fetchSnippets ? 100 : 1000) : (fetchSnippets ? 10 : 100), post.getInt("maximumRecords", post.getInt("count", 10)));
int offset = (newsearch) ? 0 : post.getInt("startRecord", post.getInt("offset", 0));
boolean global = post.get("resource", "local").equals("global");
final boolean indexof = (post != null && post.get("indexof","").equals("on"));
String urlmask = null;
String originalUrlMask = null;
if (post.containsKey("urlmask") && post.get("urlmask").equals("no")) {
originalUrlMask = ".*";
} else if (!newsearch && post.containsKey("urlmaskfilter")) {
originalUrlMask = post.get("urlmaskfilter", ".*");
} else {
originalUrlMask = ".*";
}
String prefermask = (post == null) ? "" : post.get("prefermaskfilter", "");
if (prefermask.length() > 0 && prefermask.indexOf(".*") < 0) prefermask = ".*" + prefermask + ".*";
Bitfield constraint = (post != null && post.containsKey("constraint") && post.get("constraint", "").length() > 0) ? new Bitfield(4, post.get("constraint", "______")) : null;
if (indexof) {
constraint = new Bitfield(4);
constraint.set(Condenser.flag_cat_indexof, true);
}
final boolean indexReceiveGranted = sb.getConfigBool(SwitchboardConstants.INDEX_RECEIVE_ALLOW, true) ||
sb.getConfigBool(SwitchboardConstants.INDEX_RECEIVE_AUTODISABLED, true);
global = global && indexReceiveGranted;
final boolean clustersearch = sb.isRobinsonMode() &&
(sb.getConfig("cluster.mode", "").equals("privatecluster") ||
sb.getConfig("cluster.mode", "").equals("publiccluster"));
if (clustersearch) global = true;
if (!global) {
if (authenticated) {
sb.searchQueriesRobinsonFromLocal++;
} else {
sb.searchQueriesRobinsonFromRemote++;
}
}
final ContentDomain contentdom = ContentDomain.contentdomParser(post == null ? "text" : post.get("contentdom", "text"));
if ((contentdom != ContentDomain.TEXT) && (itemsPerPage <= 32)) itemsPerPage = 64;
TreeSet<Long> trackerHandles = sb.localSearchTracker.get(client);
if (trackerHandles == null) trackerHandles = new TreeSet<Long>();
boolean block = false;
if (Domains.matchesList(client, sb.networkBlacklist)) {
global = false;
fetchSnippets = false;
block = true;
Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: BLACKLISTED CLIENT FROM " + client + " gets no permission to search");
} else if (Domains.matchesList(client, sb.networkWhitelist)) {
Log.logInfo("LOCAL_SEARCH", "ACCECC CONTROL: WHITELISTED CLIENT FROM " + client + " gets no search restrictions");
} else if (global || fetchSnippets) {
synchronized (trackerHandles) {
int accInOneSecond = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 1000)).size();
int accInThreeSeconds = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 3000)).size();
int accInOneMinute = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 60000)).size();
int accInTenMinutes = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 600000)).size();
if (accInTenMinutes > 600) {
global = false;
fetchSnippets = false;
block = true;
Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInTenMinutes + " searches in ten minutes, fully blocked (no results generated)");
} else if (accInOneMinute > 200) {
global = false;
fetchSnippets = false;
block = true;
Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInOneMinute + " searches in one minute, fully blocked (no results generated)");
} else if (accInThreeSeconds > 1) {
global = false;
fetchSnippets = false;
Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInThreeSeconds + " searches in three seconds, blocked global search and snippets");
} else if (accInOneSecond > 2) {
global = false;
fetchSnippets = false;
Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInOneSecond + " searches in one second, blocked global search and snippets");
}
}
}
if ((!block) && (post == null || post.get("cat", "href").equals("href"))) {
if (!MemoryControl.request(8000000L, false)) {
indexSegment.urlMetadata().clearCache();
SearchEventCache.cleanupEvents(true);
}
final RankingProfile ranking = sb.getRanking();
if (querystring.indexOf("NEAR") >= 0) {
querystring = querystring.replace("NEAR", "");
ranking.coeff_worddistance = RankingProfile.COEFF_MAX;
}
if (querystring.indexOf("RECENT") >= 0) {
querystring = querystring.replace("RECENT", "");
ranking.coeff_date = RankingProfile.COEFF_MAX;
}
int lrp = querystring.indexOf("LANGUAGE:");
String lr = "";
if (lrp >= 0) {
if (querystring.length() >= (lrp + 11))
lr = querystring.substring(lrp + 9, lrp + 11);
querystring = querystring.replace("LANGUAGE:" + lr, "");
lr = lr.toLowerCase();
}
int inurl = querystring.indexOf("inurl:");
if (inurl >= 0) {
int ftb = querystring.indexOf(' ', inurl);
if (ftb == -1) ftb = querystring.length();
String urlstr = querystring.substring(inurl + 6, ftb);
querystring = querystring.replace("inurl:" + urlstr, "");
if(urlstr.length() > 0) urlmask = ".*" + urlstr + ".*";
}
int filetype = querystring.indexOf("filetype:");
if (filetype >= 0) {
int ftb = querystring.indexOf(' ', filetype);
if (ftb == -1) ftb = querystring.length();
String ft = querystring.substring(filetype + 9, ftb);
querystring = querystring.replace("filetype:" + ft, "");
while (ft.length() > 0 && ft.charAt(0) == '.') ft = ft.substring(1);
if(ft.length() > 0) {
if (urlmask == null) {
urlmask = ".*\\." + ft;
} else {
urlmask = urlmask + ".*\\." + ft;
}
}
}
String tenant = null;
if (post.containsKey("tenant")) {
tenant = post.get("tenant");
if (tenant != null && tenant.length() == 0) tenant = null;
if (tenant != null) {
if (urlmask == null) urlmask = ".*" + tenant + ".*"; else urlmask = ".*" + tenant + urlmask;
}
}
int site = querystring.indexOf("site:");
String sitehash = null;
if (site >= 0) {
int ftb = querystring.indexOf(' ', site);
if (ftb == -1) ftb = querystring.length();
String domain = querystring.substring(site + 5, ftb);
querystring = querystring.replace("site:" + domain, "");
while (domain.length() > 0 && domain.charAt(0) == '.') domain = domain.substring(1);
while (domain.endsWith(".")) domain = domain.substring(0, domain.length() - 1);
sitehash = DigestURI.domhash(domain);
}
int authori = querystring.indexOf("author:");
String authorhash = null;
if (authori >= 0) {
boolean quotes = false;
if (querystring.charAt(authori + 7) == (char) 39) {
quotes = true;
}
String author;
if (quotes) {
int ftb = querystring.indexOf((char) 39, authori + 8);
if (ftb == -1) ftb = querystring.length() + 1;
author = querystring.substring(authori + 8, ftb);
querystring = querystring.replace("author:'" + author + "'", "");
} else {
int ftb = querystring.indexOf(' ', authori);
if (ftb == -1) ftb = querystring.length();
author = querystring.substring(authori + 7, ftb);
querystring = querystring.replace("author:" + author, "");
}
authorhash = new String(Word.word2hash(author));
}
int tld = querystring.indexOf("tld:");
if (tld >= 0) {
int ftb = querystring.indexOf(' ', tld);
if (ftb == -1) ftb = querystring.length();
String domain = querystring.substring(tld + 4, ftb);
querystring = querystring.replace("tld:" + domain, "");
while (domain.length() > 0 && domain.charAt(0) == '.') domain = domain.substring(1);
if (domain.indexOf('.') < 0) domain = "\\." + domain;
if (domain.length() > 0) {
if (urlmask == null) {
urlmask = "[a-zA-Z]*://[^/]*" + domain + "/.*";
} else {
urlmask = "[a-zA-Z]*://[^/]*" + domain + "/.*" + urlmask;
}
}
}
if (urlmask == null || urlmask.length() == 0) urlmask = originalUrlMask;
String language = (post == null) ? lr : post.get("lr", lr);
if (language.startsWith("lang_")) language = language.substring(5);
if (!ISO639.exists(language)) {
String agent = header.get(HeaderFramework.ACCEPT_LANGUAGE);
if (agent == null) agent = System.getProperty("user.language");
language = (agent == null) ? "en" : ISO639.userAgentLanguageDetection(agent);
if (language == null) language = "en";
}
String navigation = (post == null) ? "" : post.get("nav", "");
final TreeSet<String>[] query = QueryParams.cleanQuery(querystring.trim());
int maxDistance = (querystring.indexOf('"') >= 0) ? maxDistance = query.length - 1 : Integer.MAX_VALUE;
final TreeSet<String> filtered = SetTools.joinConstructive(query[0], Switchboard.stopwords);
if (!filtered.isEmpty()) {
SetTools.excludeDestructive(query[0], Switchboard.stopwords);
}
if (post != null && post.containsKey("deleteref")) try {
if (!sb.verifyAuthentication(header, true)) {
prop.put("AUTHENTICATE", "admin log-in");
return prop;
}
final String delHash = post.get("deleteref", "");
indexSegment.termIndex().remove(Word.words2hashesHandles(query[0]), delHash.getBytes());
final HashMap<String, String> map = new HashMap<String, String>();
map.put("urlhash", delHash);
map.put("vote", "negative");
map.put("refid", "");
sb.peers.newsPool.publishMyNews(new yacyNewsDB.Record(sb.peers.mySeed(), yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD, map));
} catch (IOException e) {
Log.logException(e);
}
if (post != null && post.containsKey("recommendref")) {
if (!sb.verifyAuthentication(header, true)) {
prop.put("AUTHENTICATE", "admin log-in");
return prop;
}
final String recommendHash = post.get("recommendref", "");
final URIMetadataRow urlentry = indexSegment.urlMetadata().load(recommendHash.getBytes(), null, 0);
if (urlentry != null) {
final URIMetadataRow.Components metadata = urlentry.metadata();
Document document;
document = LoaderDispatcher.retrieveDocument(metadata.url(), true, 5000, true, false, Long.MAX_VALUE);
if (document != null) {
final HashMap<String, String> map = new HashMap<String, String>();
map.put("url", metadata.url().toNormalform(false, true).replace(',', '|'));
map.put("title", metadata.dc_title().replace(',', ' '));
map.put("description", document.dc_title().replace(',', ' '));
map.put("author", document.dc_creator());
map.put("tags", document.dc_subject(' '));
sb.peers.newsPool.publishMyNews(new yacyNewsDB.Record(sb.peers.mySeed(), yacyNewsPool.CATEGORY_SURFTIPP_ADD, map));
document.close();
}
}
}
final boolean globalsearch = (global) && indexReceiveGranted;
final HandleSet queryHashes = Word.words2hashesHandles(query[0]);
final QueryParams theQuery = new QueryParams(
originalquerystring,
queryHashes,
Word.words2hashesHandles(query[1]),
Word.words2hashesHandles(query[2]),
tenant,
maxDistance,
prefermask,
contentdom,
language,
navigation,
fetchSnippets,
itemsPerPage,
offset,
urlmask,
(clustersearch && globalsearch) ? QueryParams.SEARCHDOM_CLUSTERALL :
((globalsearch) ? QueryParams.SEARCHDOM_GLOBALDHT : QueryParams.SEARCHDOM_LOCAL),
20,
constraint,
true,
sitehash,
authorhash,
DigestURI.TLD_any_zone_filter,
client,
authenticated,
indexSegment,
ranking);
EventTracker.update("SEARCH", new ProfilingGraph.searchEvent(theQuery.id(true), SearchEvent.INITIALIZATION, 0, 0), false, 30000, ProfilingGraph.maxTime);
sb.intermissionAllThreads(3000);
theQuery.filterOut(Switchboard.blueList);
Log.logInfo("LOCAL_SEARCH", "INIT WORD SEARCH: " + theQuery.queryString + ":" + QueryParams.hashSet2hashString(theQuery.queryHashes) + " - " + theQuery.neededResults() + " links to be computed, " + theQuery.displayResults() + " lines to be displayed");
RSSFeed.channels(RSSFeed.LOCALSEARCH).addMessage(new RSSMessage("Local Search Request", theQuery.queryString, ""));
final long timestamp = System.currentTimeMillis();
if (SearchEventCache.getEvent(theQuery.id(false)) == null) {
theQuery.setOffset(0);
offset = 0;
}
final SearchEvent theSearch = SearchEventCache.getEvent(theQuery, sb.peers, sb.crawlResults, (sb.isRobinsonMode()) ? sb.clusterhashes : null, false, sb.loader);
try {Thread.sleep(global ? 100 : 10);} catch (InterruptedException e1) {}
Log.logInfo("LOCAL_SEARCH", "EXIT WORD SEARCH: " + theQuery.queryString + " - " +
(theSearch.getRankingResult().getLocalIndexCount() + theSearch.getRankingResult().getRemoteResourceSize()) + " links found, " +
(System.currentTimeMillis() - timestamp) + " ms");
theQuery.resultcount = theSearch.getRankingResult().getLocalIndexCount() + theSearch.getRankingResult().getRemoteResourceSize();
theQuery.searchtime = System.currentTimeMillis() - timestamp;
theQuery.urlretrievaltime = theSearch.result().getURLRetrievalTime();
theQuery.snippetcomputationtime = theSearch.result().getSnippetComputationTime();
sb.localSearches.add(theQuery);
int meanMax = 0;
if (post != null && post.containsKey("meanCount")) {
try {
meanMax = Integer.parseInt(post.get("meanCount"));
} catch (NumberFormatException e) {}
}
prop.put("meanCount", meanMax);
if (meanMax > 0) {
DidYouMean didYouMean = new DidYouMean(indexSegment.termIndex());
Iterator<String> meanIt = didYouMean.getSuggestions(querystring, 300, 10).iterator();
int meanCount = 0;
String suggestion;
while(meanCount<meanMax && meanIt.hasNext()) {
suggestion = meanIt.next();
prop.put("didYouMean_suggestions_"+meanCount+"_word", suggestion);
prop.put("didYouMean_suggestions_"+meanCount+"_url",
"/yacysearch.html" + "?display=" + display +
"&query=" + suggestion +
"&maximumRecords="+ theQuery.displayResults() +
"&startRecord=" + (0 * theQuery.displayResults()) +
"&resource=" + ((theQuery.isLocal()) ? "local" : "global") +
"&verify=" + ((theQuery.onlineSnippetFetch) ? "true" : "false") +
"&nav=" + theQuery.navigators +
"&urlmaskfilter=" + originalUrlMask.toString() +
"&prefermaskfilter=" + theQuery.prefer.toString() +
"&cat=href&constraint=" + ((theQuery.constraint == null) ? "" : theQuery.constraint.exportB64()) +
"&contentdom=" + theQuery.contentdom() +
"&former=" + theQuery.queryString(true) +
"&meanCount=" + meanMax
);
prop.put("didYouMean_suggestions_"+meanCount+"_sep","|");
meanCount++;
}
prop.put("didYouMean_suggestions_"+(meanCount-1)+"_sep","");
prop.put("didYouMean", meanCount>0 ? 1:0);
prop.put("didYouMean_suggestions", meanCount);
} else {
prop.put("didYouMean", 0);
}
TreeSet<Location> coordinates = LibraryProvider.geoLoc.find(originalquerystring, false);
if (coordinates == null || coordinates.isEmpty() || offset > 0) {
prop.put("geoinfo", "0");
} else {
int i = 0;
for (Location c: coordinates) {
prop.put("geoinfo_loc_" + i + "_lon", Math.round(c.lon() * 10000.0) / 10000.0);
prop.put("geoinfo_loc_" + i + "_lat", Math.round(c.lat() * 10000.0) / 10000.0);
prop.put("geoinfo_loc_" + i + "_name", c.getName());
i++;
if (i >= 10) break;
}
prop.put("geoinfo_loc", i);
prop.put("geoinfo", "1");
}
try {
synchronized (trackerHandles) {
trackerHandles.add(theQuery.handle);
while (trackerHandles.size() > 600) if (!trackerHandles.remove(trackerHandles.first())) break;
}
sb.localSearchTracker.put(client, trackerHandles);
if (sb.localSearchTracker.size() > 1000) sb.localSearchTracker.remove(sb.localSearchTracker.keys().nextElement());
} catch (Exception e) {
Log.logException(e);
}
prop.put("num-results_offset", offset);
prop.put("num-results_itemscount", Formatter.number(0, true));
prop.put("num-results_itemsPerPage", itemsPerPage);
prop.put("num-results_totalcount", Formatter.number(theSearch.getRankingResult().getLocalIndexCount() + theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("num-results_globalresults", (globalsearch) ? "1" : "0");
prop.put("num-results_globalresults_localResourceSize", Formatter.number(theSearch.getRankingResult().getLocalIndexCount(), true));
prop.put("num-results_globalresults_remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("num-results_globalresults_remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true));
prop.put("num-results_globalresults_remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true));
final StringBuilder resnav = new StringBuilder();
final int thispage = offset / theQuery.displayResults();
if (thispage == 0) {
resnav.append("<img src=\"env/grafics/navdl.gif\" alt=\"arrowleft\" width=\"16\" height=\"16\" /> ");
} else {
resnav.append("<a href=\"");
resnav.append(QueryParams.navurl("html", thispage - 1, display, theQuery, originalUrlMask, null, navigation));
resnav.append("\"><img src=\"env/grafics/navdl.gif\" alt=\"arrowleft\" width=\"16\" height=\"16\" /></a> ");
}
final int numberofpages = Math.min(10, Math.max(1 + thispage, 1 + ((theSearch.getRankingResult().getLocalIndexCount() < 11) ? Math.max(30, theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize()) : theSearch.getRankingResult().getLocalIndexCount()) / theQuery.displayResults()));
for (int i = 0; i < numberofpages; i++) {
if (i == thispage) {
resnav.append("<img src=\"env/grafics/navs");
resnav.append(i + 1);
resnav.append(".gif\" alt=\"page");
resnav.append(i + 1);
resnav.append("\" width=\"16\" height=\"16\" /> ");
} else {
resnav.append("<a href=\"");
resnav.append(QueryParams.navurl("html", i, display, theQuery, originalUrlMask, null, navigation));
resnav.append("\"><img src=\"env/grafics/navd");
resnav.append(i + 1);
resnav.append(".gif\" alt=\"page");
resnav.append(i + 1);
resnav.append("\" width=\"16\" height=\"16\" /></a> ");
}
}
if (thispage >= numberofpages) {
resnav.append("<img src=\"env/grafics/navdr.gif\" alt=\"arrowright\" width=\"16\" height=\"16\" />");
} else {
resnav.append("<a href=\"");
resnav.append(QueryParams.navurl("html", thispage + 1, display, theQuery, originalUrlMask, null, navigation));
resnav.append("\"><img src=\"env/grafics/navdr.gif\" alt=\"arrowright\" width=\"16\" height=\"16\" /></a>");
}
String resnavs = resnav.toString();
prop.put("num-results_resnav", resnavs);
prop.put("pageNavBottom", (theSearch.getRankingResult().getLocalIndexCount() - offset > 6) ? 1 : 0);
prop.put("pageNavBottom_resnav", resnavs);
for (int i = 0; i < theQuery.displayResults(); i++) {
prop.put("results_" + i + "_item", offset + i);
prop.put("results_" + i + "_eventID", theQuery.id(false));
prop.put("results_" + i + "_display", display);
}
prop.put("results", theQuery.displayResults());
prop.put("resultTable", (contentdom == ContentDomain.APP || contentdom == ContentDomain.AUDIO || contentdom == ContentDomain.VIDEO) ? 1 : 0);
prop.put("eventID", theQuery.id(false));
if (!filtered.isEmpty()) {
prop.put("excluded", "1");
prop.putHTML("excluded_stopwords", filtered.toString());
} else {
prop.put("excluded", "0");
}
if (prop == null || prop.isEmpty()) {
if (post == null || post.get("query", post.get("search", "")).length() < 3) {
prop.put("num-results", "2");
} else {
prop.put("num-results", "1");
}
} else {
prop.put("num-results", "3");
}
prop.put("cat", "href");
prop.put("depth", "0");
String hostName = header.get("Host", "localhost");
if (hostName.indexOf(':') == -1) hostName += ":" + serverCore.getPortNr(env.getConfig("port", "8080"));
prop.put("searchBaseURL", "http://" + hostName + "/yacysearch.html");
prop.put("rssYacyImageURL", "http://" + hostName + "/env/grafics/yacy.gif");
}
prop.put("searchagain", global ? "1" : "0");
prop.put("display", display);
prop.putHTML("former", originalquerystring);
prop.put("count", itemsPerPage);
prop.put("offset", offset);
prop.put("resource", global ? "global" : "local");
prop.putHTML("urlmaskfilter", originalUrlMask);
prop.putHTML("prefermaskfilter", prefermask);
prop.put("indexof", (indexof) ? "on" : "off");
prop.put("constraint", (constraint == null) ? "" : constraint.exportB64());
prop.put("verify", (fetchSnippets) ? "true" : "false");
prop.put("contentdom", (post == null ? "text" : post.get("contentdom", "text")));
prop.put("searchdomswitches", sb.getConfigBool("search.text", true) || sb.getConfigBool("search.audio", true) || sb.getConfigBool("search.video", true) || sb.getConfigBool("search.image", true) || sb.getConfigBool("search.app", true) ? 1 : 0);
prop.put("searchdomswitches_searchtext", sb.getConfigBool("search.text", true) ? 1 : 0);
prop.put("searchdomswitches_searchaudio", sb.getConfigBool("search.audio", true) ? 1 : 0);
prop.put("searchdomswitches_searchvideo", sb.getConfigBool("search.video", true) ? 1 : 0);
prop.put("searchdomswitches_searchimage", sb.getConfigBool("search.image", true) ? 1 : 0);
prop.put("searchdomswitches_searchapp", sb.getConfigBool("search.app", true) ? 1 : 0);
prop.put("searchdomswitches_searchtext_check", (contentdom == ContentDomain.TEXT) ? "1" : "0");
prop.put("searchdomswitches_searchaudio_check", (contentdom == ContentDomain.AUDIO) ? "1" : "0");
prop.put("searchdomswitches_searchvideo_check", (contentdom == ContentDomain.VIDEO) ? "1" : "0");
prop.put("searchdomswitches_searchimage_check", (contentdom == ContentDomain.IMAGE) ? "1" : "0");
prop.put("searchdomswitches_searchapp_check", (contentdom == ContentDomain.APP) ? "1" : "0");
prop.put("searchdomswitches_display", prop.get("display"));
prop.put("searchdomswitches_count", prop.get("count"));
prop.put("searchdomswitches_urlmaskfilter", prop.get("urlmaskfilter"));
prop.put("searchdomswitches_prefermaskfilter", prop.get("prefermaskfilter"));
prop.put("searchdomswitches_cat", prop.get("cat"));
prop.put("searchdomswitches_constraint", prop.get("constraint"));
prop.put("searchdomswitches_contentdom", prop.get("contentdom"));
prop.put("searchdomswitches_former", prop.get("former"));
prop.put("searchdomswitches_meanCount", prop.get("meanCount"));
prop.putXML("rss_query", originalquerystring);
prop.put("rss_queryenc", originalquerystring.replace(' ', '+'));
sb.localSearchLastAccess = System.currentTimeMillis();
return prop;
}
|
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
World world = null;
Player player = null;
if (sender instanceof Player)
{
player = (Player) sender;
world = player.getWorld();
}
else world = consoleWorld;
AutoRefMatch match = getMatch(world);
args = new StrTokenizer(StringUtils.join(args, ' '), StrMatcher.splitMatcher(),
StrMatcher.quoteMatcher()).setTrimmerMatcher(StrMatcher.trimMatcher()).getTokenArray();
if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.configure"))
{
if (args.length > 1 && "cfg".equalsIgnoreCase(args[0]))
{
if (args.length >= 2 && "save".equalsIgnoreCase(args[1]) && match != null)
{
match.saveWorldConfiguration();
sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " saved.");
}
if (args.length >= 2 && "init".equalsIgnoreCase(args[1]))
{
if (match == null)
{
addMatch(match = new AutoRefMatch(world, false));
match.saveWorldConfiguration();
match.setCurrentState(MatchStatus.NONE);
sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " generated.");
}
else sender.sendMessage(this.getName() + " already initialized for " +
match.worldConfig.getString("map.name", "this map") + ".");
}
if (args.length >= 2 && "reload".equalsIgnoreCase(args[1]) && match != null)
{
match.reload();
sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " reload complete!");
}
return true;
}
if (args.length >= 1 && "archive".equalsIgnoreCase(args[0]) && match != null) try
{
match.clearEntities();
world.setTime(match.getStartTime());
world.save();
match.saveWorldConfiguration();
File archiveFolder = null;
if (args.length >= 2 && "zip".equalsIgnoreCase(args[1]))
archiveFolder = match.distributeMap();
else archiveFolder = match.archiveMapData();
String resp = String.format("%s %s", match.getVersionString(),
archiveFolder == null ? "failed to archive." : "archived!");
sender.sendMessage(ChatColor.GREEN + resp); getLogger().info(resp);
return true;
}
catch (Exception e) { return false; }
if (args.length >= 1 && "debug".equalsIgnoreCase(args[0]) && match != null)
{
if (match.isDebugMode())
{ match.setDebug(null); return true; }
boolean consoleDebug = args.length >= 2 && "console".equalsIgnoreCase(args[1]);
match.setDebug(consoleDebug ? getServer().getConsoleSender() : sender);
return true;
}
if (args.length >= 1 && "tool".equalsIgnoreCase(args[0]))
{
if (args.length >= 2 && "wincond".equalsIgnoreCase(args[1]))
{
int toolID = ZoneListener.parseTool(getConfig().getString(
"config-mode.tools.win-condition", null), Material.GOLD_SPADE);
ItemStack toolitem = new ItemStack(toolID);
PlayerInventory inv = player.getInventory();
inv.addItem(toolitem);
sender.sendMessage("Given win condition tool: " + toolitem.getType().name());
sender.sendMessage("Right-click on a block to set it as a win-condition.");
return true;
}
if (args.length >= 2 && "startmech".equalsIgnoreCase(args[1]))
{
int toolID = ZoneListener.parseTool(getConfig().getString(
"config-mode.tools.start-mechanism", null), Material.GOLD_AXE);
ItemStack toolitem = new ItemStack(toolID);
PlayerInventory inv = player.getInventory();
inv.addItem(toolitem);
sender.sendMessage("Given start mechanism tool: " + toolitem.getType().name());
sender.sendMessage("Right-click on a device to set it as a starting mechanism.");
return true;
}
if (args.length >= 2 && "protect".equalsIgnoreCase(args[1]))
{
int toolID = ZoneListener.parseTool(getConfig().getString(
"config-mode.tools.protect-entities", null), Material.GOLD_SWORD);
ItemStack toolitem = new ItemStack(toolID);
PlayerInventory inv = player.getInventory();
inv.addItem(toolitem);
sender.sendMessage("Given entity protection tool: " + toolitem.getType().name());
sender.sendMessage("Right-click on an entity to protect it from butchering.");
return true;
}
}
if (args.length >= 1 && "nocraft".equalsIgnoreCase(args[0]) && match != null)
{
ItemStack item = player.getItemInHand();
if (item != null) match.addIllegalCraft(BlockData.fromItemStack(item));
return true;
}
if (args.length >= 2 && "setspawn".equalsIgnoreCase(args[0]) && match != null && player != null)
{
AutoRefTeam team = match.teamNameLookup(args[1]);
if (team == null)
{
sender.sendMessage(ChatColor.DARK_GRAY + args[1] +
ChatColor.RESET + "is not a valid team.");
sender.sendMessage("Teams are " + match.getTeamList());
}
else
{
team.setSpawnLocation(player.getLocation());
String coords = BlockVector3.fromLocation(player.getLocation()).toCoords();
sender.sendMessage(ChatColor.GRAY + "Spawn set to " + coords + " for " + team.getName());
}
return true;
}
}
if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.admin"))
{
if (args.length == 2 && "world".equalsIgnoreCase(args[0]))
{
consoleWorld = getServer().getWorld(args[1]);
if (consoleWorld != null) sender.sendMessage("Selected world " + consoleWorld.getName());
return consoleWorld != null;
}
if (args.length >= 2 && "load".equalsIgnoreCase(args[0])) try
{
String mapName = args[1];
String customName = args.length >= 3 ? args[2] : null;
sender.sendMessage(ChatColor.GREEN + "Please wait...");
AutoRefMap.loadMap(sender, mapName, customName);
return true;
}
catch (Exception e) { e.printStackTrace(); return true; }
if (args.length == 1 && "unload".equalsIgnoreCase(args[0]) && match != null)
{
match.destroy();
return true;
}
if (args.length == 1 && "reload".equalsIgnoreCase(args[0]) && match != null) try
{
AutoRefMap map = AutoRefMap.getMap(match.getMapName());
if (map == null || !map.isInstalled())
{
sender.sendMessage(ChatColor.DARK_GRAY +
"No archive of this map exists " + match.getMapName());
return true;
}
sender.sendMessage(ChatColor.DARK_GRAY +
"Preparing a new copy of " + map.getVersionString());
AutoRefMatch newmatch = AutoRefMap.createMatch(map, null);
for (Player p : match.getWorld().getPlayers())
p.teleport(newmatch.getWorldSpawn());
match.destroy();
return true;
}
catch (Exception e) { e.printStackTrace(); return true; }
if (args.length == 1 && "maplist".equalsIgnoreCase(args[0]))
{
List<AutoRefMap> maps = Lists.newArrayList(AutoRefMap.getAvailableMaps());
Collections.sort(maps);
sender.sendMessage(ChatColor.GOLD + String.format("Available Maps (%d):", maps.size()));
for (AutoRefMap mapInfo : maps)
{
ChatColor color = mapInfo.isInstalled() ? ChatColor.WHITE : ChatColor.DARK_GRAY;
sender.sendMessage("* " + color + mapInfo.getVersionString());
}
return true;
}
if (args.length >= 1 && "update".equalsIgnoreCase(args[0]))
{
boolean force = (args.length >= 2 && args[1].startsWith("f"));
AutoRefMap.getUpdates(sender, force);
return true;
}
if (args.length >= 1 && "state".equalsIgnoreCase(args[0]) &&
match != null && match.isDebugMode()) try
{
if (args.length >= 2)
match.setCurrentState(MatchStatus.valueOf(args[1].toUpperCase()));
getLogger().info("Match Status is now " + match.getCurrentState().name());
return true;
}
catch (Exception e) { return false; }
if (args.length > 1 && "autoinvite".equalsIgnoreCase(args[0]))
{
for (int i = 1; i < args.length; ++i)
{
OfflinePlayer opl = getServer().getOfflinePlayer(args[i]);
for (AutoRefMatch m : getMatches()) m.removeExpectedPlayer(opl);
match.addExpectedPlayer(opl);
Player invited = getServer().getPlayer(args[i]);
if (invited == null) continue;
AutoRefMatch m = getMatch(invited.getWorld());
if (m != null && m.isPlayer(invited) && m.getCurrentState().inProgress()) continue;
match.acceptInvitation(invited);
}
return true;
}
if (args.length >= 2 && "send".equalsIgnoreCase(args[0]) &&
match != null && match.isDebugMode())
{
Set<Player> targets = match.getReferees();
if (args.length >= 3) targets = Sets.newHashSet(getServer().getPlayer(args[2]));
for (Player ref : targets) if (ref != null) ref.sendPluginMessage(this,
AutoReferee.REFEREE_PLUGIN_CHANNEL, args[1].getBytes());
return true;
}
}
if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.referee"))
{
if (args.length == 3 && "teamname".equalsIgnoreCase(args[0]) && match != null)
{
AutoRefTeam team = null;
for (AutoRefTeam t : match.getTeams())
if (t.matches(args[1])) team = t;
if (team == null)
{
sender.sendMessage(ChatColor.DARK_GRAY + args[1] +
ChatColor.RESET + "is not a valid team.");
sender.sendMessage("Teams are " + match.getTeamList());
}
else team.setName(args[2]);
return true;
}
if (args.length >= 1 && "hud".equalsIgnoreCase(args[0]) && match != null)
{
if (args.length >= 2 && "swap".equalsIgnoreCase(args[1]))
{
match.messageReferee(player, "match", match.getWorld().getName(), "swap");
return true;
}
}
if (args.length == 3 && "swapteams".equalsIgnoreCase(args[0]) && match != null)
{
AutoRefTeam team1 = null, team2 = null;
for (AutoRefTeam t : match.getTeams())
{
if (t.matches(args[1])) team1 = t;
if (t.matches(args[2])) team2 = t;
}
if (team1 == null)
{
sender.sendMessage(ChatColor.DARK_GRAY + args[1] +
ChatColor.RESET + "is not a valid team.");
sender.sendMessage("Teams are " + match.getTeamList());
}
else if (team2 == null)
{
sender.sendMessage(ChatColor.DARK_GRAY + args[2] +
ChatColor.RESET + "is not a valid team.");
sender.sendMessage("Teams are " + match.getTeamList());
}
else AutoRefTeam.switchTeams(team1, team2);
return true;
}
if (args.length == 1 && "countdown".equalsIgnoreCase(args[0]) && match != null)
{
match.startCountdown(0, false);
return true;
}
}
if ("autoref".equalsIgnoreCase(cmd.getName()))
{
if (args.length > 1 && "invite".equalsIgnoreCase(args[0]) &&
match != null && match.getCurrentState().isBeforeMatch())
{
String from = (sender instanceof Player) ? match.getPlayerName(player) : "This server";
for (int i = 1; i < args.length; ++i)
{
Player invited = getServer().getPlayer(args[i]);
if (invited == null) continue;
AutoRefMatch m = getMatch(invited.getWorld());
if (m != null && m.isPlayer(invited) && m.getCurrentState().inProgress()) continue;
if (invited.getWorld() != match.getWorld())
new Conversation(this, invited, new InvitationPrompt(match, from)).begin();
}
return true;
}
if (args.length >= 1 && "version".equalsIgnoreCase(args[0]))
{
sender.sendMessage(ChatColor.DARK_GRAY + "This server is running " +
ChatColor.BLUE + this.getDescription().getFullName());
return true;
}
}
if ("zones".equalsIgnoreCase(cmd.getName()) && match != null)
{
Set<AutoRefTeam> lookupTeams = null;
if (args.length > 1)
{
AutoRefTeam t = match.teamNameLookup(args[1]);
if (t == null)
{
sender.sendMessage(ChatColor.DARK_GRAY + args[1] +
ChatColor.RESET + "is not a valid team.");
return true;
}
lookupTeams = Sets.newHashSet();
lookupTeams.add(t);
}
else lookupTeams = match.getTeams();
if (lookupTeams == null) return false;
for (AutoRefTeam team : lookupTeams)
{
sender.sendMessage(team.getName() + "'s Regions:");
if (team.getRegions().size() > 0) for (CuboidRegion reg : team.getRegions())
{
Vector3 mn = reg.getMinimumPoint(), mx = reg.getMaximumPoint();
sender.sendMessage(" (" + mn.toCoords() + ") => (" + mx.toCoords() + ")");
}
else sender.sendMessage(" <None>");
}
return true;
}
if ("zone".equalsIgnoreCase(cmd.getName()) && match != null)
{
WorldEditPlugin worldEdit = getWorldEdit();
if (worldEdit == null)
{
sender.sendMessage("This method requires WorldEdit installed and running.");
return true;
}
if (args.length == 0)
{
sender.sendMessage("Must specify a team as this zone's owner.");
return true;
}
AutoRefTeam t, START = new AutoRefTeam(); String tname = args[0];
t = "start".equals(tname) ? START : match.teamNameLookup(tname);
if (t == null)
{
sender.sendMessage(ChatColor.DARK_GRAY + tname +
ChatColor.RESET + "is not a valid team.");
sender.sendMessage("Teams are " + match.getTeamList());
return true;
}
Selection sel = worldEdit.getSelection(player);
if ((sel instanceof CuboidSelection))
{
CuboidSelection csel = (CuboidSelection) sel;
CuboidRegion reg = new CuboidRegion(
new Vector3(csel.getNativeMinimumPoint()),
new Vector3(csel.getNativeMaximumPoint())
);
if (t == START)
{
match.setStartRegion(reg);
sender.sendMessage("Region now marked as " +
"the start region!");
}
else
{
AutoRefRegion areg = new AutoRefRegion(reg);
if (args.length >= 2) for (String f : args[1].split(",")) areg.toggle(f);
t.getRegions().add(areg);
sender.sendMessage("Region now marked as " +
t.getName() + "'s zone!");
}
}
return true;
}
if ("matchinfo".equalsIgnoreCase(cmd.getName()))
{
if (match != null) match.sendMatchInfo(player);
else sender.sendMessage(ChatColor.GRAY +
this.getName() + " is not running for this world!");
return true;
}
if ("jointeam".equalsIgnoreCase(cmd.getName()) && match != null && !isAutoMode())
{
AutoRefTeam team = args.length > 0 ? match.teamNameLookup(args[0]) :
match.getArbitraryTeam();
if (team == null)
{
if (args.length > 0)
{
sender.sendMessage(ChatColor.DARK_GRAY + args[0] +
ChatColor.RESET + "is not a valid team.");
sender.sendMessage("Teams are " + match.getTeamList());
}
return true;
}
if (args.length >= 2 && player.hasPermission("autoreferee.referee"))
for (int i = 1; i < args.length; ++i)
{
Player target = getServer().getPlayer(args[i]);
if (target != null) match.joinTeam(target, team, true);
}
else match.joinTeam(player, team, player.hasPermission("autoreferee.referee"));
return true;
}
if ("leaveteam".equalsIgnoreCase(cmd.getName()) && match != null && !isAutoMode())
{
if (args.length >= 1 && player.hasPermission("autoreferee.referee"))
for (int i = 0; i < args.length; ++i)
{
Player target = getServer().getPlayer(args[i]);
if (target != null) match.leaveTeam(target, true);
}
else match.leaveTeam(player, player.hasPermission("autoreferee.referee"));
return true;
}
if ("viewinventory".equalsIgnoreCase(cmd.getName()) && args.length == 1
&& match != null && player != null)
{
if (!match.isReferee(player))
{ sender.sendMessage("You do not have permission."); return true; }
AutoRefPlayer target = match.getPlayer(getServer().getPlayer(args[0]));
if (target != null) target.showInventory(player);
return true;
}
if ("ready".equalsIgnoreCase(cmd.getName()) &&
match != null && match.getCurrentState().isBeforeMatch())
{
boolean rstate = true;
if (args.length > 0)
{
String rstr = args[0].toLowerCase();
rstate = !rstr.startsWith("f") && !rstr.startsWith("n");
}
if (match.isReferee(player))
{
if (args.length > 0) try { match.setReadyDelay(Integer.parseInt(args[0])); }
catch (NumberFormatException e) { };
match.setRefereeReady(rstate);
}
else
{
AutoRefTeam team = match.getPlayerTeam(player);
if (team != null) team.setReady(rstate);
}
match.checkTeamsStart();
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
World world = null;
Player player = null;
if (sender instanceof Player)
{
player = (Player) sender;
world = player.getWorld();
}
else world = consoleWorld;
AutoRefMatch match = getMatch(world);
args = new StrTokenizer(StringUtils.join(args, ' '), StrMatcher.splitMatcher(),
StrMatcher.quoteMatcher()).setTrimmerMatcher(StrMatcher.trimMatcher()).getTokenArray();
if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.configure"))
{
if (args.length > 1 && "cfg".equalsIgnoreCase(args[0]))
{
if (args.length >= 2 && "save".equalsIgnoreCase(args[1]) && match != null)
{
match.saveWorldConfiguration();
sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " saved.");
}
if (args.length >= 2 && "init".equalsIgnoreCase(args[1]))
{
if (match == null)
{
addMatch(match = new AutoRefMatch(world, false));
match.saveWorldConfiguration();
match.setCurrentState(MatchStatus.NONE);
sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " generated.");
}
else sender.sendMessage(this.getName() + " already initialized for " +
match.worldConfig.getString("map.name", "this map") + ".");
}
if (args.length >= 2 && "reload".equalsIgnoreCase(args[1]) && match != null)
{
match.reload();
sender.sendMessage(ChatColor.GREEN + CFG_FILENAME + " reload complete!");
}
return true;
}
if (args.length >= 1 && "archive".equalsIgnoreCase(args[0]) && match != null) try
{
match.clearEntities();
world.setTime(match.getStartTime());
world.save();
match.saveWorldConfiguration();
File archiveFolder = null;
if (args.length >= 2 && "zip".equalsIgnoreCase(args[1]))
archiveFolder = match.distributeMap();
else archiveFolder = match.archiveMapData();
String resp = String.format("%s %s", match.getVersionString(),
archiveFolder == null ? "failed to archive." : "archived!");
sender.sendMessage(ChatColor.GREEN + resp); getLogger().info(resp);
return true;
}
catch (Exception e) { return false; }
if (args.length >= 1 && "debug".equalsIgnoreCase(args[0]) && match != null)
{
if (match.isDebugMode())
{ match.setDebug(null); return true; }
boolean consoleDebug = args.length >= 2 && "console".equalsIgnoreCase(args[1]);
match.setDebug(consoleDebug ? getServer().getConsoleSender() : sender);
return true;
}
if (args.length >= 1 && "tool".equalsIgnoreCase(args[0]))
{
if (args.length >= 2 && "wincond".equalsIgnoreCase(args[1]))
{
int toolID = ZoneListener.parseTool(getConfig().getString(
"config-mode.tools.win-condition", null), Material.GOLD_SPADE);
ItemStack toolitem = new ItemStack(toolID);
PlayerInventory inv = player.getInventory();
inv.addItem(toolitem);
sender.sendMessage("Given win condition tool: " + toolitem.getType().name());
sender.sendMessage("Right-click on a block to set it as a win-condition.");
return true;
}
if (args.length >= 2 && "startmech".equalsIgnoreCase(args[1]))
{
int toolID = ZoneListener.parseTool(getConfig().getString(
"config-mode.tools.start-mechanism", null), Material.GOLD_AXE);
ItemStack toolitem = new ItemStack(toolID);
PlayerInventory inv = player.getInventory();
inv.addItem(toolitem);
sender.sendMessage("Given start mechanism tool: " + toolitem.getType().name());
sender.sendMessage("Right-click on a device to set it as a starting mechanism.");
return true;
}
if (args.length >= 2 && "protect".equalsIgnoreCase(args[1]))
{
int toolID = ZoneListener.parseTool(getConfig().getString(
"config-mode.tools.protect-entities", null), Material.GOLD_SWORD);
ItemStack toolitem = new ItemStack(toolID);
PlayerInventory inv = player.getInventory();
inv.addItem(toolitem);
sender.sendMessage("Given entity protection tool: " + toolitem.getType().name());
sender.sendMessage("Right-click on an entity to protect it from butchering.");
return true;
}
}
if (args.length >= 1 && "nocraft".equalsIgnoreCase(args[0]) && match != null)
{
ItemStack item = player.getItemInHand();
if (item != null) match.addIllegalCraft(BlockData.fromItemStack(item));
return true;
}
if (args.length >= 2 && "setspawn".equalsIgnoreCase(args[0]) && match != null && player != null)
{
AutoRefTeam team = match.teamNameLookup(args[1]);
if (team == null)
{
sender.sendMessage(ChatColor.DARK_GRAY + args[1] +
ChatColor.RESET + " is not a valid team.");
sender.sendMessage("Teams are " + match.getTeamList());
}
else
{
team.setSpawnLocation(player.getLocation());
String coords = BlockVector3.fromLocation(player.getLocation()).toCoords();
sender.sendMessage(ChatColor.GRAY + "Spawn set to " + coords + " for " + team.getName());
}
return true;
}
}
if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.admin"))
{
if (args.length == 2 && "world".equalsIgnoreCase(args[0]))
{
consoleWorld = getServer().getWorld(args[1]);
if (consoleWorld != null) sender.sendMessage("Selected world " + consoleWorld.getName());
return consoleWorld != null;
}
if (args.length >= 2 && "load".equalsIgnoreCase(args[0])) try
{
String mapName = args[1];
String customName = args.length >= 3 ? args[2] : null;
sender.sendMessage(ChatColor.GREEN + "Please wait...");
AutoRefMap.loadMap(sender, mapName, customName);
return true;
}
catch (Exception e) { e.printStackTrace(); return true; }
if (args.length == 1 && "unload".equalsIgnoreCase(args[0]) && match != null)
{
match.destroy();
return true;
}
if (args.length == 1 && "reload".equalsIgnoreCase(args[0]) && match != null) try
{
AutoRefMap map = AutoRefMap.getMap(match.getMapName());
if (map == null || !map.isInstalled())
{
sender.sendMessage(ChatColor.DARK_GRAY +
"No archive of this map exists " + match.getMapName());
return true;
}
sender.sendMessage(ChatColor.DARK_GRAY +
"Preparing a new copy of " + map.getVersionString());
AutoRefMatch newmatch = AutoRefMap.createMatch(map, null);
for (Player p : match.getWorld().getPlayers())
p.teleport(newmatch.getWorldSpawn());
match.destroy();
return true;
}
catch (Exception e) { e.printStackTrace(); return true; }
if (args.length == 1 && "maplist".equalsIgnoreCase(args[0]))
{
List<AutoRefMap> maps = Lists.newArrayList(AutoRefMap.getAvailableMaps());
Collections.sort(maps);
sender.sendMessage(ChatColor.GOLD + String.format("Available Maps (%d):", maps.size()));
for (AutoRefMap mapInfo : maps)
{
ChatColor color = mapInfo.isInstalled() ? ChatColor.WHITE : ChatColor.DARK_GRAY;
sender.sendMessage("* " + color + mapInfo.getVersionString());
}
return true;
}
if (args.length >= 1 && "update".equalsIgnoreCase(args[0]))
{
boolean force = (args.length >= 2 && args[1].startsWith("f"));
AutoRefMap.getUpdates(sender, force);
return true;
}
if (args.length >= 1 && "state".equalsIgnoreCase(args[0]) &&
match != null && match.isDebugMode()) try
{
if (args.length >= 2)
match.setCurrentState(MatchStatus.valueOf(args[1].toUpperCase()));
getLogger().info("Match Status is now " + match.getCurrentState().name());
return true;
}
catch (Exception e) { return false; }
if (args.length > 1 && "autoinvite".equalsIgnoreCase(args[0]))
{
for (int i = 1; i < args.length; ++i)
{
OfflinePlayer opl = getServer().getOfflinePlayer(args[i]);
for (AutoRefMatch m : getMatches()) m.removeExpectedPlayer(opl);
match.addExpectedPlayer(opl);
Player invited = getServer().getPlayer(args[i]);
if (invited == null) continue;
AutoRefMatch m = getMatch(invited.getWorld());
if (m != null && m.isPlayer(invited) && m.getCurrentState().inProgress()) continue;
match.acceptInvitation(invited);
}
return true;
}
if (args.length >= 2 && "send".equalsIgnoreCase(args[0]) &&
match != null && match.isDebugMode())
{
Set<Player> targets = match.getReferees();
if (args.length >= 3) targets = Sets.newHashSet(getServer().getPlayer(args[2]));
for (Player ref : targets) if (ref != null) ref.sendPluginMessage(this,
AutoReferee.REFEREE_PLUGIN_CHANNEL, args[1].getBytes());
return true;
}
}
if ("autoref".equalsIgnoreCase(cmd.getName()) && sender.hasPermission("autoreferee.referee"))
{
if (args.length == 3 && "teamname".equalsIgnoreCase(args[0]) && match != null)
{
AutoRefTeam team = null;
for (AutoRefTeam t : match.getTeams())
if (t.matches(args[1])) team = t;
if (team == null)
{
sender.sendMessage(ChatColor.DARK_GRAY + args[1] +
ChatColor.RESET + " is not a valid team.");
sender.sendMessage("Teams are " + match.getTeamList());
}
else team.setName(args[2]);
return true;
}
if (args.length >= 1 && "hud".equalsIgnoreCase(args[0]) && match != null)
{
if (args.length >= 2 && "swap".equalsIgnoreCase(args[1]))
{
match.messageReferee(player, "match", match.getWorld().getName(), "swap");
return true;
}
}
if (args.length == 3 && "swapteams".equalsIgnoreCase(args[0]) && match != null)
{
AutoRefTeam team1 = null, team2 = null;
for (AutoRefTeam t : match.getTeams())
{
if (t.matches(args[1])) team1 = t;
if (t.matches(args[2])) team2 = t;
}
if (team1 == null)
{
sender.sendMessage(ChatColor.DARK_GRAY + args[1] +
ChatColor.RESET + " is not a valid team.");
sender.sendMessage("Teams are " + match.getTeamList());
}
else if (team2 == null)
{
sender.sendMessage(ChatColor.DARK_GRAY + args[2] +
ChatColor.RESET + " is not a valid team.");
sender.sendMessage("Teams are " + match.getTeamList());
}
else AutoRefTeam.switchTeams(team1, team2);
return true;
}
if (args.length == 1 && "countdown".equalsIgnoreCase(args[0]) && match != null)
{
match.startCountdown(0, false);
return true;
}
}
if ("autoref".equalsIgnoreCase(cmd.getName()))
{
if (args.length > 1 && "invite".equalsIgnoreCase(args[0]) &&
match != null && match.getCurrentState().isBeforeMatch())
{
String from = (sender instanceof Player) ? match.getPlayerName(player) : "This server";
for (int i = 1; i < args.length; ++i)
{
Player invited = getServer().getPlayer(args[i]);
if (invited == null) continue;
AutoRefMatch m = getMatch(invited.getWorld());
if (m != null && m.isPlayer(invited) && m.getCurrentState().inProgress()) continue;
if (invited.getWorld() != match.getWorld())
new Conversation(this, invited, new InvitationPrompt(match, from)).begin();
}
return true;
}
if (args.length >= 1 && "version".equalsIgnoreCase(args[0]))
{
sender.sendMessage(ChatColor.DARK_GRAY + "This server is running " +
ChatColor.BLUE + this.getDescription().getFullName());
return true;
}
}
if ("zones".equalsIgnoreCase(cmd.getName()) && match != null)
{
Set<AutoRefTeam> lookupTeams = null;
if (args.length > 1)
{
AutoRefTeam t = match.teamNameLookup(args[1]);
if (t == null)
{
sender.sendMessage(ChatColor.DARK_GRAY + args[1] +
ChatColor.RESET + " is not a valid team.");
return true;
}
lookupTeams = Sets.newHashSet();
lookupTeams.add(t);
}
else lookupTeams = match.getTeams();
if (lookupTeams == null) return false;
for (AutoRefTeam team : lookupTeams)
{
sender.sendMessage(team.getName() + "'s Regions:");
if (team.getRegions().size() > 0) for (CuboidRegion reg : team.getRegions())
{
Vector3 mn = reg.getMinimumPoint(), mx = reg.getMaximumPoint();
sender.sendMessage(" (" + mn.toCoords() + ") => (" + mx.toCoords() + ")");
}
else sender.sendMessage(" <None>");
}
return true;
}
if ("zone".equalsIgnoreCase(cmd.getName()) && match != null)
{
WorldEditPlugin worldEdit = getWorldEdit();
if (worldEdit == null)
{
sender.sendMessage("This method requires WorldEdit installed and running.");
return true;
}
if (args.length == 0)
{
sender.sendMessage("Must specify a team as this zone's owner.");
return true;
}
AutoRefTeam t, START = new AutoRefTeam(); String tname = args[0];
t = "start".equals(tname) ? START : match.teamNameLookup(tname);
if (t == null)
{
sender.sendMessage(ChatColor.DARK_GRAY + tname +
ChatColor.RESET + " is not a valid team.");
sender.sendMessage("Teams are " + match.getTeamList());
return true;
}
Selection sel = worldEdit.getSelection(player);
if ((sel instanceof CuboidSelection))
{
CuboidSelection csel = (CuboidSelection) sel;
CuboidRegion reg = new CuboidRegion(
new Vector3(csel.getNativeMinimumPoint()),
new Vector3(csel.getNativeMaximumPoint())
);
if (t == START)
{
match.setStartRegion(reg);
sender.sendMessage("Region now marked as " +
"the start region!");
}
else
{
AutoRefRegion areg = new AutoRefRegion(reg);
if (args.length >= 2) for (String f : args[1].split(",")) areg.toggle(f);
t.getRegions().add(areg);
sender.sendMessage("Region now marked as " +
t.getName() + "'s zone!");
}
}
return true;
}
if ("matchinfo".equalsIgnoreCase(cmd.getName()))
{
if (match != null) match.sendMatchInfo(player);
else sender.sendMessage(ChatColor.GRAY +
this.getName() + " is not running for this world!");
return true;
}
if ("jointeam".equalsIgnoreCase(cmd.getName()) && match != null && !isAutoMode())
{
AutoRefTeam team = args.length > 0 ? match.teamNameLookup(args[0]) :
match.getArbitraryTeam();
if (team == null)
{
if (args.length > 0)
{
sender.sendMessage(ChatColor.DARK_GRAY + args[0] +
ChatColor.RESET + " is not a valid team.");
sender.sendMessage("Teams are " + match.getTeamList());
}
return true;
}
if (args.length >= 2 && player.hasPermission("autoreferee.referee"))
for (int i = 1; i < args.length; ++i)
{
Player target = getServer().getPlayer(args[i]);
if (target != null) match.joinTeam(target, team, true);
}
else match.joinTeam(player, team, player.hasPermission("autoreferee.referee"));
return true;
}
if ("leaveteam".equalsIgnoreCase(cmd.getName()) && match != null && !isAutoMode())
{
if (args.length >= 1 && player.hasPermission("autoreferee.referee"))
for (int i = 0; i < args.length; ++i)
{
Player target = getServer().getPlayer(args[i]);
if (target != null) match.leaveTeam(target, true);
}
else match.leaveTeam(player, player.hasPermission("autoreferee.referee"));
return true;
}
if ("viewinventory".equalsIgnoreCase(cmd.getName()) && args.length == 1
&& match != null && player != null)
{
if (!match.isReferee(player))
{ sender.sendMessage("You do not have permission."); return true; }
AutoRefPlayer target = match.getPlayer(getServer().getPlayer(args[0]));
if (target != null) target.showInventory(player);
return true;
}
if ("ready".equalsIgnoreCase(cmd.getName()) &&
match != null && match.getCurrentState().isBeforeMatch())
{
boolean rstate = true;
if (args.length > 0)
{
String rstr = args[0].toLowerCase();
rstate = !rstr.startsWith("f") && !rstr.startsWith("n");
}
if (match.isReferee(player))
{
if (args.length > 0) try { match.setReadyDelay(Integer.parseInt(args[0])); }
catch (NumberFormatException e) { };
match.setRefereeReady(rstate);
}
else
{
AutoRefTeam team = match.getPlayerTeam(player);
if (team != null) team.setReady(rstate);
}
match.checkTeamsStart();
return true;
}
return false;
}
|
private void updatePoster(int id){
if (cinemas_list.size() > 0){
RemoteViews view = new RemoteViews(this.myContext.getPackageName(), R.layout.afisha_widget_provider);
int cinemas_iterator = cinemas_iterators.get(id);
if (cinemas_list.size() <= cinemas_iterator){
cinemas_iterator = 0;
}
Bitmap poster = cinemas_list.get(cinemas_iterator).getPosterImg();
if (poster != null){
view.setImageViewBitmap(R.id.cinema_poster, poster);
}
poster = null;
cinemas_iterator++;
if (cinemas_list.size() <= cinemas_iterator){
cinemas_iterator = 0;
}
cinemas_iterators.put(id, cinemas_iterator);
myAppWidgetManager.updateAppWidget(id, view);
}
}
| private void updatePoster(int id){
if (cinemas_list.size() > 0){
RemoteViews view = new RemoteViews(this.myContext.getPackageName(), R.layout.afisha_widget_provider);
int cinemas_iterator = cinemas_iterators.get(id);
if (cinemas_list.size() <= cinemas_iterator){
cinemas_iterator = 0;
}
Bitmap poster = cinemas_list.get(cinemas_iterator).getPosterImg();
if (poster != null){
view.setImageViewBitmap(R.id.cinema_poster, poster);
}
cinemas_iterator++;
if (cinemas_list.size() <= cinemas_iterator){
cinemas_iterator = 0;
}
cinemas_iterators.put(id, cinemas_iterator);
myAppWidgetManager.updateAppWidget(id, view);
}
}
|
protected void executeAction() {
System.out.println("Execute action: "+varID);
if(varID!=null){
Variable v = (Variable) Services.getService().getModelMapping().get(varID);
System.out.println("VARIABLE "+v);
}
varID = model.createVariable(scopeID);
}
| protected void executeAction() {
if(varID == null)
varID = model.createVariable(scopeID);
else
model.restoreVariable(scopeID, varID);
}
|
public void initPage() throws Exception
{
initJavaScript();
URL envURL = new URL(contextURL + "/env.js");
evaluateURL(envURL);
evaluateScript("window.location = '" + contextURL + "'");
URL cometdURL = new URL(contextURL + "/org/cometd.js");
evaluateURL(cometdURL);
URL jqueryURL = new URL(contextURL + "/jquery/jquery-1.3.2.js");
evaluateURL(jqueryURL);
URL jqueryJSONURL = new URL(contextURL + "/jquery/jquery.json-2.2.js");
evaluateURL(jqueryJSONURL);
URL jqueryCometdURL = new URL(contextURL + "/jquery/jquery.cometd.js");
evaluateURL(jqueryCometdURL);
}
| public void initPage() throws Exception
{
initJavaScript();
URL envURL = new URL(contextURL + "/env.js");
evaluateURL(envURL);
evaluateScript("window.location = '" + contextURL + "'");
URL cometdURL = new URL(contextURL + "/org/cometd.js");
evaluateURL(cometdURL);
URL jqueryURL = new URL(contextURL + "/jquery/jquery-1.4.2.js");
evaluateURL(jqueryURL);
URL jqueryJSONURL = new URL(contextURL + "/jquery/jquery.json-2.2.js");
evaluateURL(jqueryJSONURL);
URL jqueryCometdURL = new URL(contextURL + "/jquery/jquery.cometd.js");
evaluateURL(jqueryCometdURL);
}
|
public void setup(BundleContext context, Map<String, String> configProperties) throws Exception
{
Enumeration<?> enUrls = context.getBundle().findEntries("/etc", "jetty.xml", false);
if (enUrls != null && enUrls.hasMoreElements())
{
URL url = (URL) enUrls.nextElement();
if (url != null)
{
url = DefaultFileLocatorHelper.getLocalURL(url);
if (url.getProtocol().equals("file"))
{
File jettyxml = new File(url.toURI());
File jettyhome = jettyxml.getParentFile().getParentFile();
System.setProperty("jetty.home", jettyhome.getAbsolutePath());
}
}
}
File _installLocation = BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(context.getBundle());
boolean bootBundleCanBeJarred = true;
String jettyHome = stripQuotesIfPresent(System.getProperty("jetty.home"));
if (jettyHome == null || jettyHome.length() == 0)
{
if (_installLocation != null)
{
if (_installLocation.getName().endsWith(".jar"))
{
jettyHome = JettyHomeHelper.setupJettyHomeInEclipsePDE(_installLocation);
}
if (jettyHome == null && _installLocation != null && _installLocation.isDirectory())
{
jettyHome = _installLocation.getAbsolutePath() + "/jettyhome";
bootBundleCanBeJarred = false;
}
}
}
if (jettyHome == null || (!bootBundleCanBeJarred && !_installLocation.isDirectory()))
{
}
else
{
System.setProperty("jetty.home",jettyHome);
}
String jettyLogs = stripQuotesIfPresent(System.getProperty("jetty.logs"));
if (jettyLogs == null || jettyLogs.length() == 0)
{
System.setProperty("jetty.logs",jettyHome + "/logs");
}
if (jettyHome != null)
{
try
{
System.err.println("JETTY_HOME set to " + new File(jettyHome).getCanonicalPath());
}
catch (Throwable t)
{
System.err.println("JETTY_HOME _set to " + new File(jettyHome).getAbsolutePath());
}
}
else
{
}
ClassLoader contextCl = Thread.currentThread().getContextClassLoader();
try
{
File jettyHomeF = jettyHome != null ? new File(jettyHome) : null;
ClassLoader libExtClassLoader = null;
try
{
libExtClassLoader = LibExtClassLoaderHelper.createLibEtcClassLoader(jettyHomeF,_server,
JettyBootstrapActivator.class.getClassLoader());
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
Thread.currentThread().setContextClassLoader(libExtClassLoader);
String jettyetc = System.getProperty(OSGiWebappConstants.SYS_PROP_JETTY_ETC_FILES,"etc/jetty.xml");
StringTokenizer tokenizer = new StringTokenizer(jettyetc,";,");
Map<Object,Object> id_map = new HashMap<Object,Object>();
id_map.put("Server",_server);
Map<Object,Object> properties = new HashMap<Object,Object>();
if (jettyHome != null)
{
properties.put("jetty.home",jettyHome);
}
properties.put("jetty.host",System.getProperty("jetty.host",""));
properties.put("jetty.port",System.getProperty("jetty.port","8080"));
properties.put("jetty.port.ssl",System.getProperty("jetty.port.ssl","8443"));
while (tokenizer.hasMoreTokens())
{
String etcFile = tokenizer.nextToken().trim();
File conffile = null;
enUrls = null;
if (etcFile.indexOf(":") != -1)
{
conffile = Resource.newResource(etcFile).getFile();
}
else if (etcFile.startsWith("/"))
{
conffile = new File(etcFile);
}
else if (jettyHomeF != null)
{
conffile = new File(jettyHomeF, etcFile);
}
else
{
int last = etcFile.lastIndexOf('/');
String path = last != -1 && last < etcFile.length() -2
? etcFile.substring(0, last) : "/";
if (!path.startsWith("/"))
{
path = "/" + path;
}
String pattern = last != -1 && last < etcFile.length() -2
? etcFile.substring(last+1) : etcFile;
enUrls = context.getBundle().findEntries(path, pattern, false);
if (pattern.equals("jetty.xml") && (enUrls == null || !enUrls.hasMoreElements()))
{
path = "/jettyhome" + path;
pattern = "jetty-osgi-default.xml";
enUrls = context.getBundle().findEntries(path, pattern, false);
System.err.println("Configuring jetty with the default embedded configuration:" +
"bundle org.eclipse.jetty.boot.osgi /jettyhome/etc/jetty-osgi-default.xml");
}
}
if (conffile != null && !conffile.exists())
{
__logger.warn("Unable to resolve the xml configuration file for jetty " + etcFile);
if ("etc/jetty.xml".equals(etcFile))
{
__logger.info("Configuring default server on 8080");
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
_server.addConnector(connector);
HandlerCollection handlers = new HandlerCollection();
ContextHandlerCollection contexts = new ContextHandlerCollection();
RequestLogHandler requestLogHandler = new RequestLogHandler();
handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
_server.setHandler(handlers);
}
}
else
{
InputStream is = null;
try
{
XmlConfiguration config = null;
if (conffile != null && conffile.exists())
{
is = new FileInputStream(conffile);
config =new XmlConfiguration(is);
}
else if (enUrls != null && enUrls.hasMoreElements())
{
URL url = (URL) enUrls.nextElement();
if (url != null)
{
is = url.openStream();
config = new XmlConfiguration(is);
}
else
{
System.err.println("Could not locate " + etcFile +
" inside " + context.getBundle().getSymbolicName());
continue;
}
}
else
{
continue;
}
config.setIdMap(id_map);
config.setProperties(properties);
config.configure();
id_map=config.getIdMap();
}
catch (SAXParseException saxparse)
{
Log.getLogger(WebappRegistrationHelper.class.getName()).warn("Unable to configure the jetty/etc file " + etcFile,saxparse);
throw saxparse;
}
finally
{
if (is != null) try { is.close(); } catch (IOException ioe) {}
}
}
}
init();
try
{
URL[] jarsWithTlds = getJarsWithTlds();
_commonParentClassLoaderForWebapps = jarsWithTlds == null?libExtClassLoader:new TldLocatableURLClassloader(libExtClassLoader,jarsWithTlds);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
_server.start();
}
catch (Throwable t)
{
t.printStackTrace();
}
finally
{
Thread.currentThread().setContextClassLoader(contextCl);
}
}
| public void setup(BundleContext context, Map<String, String> configProperties) throws Exception
{
Enumeration<?> enUrls = context.getBundle().findEntries("/etc", "jetty.xml", false);
if (enUrls != null && enUrls.hasMoreElements())
{
URL url = (URL) enUrls.nextElement();
if (url != null)
{
url = DefaultFileLocatorHelper.getLocalURL(url);
if (url.getProtocol().equals("file"))
{
File jettyxml = new File(url.toURI());
File jettyhome = jettyxml.getParentFile().getParentFile();
System.setProperty("jetty.home", jettyhome.getAbsolutePath());
}
}
}
File _installLocation = BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(context.getBundle());
boolean bootBundleCanBeJarred = true;
String jettyHome = stripQuotesIfPresent(System.getProperty("jetty.home"));
if (jettyHome == null || jettyHome.length() == 0)
{
if (_installLocation != null)
{
if (_installLocation.getName().endsWith(".jar"))
{
jettyHome = JettyHomeHelper.setupJettyHomeInEclipsePDE(_installLocation);
}
if (jettyHome == null && _installLocation != null && _installLocation.isDirectory())
{
jettyHome = _installLocation.getAbsolutePath() + "/jettyhome";
bootBundleCanBeJarred = false;
}
}
}
if (jettyHome == null || (!bootBundleCanBeJarred && !_installLocation.isDirectory()))
{
}
else
{
System.setProperty("jetty.home",jettyHome);
}
String jettyLogs = stripQuotesIfPresent(System.getProperty("jetty.logs"));
if (jettyLogs == null || jettyLogs.length() == 0)
{
System.setProperty("jetty.logs",jettyHome + "/logs");
}
if (jettyHome != null)
{
try
{
System.err.println("JETTY_HOME set to " + new File(jettyHome).getCanonicalPath());
}
catch (Throwable t)
{
System.err.println("JETTY_HOME _set to " + new File(jettyHome).getAbsolutePath());
}
}
else
{
}
ClassLoader contextCl = Thread.currentThread().getContextClassLoader();
try
{
File jettyHomeF = jettyHome != null ? new File(jettyHome) : null;
ClassLoader libExtClassLoader = null;
try
{
libExtClassLoader = LibExtClassLoaderHelper.createLibEtcClassLoader(jettyHomeF,_server,
JettyBootstrapActivator.class.getClassLoader());
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
Thread.currentThread().setContextClassLoader(libExtClassLoader);
String jettyetc = System.getProperty(OSGiWebappConstants.SYS_PROP_JETTY_ETC_FILES,"etc/jetty.xml");
StringTokenizer tokenizer = new StringTokenizer(jettyetc,";,");
Map<Object,Object> id_map = new HashMap<Object,Object>();
id_map.put("Server",_server);
Map<Object,Object> properties = new HashMap<Object,Object>();
if (jettyHome != null)
{
properties.put("jetty.home",jettyHome);
}
properties.put("jetty.host",System.getProperty("jetty.host"));
properties.put("jetty.port",System.getProperty("jetty.port"));
properties.put("jetty.port.ssl",System.getProperty("jetty.port.ssl"));
while (tokenizer.hasMoreTokens())
{
String etcFile = tokenizer.nextToken().trim();
File conffile = null;
enUrls = null;
if (etcFile.indexOf(":") != -1)
{
conffile = Resource.newResource(etcFile).getFile();
}
else if (etcFile.startsWith("/"))
{
conffile = new File(etcFile);
}
else if (jettyHomeF != null)
{
conffile = new File(jettyHomeF, etcFile);
}
else
{
int last = etcFile.lastIndexOf('/');
String path = last != -1 && last < etcFile.length() -2
? etcFile.substring(0, last) : "/";
if (!path.startsWith("/"))
{
path = "/" + path;
}
String pattern = last != -1 && last < etcFile.length() -2
? etcFile.substring(last+1) : etcFile;
enUrls = context.getBundle().findEntries(path, pattern, false);
if (pattern.equals("jetty.xml") && (enUrls == null || !enUrls.hasMoreElements()))
{
path = "/jettyhome" + path;
pattern = "jetty-osgi-default.xml";
enUrls = context.getBundle().findEntries(path, pattern, false);
System.err.println("Configuring jetty with the default embedded configuration:" +
"bundle org.eclipse.jetty.boot.osgi /jettyhome/etc/jetty-osgi-default.xml");
}
}
if (conffile != null && !conffile.exists())
{
__logger.warn("Unable to resolve the xml configuration file for jetty " + etcFile);
if ("etc/jetty.xml".equals(etcFile))
{
__logger.info("Configuring default server on 8080");
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
_server.addConnector(connector);
HandlerCollection handlers = new HandlerCollection();
ContextHandlerCollection contexts = new ContextHandlerCollection();
RequestLogHandler requestLogHandler = new RequestLogHandler();
handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
_server.setHandler(handlers);
}
}
else
{
InputStream is = null;
try
{
XmlConfiguration config = null;
if (conffile != null && conffile.exists())
{
is = new FileInputStream(conffile);
config =new XmlConfiguration(is);
}
else if (enUrls != null && enUrls.hasMoreElements())
{
URL url = (URL) enUrls.nextElement();
if (url != null)
{
is = url.openStream();
config = new XmlConfiguration(is);
}
else
{
System.err.println("Could not locate " + etcFile +
" inside " + context.getBundle().getSymbolicName());
continue;
}
}
else
{
continue;
}
config.setIdMap(id_map);
config.setProperties(properties);
config.configure();
id_map=config.getIdMap();
}
catch (SAXParseException saxparse)
{
Log.getLogger(WebappRegistrationHelper.class.getName()).warn("Unable to configure the jetty/etc file " + etcFile,saxparse);
throw saxparse;
}
finally
{
if (is != null) try { is.close(); } catch (IOException ioe) {}
}
}
}
init();
try
{
URL[] jarsWithTlds = getJarsWithTlds();
_commonParentClassLoaderForWebapps = jarsWithTlds == null?libExtClassLoader:new TldLocatableURLClassloader(libExtClassLoader,jarsWithTlds);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
_server.start();
}
catch (Throwable t)
{
t.printStackTrace();
}
finally
{
Thread.currentThread().setContextClassLoader(contextCl);
}
}
|
public void run() {
boolean loop = true;
CommandParser cmdparse = new CommandParser();
while (loop) {
boolean word = false;
while (!word) {
try {
cmdparse.enqueue((char)in.read());
} catch (IOException e) {
System.err.println(e.toString());
close();
return;
} catch (InterruptedException e) {
close();
return;
}
while (!cmdparse.isOutputEmpty()) {
Command cmd = cmdparse.dequeue();
switch (cmd.getCommandType()) {
case MINITIALISE:
for (MapListener l : listeners.getListeners(MapListener.class))
l.updateMap(new HorizontalNode(0,1000,0,1000));
case MPOSITION:
for (MapListener l : listeners.getListeners(MapListener.class))
l.updateMapPosition(((MPositionCommand)cmd).getPosition());
case RSTATUS:
for (RobotListener l : listeners.getListeners(RobotListener.class)) {
RStatusCommand rcmd = (RStatusCommand)cmd;
l.updateAngle(rcmd.getAngleDegrees(), rcmd.getAngleRadians());
l.updateRobotPosition(rcmd.getPosition());
l.updateVoltage(rcmd.getVoltage());
}
case RLOCK:
case RUNLOCK:
for (RobotListener l : listeners.getListeners(RobotListener.class))
l.updateLocked(cmd.getCommandType() == CommandType.RLOCK);
}
}
}
}
}
| public void run() {
boolean loop = true;
CommandParser cmdparse = new CommandParser();
while (loop) {
boolean word = false;
while (!word) {
try {
cmdparse.enqueue((char)in.read());
} catch (IOException e) {
System.err.println(e.toString());
close();
return;
} catch (InterruptedException e) {
close();
return;
}
while (!cmdparse.isOutputEmpty()) {
Command cmd = cmdparse.dequeue();
switch (cmd.getCommandType()) {
case MINITIALISE:
for (MapListener l : listeners.getListeners(MapListener.class))
l.updateMap(new HorizontalNode(0,1000,0,1000));
break;
case MPOSITION:
for (MapListener l : listeners.getListeners(MapListener.class))
l.updateMapPosition(((MPositionCommand)cmd).getPosition());
break;
case RSTATUS:
for (RobotListener l : listeners.getListeners(RobotListener.class)) {
RStatusCommand rcmd = (RStatusCommand)cmd;
l.updateAngle(rcmd.getAngleDegrees(), rcmd.getAngleRadians());
l.updateRobotPosition(rcmd.getPosition());
l.updateVoltage(rcmd.getVoltage());
}
break;
case RLOCK:
case RUNLOCK:
for (RobotListener l : listeners.getListeners(RobotListener.class))
l.updateLocked(cmd.getCommandType() == CommandType.RLOCK);
break;
}
}
}
}
}
|
public String getAspectValueLabel(AspectValue value, String locale,
URI resourceRole, URI linkRole) {
URI aspectId = getAspect().getId();
String valueId = value.getId();
try {
String label = cache.getLabel(aspectId, valueId, locale, resourceRole, linkRole);
if (label != null) {
return label;
}
label = labeller.getAspectValueLabel(value, locale, resourceRole, linkRole);
this.cache.cacheLabel(aspectId, valueId,locale, resourceRole,linkRole, label);
return label;
} catch (Throwable e) {
String label = labeller.getAspectValueLabel(value,locale,resourceRole,linkRole);
try {
this.cache.cacheLabel(aspectId, valueId,locale, resourceRole,linkRole, label);
} catch (XBRLException x) {
;
}
return label;
}
}
| public String getAspectValueLabel(AspectValue value, String locale,
URI resourceRole, URI linkRole) {
URI aspectId = getAspect().getId();
String valueId = value.getId();
try {
String label = cache.getLabel(aspectId, valueId, locale, resourceRole, linkRole);
if (label != null) {
return label;
}
label = labeller.getAspectValueLabel(value, locale, resourceRole, linkRole);
this.cache.cacheLabel(aspectId, valueId, locale, resourceRole,linkRole, label);
return label;
} catch (Throwable e) {
String label = labeller.getAspectValueLabel(value,locale,resourceRole,linkRole);
try {
this.cache.cacheLabel(aspectId, valueId,locale, resourceRole,linkRole, label);
} catch (XBRLException x) {
;
}
return label;
}
}
|
Object getRequest(String path, Map params, Class resultClass)
throws IOException, JAXBException
{
GetMethod method = getHttpGetMethod();
String protocol = _isSecure ? "https" : "http";
StringBuffer query = new StringBuffer(path);
if (query.charAt(query.length() - 1) != '?') {
query.append("?");
}
for (Iterator i = params.keySet().iterator(); i.hasNext(); ) {
String key = (String)i.next();
String value = (String)params.get(key);
if (value != null) {
query.append(urlEncode(key)).append("=").append(urlEncode(value));
}
if (i.hasNext()) {
query.append("&");
}
}
URL url = new URL(protocol, _host, _port, query.toString());
_log.debug("HTTP Request: " + url.toString());
method.setURI(new URI(url.toString(), true));
int code;
try {
code = getHttpClient().executeMethod(method);
} catch (SocketException e) {
throw new HttpException("Error issuing request", e);
}
if (code == 200) {
if (resultClass != null) {
if (_log.isDebugEnabled()) {
_log.debug("HTTP Response: " +
method.getResponseBodyAsString());
}
InputStream is = method.getResponseBodyAsStream();
return deserialize(resultClass, is);
}
} else {
throw new HttpException("Invalid HTTP return code " + code);
}
return null;
}
| Object getRequest(String path, Map params, Class resultClass)
throws IOException, JAXBException
{
GetMethod method = getHttpGetMethod();
String protocol = _isSecure ? "https" : "http";
StringBuffer query = new StringBuffer(path);
if (query.charAt(query.length() - 1) != '?') {
query.append("?");
}
int idx = 0;
for (Iterator i = params.keySet().iterator(); i.hasNext(); idx++) {
String key = (String)i.next();
String value = (String)params.get(key);
if (value != null) {
if (idx > 0) {
query.append("&");
}
query.append(key).append("=").append(urlEncode(value));
}
}
URL url = new URL(protocol, _host, _port, query.toString());
_log.debug("HTTP Request: " + url.toString());
method.setURI(new URI(url.toString(), true));
int code;
try {
code = getHttpClient().executeMethod(method);
} catch (SocketException e) {
throw new HttpException("Error issuing request", e);
}
if (code == 200) {
if (resultClass != null) {
if (_log.isDebugEnabled()) {
_log.debug("HTTP Response: " +
method.getResponseBodyAsString());
}
InputStream is = method.getResponseBodyAsStream();
return deserialize(resultClass, is);
}
} else {
throw new HttpException("Invalid HTTP return code " + code);
}
return null;
}
|
protected Control createContents(Composite parent) {
model = NotificationsPlugin.getDefault().createModelWorkingCopy();
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
enableNotificationsButton = new Button(composite, SWT.CHECK);
GridDataFactory.fillDefaults().span(2, 1).applyTo(enableNotificationsButton);
enableNotificationsButton.setText(Messages.NotificationsPreferencesPage_Enable_Notifications_Text);
enableNotificationsButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateEnablement();
}
});
Label label = new Label(composite, SWT.NONE);
label.setText(" ");
GridDataFactory.fillDefaults().span(2, 1).applyTo(label);
label = new Label(composite, SWT.NONE);
label.setText(Messages.NotificationsPreferencesPage_Events_Label);
label = new Label(composite, SWT.NONE);
label.setText(Messages.NotificationsPreferencesPage_Notifiers_Label);
FilteredTree tree = new FilteredTree(composite, SWT.BORDER, new SubstringPatternFilter(), true);
eventsViewer = tree.getViewer();
GridDataFactory.fillDefaults().span(1, 2).grab(false, true).applyTo(tree);
eventsViewer.setComparer(new NotificationEventComparer());
eventsViewer.setContentProvider(new EventContentProvider());
eventsViewer.setLabelProvider(new NotificationLabelProvider());
eventsViewer.setInput(model.getCategories().toArray());
eventsViewer.expandAll();
eventsViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object input = getDetailsInput((IStructuredSelection) event.getSelection());
notifiersViewer.setInput(input);
Object item = ((IStructuredSelection) event.getSelection()).getFirstElement();
if (item instanceof NotificationEvent) {
descriptionText.setText(((NotificationEvent) item).getDescription());
notifiersViewer.getControl().setEnabled(true);
} else {
descriptionText.setText(" ");
notifiersViewer.getControl().setEnabled(false);
}
}
private Object getDetailsInput(IStructuredSelection selection) {
Object item = selection.getFirstElement();
if (item instanceof NotificationEvent) {
return model.getOrCreateNotificationHandler((NotificationEvent) item);
}
return null;
}
});
notifiersViewer = CheckboxTableViewer.newCheckList(composite, SWT.BORDER);
GridDataFactory.fillDefaults().grab(true, true).applyTo(notifiersViewer.getControl());
notifiersViewer.setContentProvider(new NotifiersContentProvider());
notifiersViewer.setLabelProvider(new NotificationLabelProvider());
notifiersViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
NotificationAction action = (NotificationAction) event.getElement();
action.setSelected(event.getChecked());
model.updateStates();
model.setDirty(true);
eventsViewer.refresh();
}
});
notifiersViewer.setCheckStateProvider(new ICheckStateProvider() {
public boolean isChecked(Object element) {
return ((NotificationAction) element).isSelected();
}
public boolean isGrayed(Object element) {
return false;
}
});
notifiersViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object item = ((IStructuredSelection) event.getSelection()).getFirstElement();
if (item instanceof NotificationAction) {
}
}
});
Group group = new Group(composite, SWT.BORDER);
GridDataFactory.fillDefaults().hint(150, SWT.DEFAULT).grab(true, true).applyTo(group);
group.setText(Messages.NotificationsPreferencesPage_Descriptions_Label);
FillLayout layout = new FillLayout();
layout.marginHeight = 5;
layout.marginWidth = 5;
group.setLayout(layout);
descriptionText = new Text(group, SWT.WRAP);
descriptionText.setBackground(group.getBackground());
reset();
Dialog.applyDialogFont(composite);
return composite;
}
| protected Control createContents(Composite parent) {
model = NotificationsPlugin.getDefault().createModelWorkingCopy();
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
enableNotificationsButton = new Button(composite, SWT.CHECK);
GridDataFactory.fillDefaults().span(2, 1).applyTo(enableNotificationsButton);
enableNotificationsButton.setText(Messages.NotificationsPreferencesPage_Enable_Notifications_Text);
enableNotificationsButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateEnablement();
}
});
Label label = new Label(composite, SWT.NONE);
label.setText(" ");
GridDataFactory.fillDefaults().span(2, 1).applyTo(label);
label = new Label(composite, SWT.NONE);
label.setText(Messages.NotificationsPreferencesPage_Events_Label);
label = new Label(composite, SWT.NONE);
label.setText(Messages.NotificationsPreferencesPage_Notifiers_Label);
FilteredTree tree = new FilteredTree(composite, SWT.BORDER, new SubstringPatternFilter(), true);
eventsViewer = tree.getViewer();
GridDataFactory.fillDefaults().span(1, 2).grab(false, true).applyTo(tree);
eventsViewer.setComparer(new NotificationEventComparer());
eventsViewer.setContentProvider(new EventContentProvider());
eventsViewer.setLabelProvider(new NotificationLabelProvider());
eventsViewer.setInput(model.getCategories().toArray());
eventsViewer.expandAll();
eventsViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object input = getDetailsInput((IStructuredSelection) event.getSelection());
notifiersViewer.setInput(input);
Object item = ((IStructuredSelection) event.getSelection()).getFirstElement();
if (item instanceof NotificationEvent) {
descriptionText.setText(((NotificationEvent) item).getDescription());
notifiersViewer.getControl().setEnabled(true);
} else {
descriptionText.setText(" ");
notifiersViewer.getControl().setEnabled(false);
}
}
private Object getDetailsInput(IStructuredSelection selection) {
Object item = selection.getFirstElement();
if (item instanceof NotificationEvent) {
return model.getOrCreateNotificationHandler((NotificationEvent) item);
}
return null;
}
});
notifiersViewer = CheckboxTableViewer.newCheckList(composite, SWT.BORDER);
GridDataFactory.fillDefaults().grab(true, true).applyTo(notifiersViewer.getControl());
notifiersViewer.setContentProvider(new NotifiersContentProvider());
notifiersViewer.setLabelProvider(new NotificationLabelProvider());
notifiersViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
NotificationAction action = (NotificationAction) event.getElement();
action.setSelected(event.getChecked());
model.updateStates();
model.setDirty(true);
eventsViewer.refresh();
}
});
notifiersViewer.setCheckStateProvider(new ICheckStateProvider() {
public boolean isChecked(Object element) {
return ((NotificationAction) element).isSelected();
}
public boolean isGrayed(Object element) {
return false;
}
});
notifiersViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object item = ((IStructuredSelection) event.getSelection()).getFirstElement();
if (item instanceof NotificationAction) {
}
}
});
Group group = new Group(composite, SWT.NONE);
GridDataFactory.fillDefaults().hint(150, SWT.DEFAULT).grab(true, true).applyTo(group);
group.setText(Messages.NotificationsPreferencesPage_Descriptions_Label);
FillLayout layout = new FillLayout();
layout.marginHeight = 5;
layout.marginWidth = 5;
group.setLayout(layout);
descriptionText = new Text(group, SWT.WRAP);
descriptionText.setBackground(group.getBackground());
reset();
Dialog.applyDialogFont(composite);
return composite;
}
|
public String getCommentWithPrompt(Shell shell) {
final String comment= getComment(false);
if (comment.length() == 0) {
final IPreferenceStore store= CVSUIPlugin.getPlugin().getPreferenceStore();
final String value= store.getString(ICVSUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS);
if (MessageDialogWithToggle.NEVER.equals(value))
return null;
if (MessageDialogWithToggle.PROMPT.equals(value)) {
final String title= Policy.bind("CommitWizard.3");
final String message= Policy.bind("CommitWizard.4");
final String toggleMessage= Policy.bind("CommitWizard.5");
final MessageDialogWithToggle dialog= MessageDialogWithToggle.openYesNoQuestion(shell, title, message, toggleMessage, false, store, ICVSUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS);
if (dialog.getReturnCode() == IDialogConstants.NO_ID) {
fTextBox.setFocus();
return null;
}
}
}
return getComment(true);
}
| public String getCommentWithPrompt(Shell shell) {
final String comment= getComment(false);
if (comment.length() == 0) {
final IPreferenceStore store= CVSUIPlugin.getPlugin().getPreferenceStore();
final String value= store.getString(ICVSUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS);
if (MessageDialogWithToggle.NEVER.equals(value))
return null;
if (MessageDialogWithToggle.PROMPT.equals(value)) {
final String title= Policy.bind("CommitCommentArea.2");
final String message= Policy.bind("CommitCommentArea.3");
final String toggleMessage= Policy.bind("CommitCommentArea.4");
final MessageDialogWithToggle dialog= MessageDialogWithToggle.openYesNoQuestion(shell, title, message, toggleMessage, false, store, ICVSUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS);
if (dialog.getReturnCode() == IDialogConstants.NO_ID) {
fTextBox.setFocus();
return null;
}
}
}
return getComment(true);
}
|
public boolean shouldBeIncluded(String fqClassName) {
if (includePattern == null || includePattern.trim().equals("")) {
setIncludePattern("\\(.*\\)");
}
Matcher matcher = pattern.matcher(fqClassName);
return matcher.find();
}
| public boolean shouldBeIncluded(String fqClassName) {
if (includePattern == null || includePattern.trim().equals("")) {
setIncludePattern("(.*)");
}
Matcher matcher = pattern.matcher(fqClassName);
return matcher.find();
}
|
protected void onBeforePasswordHook(Composite parent) {
super.onBeforePasswordHook(parent);
Label labelAuthenticationType = new Label(parent, SWT.NONE);
labelAuthenticationType.setText(Messages.getString("ProtocolSpecificComposite.FTPAuthType"));
comboAuthentication = new Combo(parent, SWT.READ_ONLY);
GridData comboAuthenticationData = new GridData();
comboAuthenticationData.horizontalSpan = 2;
comboAuthenticationData.horizontalAlignment = SWT.FILL;
comboAuthentication.setLayoutData(comboAuthenticationData);
comboAuthentication.add(Messages.getString("ProtocolSpecificComposite.FTPAuthTypeAnonymous"));
comboAuthentication.add(Messages.getString("ProtocolSpecificComposite.FTPAuthTypeUserPassword"));
comboAuthentication.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
setUserPasswordEnabled(comboAuthentication.getSelectionIndex() == 1);
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
| protected void onBeforePasswordHook(Composite parent) {
super.onBeforePasswordHook(parent);
Label labelAuthenticationType = new Label(parent, SWT.NONE);
labelAuthenticationType.setText(Messages.getString("ProtocolSpecificComposite.FTPAuthType"));
comboAuthentication = new Combo(parent, SWT.READ_ONLY);
GridData comboAuthenticationData = new GridData();
comboAuthenticationData.horizontalSpan = 2;
comboAuthenticationData.horizontalAlignment = SWT.FILL;
comboAuthentication.setLayoutData(comboAuthenticationData);
comboAuthentication.add(Messages.getString("ProtocolSpecificComposite.FTPAuthTypeAnonymous"));
comboAuthentication.add(Messages.getString("ProtocolSpecificComposite.FTPAuthTypeUserPassword"));
comboAuthentication.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
setUserPasswordEnabled(comboAuthentication.getSelectionIndex() == 1);
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
comboAuthentication.select(0);
}
|
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.hasBlock() && event.getClickedBlock().getType() == Material.WALL_SIGN) {
Sign s = (Sign) event.getClickedBlock().getState();
if (s.getLine(0).equalsIgnoreCase("") && !s.getLine(1).equalsIgnoreCase("") && s.getLine(2).equalsIgnoreCase("") && s.getLine(3).equalsIgnoreCase("")) {
String className = ChatColor.stripColor(s.getLine(1));
SCBClass sc = new SCBClass(className);
sc.apply(SCBGameManager.getInstance().getCraftBrother(event.getPlayer()));
}
if (s.getLine(0).equalsIgnoreCase("SuperCraftBros")) {
String mapName = ChatColor.stripColor(s.getLine(1));
SCBGameManager.getInstance().getGame(mapName).joinGame(event.getPlayer());
}
}
for (SCBGame game : SCBGameManager.getInstance().getAllGames()) {
}
}
| public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.hasBlock() && event.getClickedBlock().getType() == Material.WALL_SIGN) {
Sign s = (Sign) event.getClickedBlock().getState();
if (s.getLine(0).equalsIgnoreCase("") && !s.getLine(1).equalsIgnoreCase("") && s.getLine(2).equalsIgnoreCase("") && s.getLine(3).equalsIgnoreCase("")) {
String className = ChatColor.stripColor(s.getLine(1));
SCBClass sc = new SCBClass(className);
sc.apply(SCBGameManager.getInstance().getCraftBrother(event.getPlayer()));
}
if (s.getLine(0).equalsIgnoreCase("SuperCraftBros")) {
String mapName = ChatColor.stripColor(s.getLine(1));
SCBGameManager.getInstance().getGame(mapName).joinLobby(event.getPlayer());
}
}
for (SCBGame game : SCBGameManager.getInstance().getAllGames()) {
}
}
|
public DbObj objForCursor(Cursor cursor) {
try {
long localId = -1;
String appId = null;
String type = null;
JSONObject json = null;
long senderId = -1;
long hash = -1;
String name = null;
long seqNum = -1;
Integer intKey = null;
long timestamp = -1;
try {
localId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_ID));
} catch (IllegalArgumentException e) {
}
try {
appId = cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_APP_ID));
} catch (IllegalArgumentException e) {
}
try {
type = cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_TYPE));
} catch (IllegalArgumentException e) {
}
try {
json = new JSONObject(
cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_JSON)));
} catch (IllegalArgumentException e) {
}
try {
senderId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_CONTACT_ID));
} catch (IllegalArgumentException e) {
}
try {
hash = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_HASH));
} catch (IllegalArgumentException e) {
}
try {
name = cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_FEED_NAME));
} catch (IllegalArgumentException e) {
}
try {
seqNum = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_SEQUENCE_ID));
} catch (IllegalArgumentException e) {
}
try {
intKey = cursor.getInt(cursor.getColumnIndexOrThrow(DbObj.COL_KEY_INT));
} catch (IllegalArgumentException e) {
}
try {
timestamp = cursor.getInt(cursor.getColumnIndexOrThrow(DbObj.COL_TIMESTAMP));
} catch (IllegalArgumentException e) {
}
final Uri feedUri = DbFeed.uriForName(name);
final byte[] raw;
int rawIndex = cursor.getColumnIndex(DbObj.COL_RAW);
if (rawIndex == -1) {
raw = null;
} else {
raw = cursor.getBlob(cursor.getColumnIndexOrThrow(DbObj.COL_RAW));
}
return new DbObj(this, appId, type, json, localId, hash, raw, senderId, seqNum,
feedUri, intKey, timestamp);
} catch (JSONException e) {
Log.e(TAG, "Couldn't parse obj.", e);
return null;
}
}
| public DbObj objForCursor(Cursor cursor) {
try {
long localId = -1;
String appId = null;
String type = null;
JSONObject json = null;
long senderId = -1;
long hash = -1;
String name = null;
long seqNum = -1;
Integer intKey = null;
long timestamp = -1;
try {
localId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_ID));
} catch (IllegalArgumentException e) {
}
try {
appId = cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_APP_ID));
} catch (IllegalArgumentException e) {
}
try {
type = cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_TYPE));
} catch (IllegalArgumentException e) {
}
try {
json = new JSONObject(
cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_JSON)));
} catch (IllegalArgumentException e) {
}
try {
senderId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_CONTACT_ID));
} catch (IllegalArgumentException e) {
}
try {
hash = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_HASH));
} catch (IllegalArgumentException e) {
}
try {
name = cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_FEED_NAME));
} catch (IllegalArgumentException e) {
}
try {
seqNum = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_SEQUENCE_ID));
} catch (IllegalArgumentException e) {
}
try {
intKey = cursor.getInt(cursor.getColumnIndexOrThrow(DbObj.COL_KEY_INT));
} catch (IllegalArgumentException e) {
}
try {
timestamp = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_TIMESTAMP));
} catch (IllegalArgumentException e) {
}
final Uri feedUri = DbFeed.uriForName(name);
final byte[] raw;
int rawIndex = cursor.getColumnIndex(DbObj.COL_RAW);
if (rawIndex == -1) {
raw = null;
} else {
raw = cursor.getBlob(cursor.getColumnIndexOrThrow(DbObj.COL_RAW));
}
return new DbObj(this, appId, type, json, localId, hash, raw, senderId, seqNum,
feedUri, intKey, timestamp);
} catch (JSONException e) {
Log.e(TAG, "Couldn't parse obj.", e);
return null;
}
}
|
public void init(Properties properties) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore ts = KeyStore.getInstance("JKS");
String keyStorePassword = getProperty(properties, "keyStorePassword");
String keyStore = getProperty(properties, "keyStore");
if (keyStore == null || keyStorePassword == null) {
throw new RuntimeException("SSL is enabled but keyStore[Password] properties aren't set!");
}
String trustStore = getProperty(properties, "trustStore", keyStore);
String trustStorePassword = getProperty(properties, "trustStorePassword", keyStorePassword);
String keyManagerAlgorithm = properties.getProperty("keyManagerAlgorithm", TrustManagerFactory.getDefaultAlgorithm());
String trustManagerAlgorithm = properties.getProperty("trustManagerAlgorithm", TrustManagerFactory.getDefaultAlgorithm());
String protocol = properties.getProperty("protocol", "TLS");
final char[] keyStorePassPhrase = keyStorePassword.toCharArray();
loadKeyStore(ks, keyStorePassPhrase, keyStore);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
kmf.init(ks, keyStorePassPhrase);
loadKeyStore(ts, trustStorePassword.toCharArray(), trustStore);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
tmf.init(ts);
sslContext = SSLContext.getInstance(protocol);
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
}
| public void init(Properties properties) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore ts = KeyStore.getInstance("JKS");
String keyStorePassword = getProperty(properties, "keyStorePassword");
String keyStore = getProperty(properties, "keyStore");
if (keyStore == null || keyStorePassword == null) {
throw new RuntimeException("SSL is enabled but keyStore[Password] properties aren't set!");
}
String trustStore = getProperty(properties, "trustStore", keyStore);
String trustStorePassword = getProperty(properties, "trustStorePassword", keyStorePassword);
String keyManagerAlgorithm = properties.getProperty("keyManagerAlgorithm", KeyManagerFactory.getDefaultAlgorithm());
String trustManagerAlgorithm = properties.getProperty("trustManagerAlgorithm", TrustManagerFactory.getDefaultAlgorithm());
String protocol = properties.getProperty("protocol", "TLS");
final char[] keyStorePassPhrase = keyStorePassword.toCharArray();
loadKeyStore(ks, keyStorePassPhrase, keyStore);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
kmf.init(ks, keyStorePassPhrase);
loadKeyStore(ts, trustStorePassword.toCharArray(), trustStore);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
tmf.init(ts);
sslContext = SSLContext.getInstance(protocol);
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
}
|
public String toPrettyString( String relatedPart ) {
if ( days == 0 && seconds == 0 ) return (relatedPart == null ? "" : "At the "+relatedPart+".");
StringBuilder result = new StringBuilder("");
if ( seconds == 0 && ((days / 7) * 7) == days ) {
result.append(Integer.toString((Math.abs(days) / 7)));
result.append(" week");
if ( days > 7 ) result.append("s");
}
else {
if ( days != 0 ) {
result.append(Math.abs(days));
result.append(" day");
if ( days > 1 ) result.append("s");
}
if ( seconds != 0) {
if ( days > 0 ) result.append(", ");
int s = Math.abs(seconds);
int h = s / 3600;
s -= (h*3600);
int m = s / 60;
s -= (m*60);
if ( h > 0 ) {
result.append(h);
result.append(" hour");
if ( h > 1 ) result.append("s");
}
if ( m > 0 ) {
if ( h > 0 ) result.append(", ");
result.append(m);
result.append(" minute");
if ( m > 1 ) result.append("s");
}
if ( s > 0 ) {
if ( m > 0 || h > 0 ) result.append(", ");
result.append(s);
result.append(" second");
if ( s > 1 ) result.append("s");
}
}
}
result.append( days < 0 || seconds < 0 ? " before" : " after" );
if ( relatedPart != null ) {
result.append(" ");
result.append(relatedPart);
}
result.append(".");
return result.toString();
}
| public String toPrettyString( String relatedPart ) {
if ( days == 0 && seconds == 0 ) return (relatedPart == null ? "" : "At the "+relatedPart+".");
StringBuilder result = new StringBuilder("");
if ( seconds == 0 && ((days / 7) * 7) == days ) {
result.append(Integer.toString((Math.abs(days) / 7)));
result.append(" week");
if ( Math.abs(days) > 7 ) result.append("s");
}
else {
if ( days != 0 ) {
result.append(Math.abs(days));
result.append(" day");
if ( Math.abs(days) > 1 ) result.append("s");
}
if ( seconds != 0) {
if ( Math.abs(days) > 0 ) result.append(", ");
int s = Math.abs(seconds);
int h = s / 3600;
s -= (h*3600);
int m = s / 60;
s -= (m*60);
if ( h > 0 ) {
result.append(h);
result.append(" hour");
if ( h > 1 ) result.append("s");
}
if ( m > 0 ) {
if ( h > 0 ) result.append(", ");
result.append(m);
result.append(" minute");
if ( m > 1 ) result.append("s");
}
if ( s > 0 ) {
if ( m > 0 || (h > 0 && m == 0) ) result.append(", ");
result.append(s);
result.append(" second");
if ( s > 1 ) result.append("s");
}
}
}
result.append( days < 0 || seconds < 0 ? " before" : " after" );
if ( relatedPart != null ) {
result.append(" ");
result.append(relatedPart);
}
result.append(".");
return result.toString();
}
|
public SettingsFrame() {
setTitle("DavMail Settings");
JPanel panel = new JPanel(new GridLayout(5, 2));
panel.setBorder(BorderFactory.createTitledBorder("Gateway settings"));
final JTextField urlField = new JTextField(Settings.getProperty("davmail.url"), 15);
urlField.setToolTipText("Base outlook web access URL");
final JTextField popPortField = new JTextField(Settings.getProperty("davmail.popPort"), 4);
final JTextField smtpPortField = new JTextField(Settings.getProperty("davmail.smtpPort"), 4);
final JTextField keepDelayField = new JTextField(Settings.getProperty("davmail.keepDelay"), 4);
keepDelayField.setToolTipText("Number of days to keep messages in trash");
final JCheckBox allowRemoteField = new JCheckBox();
allowRemoteField.setSelected(Settings.getBooleanProperty("davmail.allowRemote"));
allowRemoteField.setToolTipText("Allow remote connections to the gateway (server mode)");
addSettingComponent(panel, "OWA url: ", urlField);
addSettingComponent(panel, "Local POP port: ", popPortField);
addSettingComponent(panel, "Local SMTP port: ", smtpPortField);
addSettingComponent(panel, "Keep Delay: ", keepDelayField);
addSettingComponent(panel, "Allow Remote Connections: ", allowRemoteField);
add("North", panel);
panel = new JPanel(new GridLayout(5, 2));
panel.setBorder(BorderFactory.createTitledBorder("Proxy settings"));
boolean enableProxy = Settings.getBooleanProperty("davmail.allowRemote");
final JCheckBox enableProxyField = new JCheckBox();
enableProxyField.setSelected(enableProxy);
final JTextField httpProxyField = new JTextField(Settings.getProperty("davmail.proxyHost"), 15);
final JTextField httpProxyPortField = new JTextField(Settings.getProperty("davmail.proxyPort"), 4);
final JTextField httpProxyUserField = new JTextField(Settings.getProperty("davmail.proxyUser"), 4);
final JTextField httpProxyPasswordField = new JPasswordField(Settings.getProperty("davmail.proxyPassword"), 4);
httpProxyField.setEnabled(enableProxy);
httpProxyPortField.setEnabled(enableProxy);
httpProxyUserField.setEnabled(enableProxy);
httpProxyPasswordField.setEnabled(enableProxy);
enableProxyField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
boolean enableProxy = enableProxyField.isSelected();
httpProxyField.setEnabled(enableProxy);
httpProxyPortField.setEnabled(enableProxy);
httpProxyUserField.setEnabled(enableProxy);
httpProxyPasswordField.setEnabled(enableProxy);
}
});
addSettingComponent(panel, "Enable proxy: ", enableProxyField);
addSettingComponent(panel, "Proxy server: ", httpProxyField);
addSettingComponent(panel, "Proxy port: ", httpProxyPortField);
addSettingComponent(panel, "Proxy user: ", httpProxyUserField);
addSettingComponent(panel, "Proxy password: ", httpProxyPasswordField);
add("Center", panel);
panel = new JPanel();
JButton cancel = new JButton("Cancel");
JButton ok = new JButton("Save");
ActionListener save = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Settings.setProperty("davmail.url", urlField.getText());
Settings.setProperty("davmail.popPort", popPortField.getText());
Settings.setProperty("davmail.smtpPort", smtpPortField.getText());
Settings.setProperty("davmail.keepDelay", keepDelayField.getText());
Settings.setProperty("davmail.allowRemote", String.valueOf(allowRemoteField.isSelected()));
Settings.setProperty("davmail.enableProxy", String.valueOf(enableProxyField.isSelected()));
Settings.setProperty("davmail.proxyHost", httpProxyField.getText());
Settings.setProperty("davmail.proxyPort", httpProxyPortField.getText());
Settings.setProperty("davmail.proxyUser", httpProxyUserField.getText());
Settings.setProperty("davmail.proxyPassword", httpProxyPasswordField.getText());
Settings.save();
setVisible(false);
DavGateway.start();
}
};
ok.addActionListener(save);
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
urlField.setText(Settings.getProperty("davmail.url"));
popPortField.setText(Settings.getProperty("davmail.popPort"));
smtpPortField.setText(Settings.getProperty("davmail.smtpPort"));
keepDelayField.setText(Settings.getProperty("davmail.keepDelay"));
allowRemoteField.setSelected(Settings.getBooleanProperty(("davmail.allowRemote")));
boolean enableProxy = Settings.getBooleanProperty("davmail.allowRemote");
enableProxyField.setSelected(enableProxy);
httpProxyField.setEnabled(enableProxy);
httpProxyPortField.setEnabled(enableProxy);
httpProxyUserField.setEnabled(enableProxy);
httpProxyPasswordField.setEnabled(enableProxy);
httpProxyField.setText(Settings.getProperty("davmail.proxyHost"));
httpProxyPortField.setText(Settings.getProperty("davmail.proxyPort"));
httpProxyUserField.setText(Settings.getProperty("davmail.proxyUser"));
httpProxyPasswordField.setText(Settings.getProperty("davmail.proxyPassword"));
setVisible(false);
}
});
panel.add(ok);
panel.add(cancel);
add("South", panel);
pack();
setResizable(false);
setLocation(getToolkit().getScreenSize().width / 2 -
getSize().width / 2,
getToolkit().getScreenSize().height / 2 -
getSize().height / 2);
urlField.requestFocus();
}
| public SettingsFrame() {
setTitle("DavMail Settings");
JPanel panel = new JPanel(new GridLayout(5, 2));
panel.setBorder(BorderFactory.createTitledBorder("Gateway settings"));
final JTextField urlField = new JTextField(Settings.getProperty("davmail.url"), 15);
urlField.setToolTipText("Base outlook web access URL");
final JTextField popPortField = new JTextField(Settings.getProperty("davmail.popPort"), 4);
final JTextField smtpPortField = new JTextField(Settings.getProperty("davmail.smtpPort"), 4);
final JTextField keepDelayField = new JTextField(Settings.getProperty("davmail.keepDelay"), 4);
keepDelayField.setToolTipText("Number of days to keep messages in trash");
final JCheckBox allowRemoteField = new JCheckBox();
allowRemoteField.setSelected(Settings.getBooleanProperty("davmail.allowRemote"));
allowRemoteField.setToolTipText("Allow remote connections to the gateway (server mode)");
addSettingComponent(panel, "OWA url: ", urlField);
addSettingComponent(panel, "Local POP port: ", popPortField);
addSettingComponent(panel, "Local SMTP port: ", smtpPortField);
addSettingComponent(panel, "Keep Delay: ", keepDelayField);
addSettingComponent(panel, "Allow Remote Connections: ", allowRemoteField);
add("North", panel);
panel = new JPanel(new GridLayout(5, 2));
panel.setBorder(BorderFactory.createTitledBorder("Proxy settings"));
boolean enableProxy = Settings.getBooleanProperty("davmail.enableProxy");
final JCheckBox enableProxyField = new JCheckBox();
enableProxyField.setSelected(enableProxy);
final JTextField httpProxyField = new JTextField(Settings.getProperty("davmail.proxyHost"), 15);
final JTextField httpProxyPortField = new JTextField(Settings.getProperty("davmail.proxyPort"), 4);
final JTextField httpProxyUserField = new JTextField(Settings.getProperty("davmail.proxyUser"), 4);
final JTextField httpProxyPasswordField = new JPasswordField(Settings.getProperty("davmail.proxyPassword"), 4);
httpProxyField.setEnabled(enableProxy);
httpProxyPortField.setEnabled(enableProxy);
httpProxyUserField.setEnabled(enableProxy);
httpProxyPasswordField.setEnabled(enableProxy);
enableProxyField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
boolean enableProxy = enableProxyField.isSelected();
httpProxyField.setEnabled(enableProxy);
httpProxyPortField.setEnabled(enableProxy);
httpProxyUserField.setEnabled(enableProxy);
httpProxyPasswordField.setEnabled(enableProxy);
}
});
addSettingComponent(panel, "Enable proxy: ", enableProxyField);
addSettingComponent(panel, "Proxy server: ", httpProxyField);
addSettingComponent(panel, "Proxy port: ", httpProxyPortField);
addSettingComponent(panel, "Proxy user: ", httpProxyUserField);
addSettingComponent(panel, "Proxy password: ", httpProxyPasswordField);
add("Center", panel);
panel = new JPanel();
JButton cancel = new JButton("Cancel");
JButton ok = new JButton("Save");
ActionListener save = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Settings.setProperty("davmail.url", urlField.getText());
Settings.setProperty("davmail.popPort", popPortField.getText());
Settings.setProperty("davmail.smtpPort", smtpPortField.getText());
Settings.setProperty("davmail.keepDelay", keepDelayField.getText());
Settings.setProperty("davmail.allowRemote", String.valueOf(allowRemoteField.isSelected()));
Settings.setProperty("davmail.enableProxy", String.valueOf(enableProxyField.isSelected()));
Settings.setProperty("davmail.proxyHost", httpProxyField.getText());
Settings.setProperty("davmail.proxyPort", httpProxyPortField.getText());
Settings.setProperty("davmail.proxyUser", httpProxyUserField.getText());
Settings.setProperty("davmail.proxyPassword", httpProxyPasswordField.getText());
Settings.save();
setVisible(false);
DavGateway.start();
}
};
ok.addActionListener(save);
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
urlField.setText(Settings.getProperty("davmail.url"));
popPortField.setText(Settings.getProperty("davmail.popPort"));
smtpPortField.setText(Settings.getProperty("davmail.smtpPort"));
keepDelayField.setText(Settings.getProperty("davmail.keepDelay"));
allowRemoteField.setSelected(Settings.getBooleanProperty(("davmail.allowRemote")));
boolean enableProxy = Settings.getBooleanProperty("davmail.allowRemote");
enableProxyField.setSelected(enableProxy);
httpProxyField.setEnabled(enableProxy);
httpProxyPortField.setEnabled(enableProxy);
httpProxyUserField.setEnabled(enableProxy);
httpProxyPasswordField.setEnabled(enableProxy);
httpProxyField.setText(Settings.getProperty("davmail.proxyHost"));
httpProxyPortField.setText(Settings.getProperty("davmail.proxyPort"));
httpProxyUserField.setText(Settings.getProperty("davmail.proxyUser"));
httpProxyPasswordField.setText(Settings.getProperty("davmail.proxyPassword"));
setVisible(false);
}
});
panel.add(ok);
panel.add(cancel);
add("South", panel);
pack();
setResizable(false);
setLocation(getToolkit().getScreenSize().width / 2 -
getSize().width / 2,
getToolkit().getScreenSize().height / 2 -
getSize().height / 2);
urlField.requestFocus();
}
|
public void switchToGroup(String group) {
CellCollection cellCollection = CellCollection.getInstance();
cells.clear();
if (group == null) {
LinkedList<CellData> data = cellCollection.getCurrentGroup();
if (data != null)
cells.addAll(data);
else
return;
}
else
cells.addAll(cellCollection.getGroup(group));
if (cells.size()>0)
cellCollection.setCurrentCell(cells.getFirst());
else
getActivity().onBackPressed();
if (adapter != null)
adapter.notifyDataSetChanged();
}
| public void switchToGroup(String group) {
CellCollection cellCollection = CellCollection.getInstance();
cells.clear();
if (group == null) {
LinkedList<CellData> data = cellCollection.getCurrentGroup();
if (data != null)
cells.addAll(data);
else
return;
}
else
cells.addAll(cellCollection.getGroup(group));
if (cells.size()>0)
cellCollection.setCurrentCell(cells.getFirst());
else
getActivity().getSupportFragmentManager().popBackStack();
if (adapter != null)
adapter.notifyDataSetChanged();
}
|
public void execute(CommandSource source, String[] args, int baseIndex, boolean fuzzyLookup) throws CommandException {
if (rawExecutor != null && rawExecutor != this) {
rawExecutor.execute(source, args, baseIndex, fuzzyLookup);
return;
}
if (args.length > baseIndex && children.size() > 0) {
Command sub = null;
if (args.length > baseIndex + 1) {
sub = getChild(args[baseIndex + 1], fuzzyLookup);
}
if (sub == null) {
throw getMissingChildException(getUsage(args, baseIndex));
}
sub.execute(source, args, ++baseIndex, fuzzyLookup);
return;
}
if (executor == null || baseIndex >= args.length) {
throw new MissingCommandException("No command found!", getUsage(args, baseIndex));
}
if (!hasPermission(source)) {
throw new CommandException("You no not have the required permissions!");
}
final String[] originalArgs = args;
args = MiscCompatibilityUtils.arrayCopyOfRange(originalArgs, baseIndex, args.length);
CommandContext context = new CommandContext(args, valueFlags);
for (char flag : context.getFlags().toArray()) {
if (!flags.contains(flag)) {
throw new CommandUsageException("Unknown flag:" + flag, getUsage(originalArgs, baseIndex));
}
}
if (context.length() < minArgLength) {
throw new CommandUsageException("Not enough arguments", getUsage(originalArgs, baseIndex));
}
if (maxArgLength >= 0 && context.length() > maxArgLength) {
throw new CommandUsageException("Too many arguments", getUsage(originalArgs, baseIndex));
}
try {
executor.processCommand(source, this, context);
} catch (CommandException e) {
throw e;
} catch (Throwable t) {
throw new WrappedCommandException(t);
}
}
| public void execute(CommandSource source, String[] args, int baseIndex, boolean fuzzyLookup) throws CommandException {
if (rawExecutor != null && rawExecutor != this) {
rawExecutor.execute(source, args, baseIndex, fuzzyLookup);
return;
}
if (args.length > baseIndex && children.size() > 0) {
Command sub = null;
if (args.length > baseIndex + 1) {
sub = getChild(args[baseIndex + 1], fuzzyLookup);
}
if (sub == null) {
throw getMissingChildException(getUsage(args, baseIndex));
}
sub.execute(source, args, ++baseIndex, fuzzyLookup);
return;
}
if (executor == null || baseIndex >= args.length) {
throw new MissingCommandException("No command found!", getUsage(args, baseIndex));
}
if (!hasPermission(source)) {
throw new CommandException("You do not have the required permissions!");
}
final String[] originalArgs = args;
args = MiscCompatibilityUtils.arrayCopyOfRange(originalArgs, baseIndex, args.length);
CommandContext context = new CommandContext(args, valueFlags);
for (char flag : context.getFlags().toArray()) {
if (!flags.contains(flag)) {
throw new CommandUsageException("Unknown flag:" + flag, getUsage(originalArgs, baseIndex));
}
}
if (context.length() < minArgLength) {
throw new CommandUsageException("Not enough arguments", getUsage(originalArgs, baseIndex));
}
if (maxArgLength >= 0 && context.length() > maxArgLength) {
throw new CommandUsageException("Too many arguments", getUsage(originalArgs, baseIndex));
}
try {
executor.processCommand(source, this, context);
} catch (CommandException e) {
throw e;
} catch (Throwable t) {
throw new WrappedCommandException(t);
}
}
|
public static void doHttpGet( Context context, HttpClient httpClient, HttpHost target,
String path, File pdfFile ) {
InputStream in = null;
FileOutputStream out = null;
try {
URI uri = new URI( path );
HttpGet get = new HttpGet( uri );
HttpResponse response = httpClient.execute( target, get );
if ( response.getStatusLine().getStatusCode() == HttpStatus.SC_OK ) {
out = new FileOutputStream( pdfFile );
HttpEntity entity = response.getEntity();
in = entity.getContent();
byte[] buffer = new byte[ 32*1024 ];
int count;
while ( ( count = in.read( buffer, 0, buffer.length ) ) != -1 ) {
out.write( buffer, 0, count );
}
}
} catch ( Exception e ) {
UiUtils.showToast( context, e.getMessage() );
} finally {
if ( in != null ) {
try {
in.close();
} catch ( IOException e ) {
}
}
if ( out != null ) {
try {
out.close();
} catch ( IOException e ) {
}
}
}
}
| public static void doHttpGet( Context context, HttpClient httpClient, HttpHost target,
String path, File pdfFile ) {
InputStream in = null;
FileOutputStream out = null;
try {
URI uri = new URI( path );
HttpGet get = new HttpGet( uri );
HttpResponse response = httpClient.execute( target, get );
if ( response.getStatusLine().getStatusCode() == HttpStatus.SC_OK ) {
out = new FileOutputStream( pdfFile );
HttpEntity entity = response.getEntity();
in = entity.getContent();
byte[] buffer = new byte[ 32*1024 ];
int count;
while ( ( count = in.read( buffer, 0, buffer.length ) ) != -1 ) {
out.write( buffer, 0, count );
}
}
} catch ( Exception e ) {
UiUtils.showToast( context, "Error: Unable to download file" );
} finally {
if ( in != null ) {
try {
in.close();
} catch ( IOException e ) {
}
}
if ( out != null ) {
try {
out.close();
} catch ( IOException e ) {
}
}
}
}
|
public synchronized GeneralizedFile buildFile(String account, String rawPath) {
if (account == null) {
throw new UserException("For SSH, you must specify either ssh://user@host/path or ssh://conf_account@/path");
}
Params p = bank.getAccountParamsIfExists(getProtocol().getCanonicalName(), account);
if (p != null) {
validateAccountParams(account, p);
String[] path = FileManipulation.split(rawPath, ":", 2, false);
if (path[0].isEmpty()) {
path[0] = p.getMandParam("host");
}
if (path[1] == null) {
path[1] = ".";
}
if (p.hasParam("password")) {
return new SshFile(path[0],
p.getMandParam("username"),
p.getParam("password"),
path[1],
p.getShortParam("port", GlobalConstants.SSH_PORT),
p.getBoolParam("skip_host_key_check", false));
} else {
return new SshFile(path[0],
p.getMandParam("username"),
p.getMandParam("key"),
p.getParam("passphrase"),
path[1],
p.getShortParam("port", GlobalConstants.SSH_PORT),
p.getBoolParam("skip_host_key_check", false));
}
} else {
String[] user = FileManipulation.split(account, ":", 2, false);
String[] path = FileManipulation.split(rawPath, ":", 2);
if (FileManipulation.contains(path[0], "[")) {
throw new IllegalArgumentException("Doesn't manage ipv6 address");
}
return new SshFile(path[0], user[0], user[1], path[1], GlobalConstants.SSH_PORT, false);
}
}
| public synchronized GeneralizedFile buildFile(String account, String rawPath) {
if (account == null) {
throw new UserException("For SSH, you must specify either ssh://user@host/path or ssh://conf_account@/path");
}
Params p = bank.getAccountParamsIfExists(getProtocol().getCanonicalName(), account);
if (p != null) {
validateAccountParams(account, p);
String[] path = FileManipulation.split(rawPath, ":", 2, false);
if (path[0].isEmpty()) {
path[0] = p.getMandParam("host");
}
if (path[1] == null) {
path[1] = ".";
}
if (p.hasParam("password")) {
return new SshFile(path[0],
p.getMandParam("username"),
p.getParam("password"),
path[1],
p.getShortParam("port", GlobalConstants.SSH_PORT),
p.getBoolParam("skip_host_key_check", false));
} else {
return new SshFile(path[0],
p.getMandParam("username"),
p.getMandParam("key"),
p.getParam("passphrase"),
path[1],
p.getShortParam("port", GlobalConstants.SSH_PORT),
p.getBoolParam("skip_host_key_check", false));
}
} else {
String[] user = FileManipulation.split(account, ":", 2, false);
String[] path = FileManipulation.split(rawPath, ":", 2);
if (FileManipulation.contains(path[0], "[")) {
throw new IllegalArgumentException("Doesn't manage ipv6 address");
}
if (path[0].length() == 0) {
throw new IllegalArgumentException("Missing host. Maybe you meant '" +account + "' as an account, but it doesn't exist.");
}
return new SshFile(path[0], user[0], user[1], path[1], GlobalConstants.SSH_PORT, false);
}
}
|
public DiskSpaceInformer() {
super(new BorderLayout());
log = new JTextArea(30, 40);
log.setMargin(new Insets(5, 5, 5, 5));
log.setEditable(false);
log.append("- Select drive or folder: click [Choose Folder]"+newline +newline);
log.append("- Space usage: right click tree item & Check Space"+newline);
log.append("- Alternative: select tree item & click [Check Space]"+newline+newline);
log.append("- Multiple items: select multiple items [Check Space]"+newline);
log.append("- Alternative: select multiple items right click]"+newline+newline);
log.append("- All drives: overview of system [Storage Info]"+newline+newline);
log.append("- Clear screen: overview of system [Storage Info]"+newline);
JScrollPane logScrollPane = new JScrollPane(log);
logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
logScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
String os = System.getProperty("os.name");
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
openButton = new JButton("Choose Folder");
openButton.addActionListener(this);
checkButton = new JButton("Check Space");
checkButton.addActionListener(this);
summaryButton = new JButton("Storage Info");
summaryButton.addActionListener(this);
clearButton = new JButton("Clear Log...");
clearButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);
buttonPanel.add(checkButton);
buttonPanel.add(summaryButton);
buttonPanel.add(clearButton);
jProgressBar = new JProgressBar();
JPanel progressPanel = new JPanel();
progressPanel.add(jProgressBar);
File root;
if (OsUtils.isWindows()) {
root = new File("c:\\");
} else {
root = new File("/");
}
FileTreeModel model = new FileTreeModel(root);
tree = new JTree();
tree.setModel(model);
tree.addMouseListener(new LeftClickMouseListener());
tree.addMouseListener(new RightClickMouseListener());
treeScrollPane = new JScrollPane(tree);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
treeScrollPane, logScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(250);
add(buttonPanel, BorderLayout.NORTH);
add(splitPane, BorderLayout.CENTER);
add(progressPanel, BorderLayout.SOUTH);
}
| public DiskSpaceInformer() {
super(new BorderLayout());
log = new JTextArea(30, 40);
log.setMargin(new Insets(5, 5, 5, 5));
log.setEditable(false);
log.append("- Select drive or folder: click [Choose Folder]"+newline +newline);
log.append("- Space usage: right click tree item & Check Space"+newline);
log.append("- Alternative: select tree item & click [Check Space]"+newline+newline);
log.append("- Multiple items: select multiple items right click"+newline);
log.append("- Alternative: select multiple items [Check Space]"+newline+newline);
log.append("- All drives: overview of system [Storage Info]"+newline+newline);
log.append("- Clear screen: overview of system [Storage Info]"+newline);
JScrollPane logScrollPane = new JScrollPane(log);
logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
logScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
String os = System.getProperty("os.name");
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
openButton = new JButton("Choose Folder");
openButton.addActionListener(this);
checkButton = new JButton("Check Space");
checkButton.addActionListener(this);
summaryButton = new JButton("Storage Info");
summaryButton.addActionListener(this);
clearButton = new JButton("Clear Log...");
clearButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);
buttonPanel.add(checkButton);
buttonPanel.add(summaryButton);
buttonPanel.add(clearButton);
jProgressBar = new JProgressBar();
JPanel progressPanel = new JPanel();
progressPanel.add(jProgressBar);
File root;
if (OsUtils.isWindows()) {
root = new File("c:\\");
} else {
root = new File("/");
}
FileTreeModel model = new FileTreeModel(root);
tree = new JTree();
tree.setModel(model);
tree.addMouseListener(new LeftClickMouseListener());
tree.addMouseListener(new RightClickMouseListener());
treeScrollPane = new JScrollPane(tree);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
treeScrollPane, logScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(250);
add(buttonPanel, BorderLayout.NORTH);
add(splitPane, BorderLayout.CENTER);
add(progressPanel, BorderLayout.SOUTH);
}
|
public static void sleepUntil(long targetTimeMs) throws InterruptedException {
if(simulating.get()) {
synchronized(sleepTimesLock) {
threadSleepTimes.put(Thread.currentThread(), new AtomicLong(targetTimeMs));
}
while(simulatedCurrTimeMs.get() < targetTimeMs) {
Thread.sleep(10);
}
synchronized(sleepTimesLock) {
threadSleepTimes.remove(Thread.currentThread());
}
} else {
long sleepTime = targetTimeMs-currentTimeMillis();
if(sleepTime>0)
Thread.sleep(sleepTime);
}
}
| public static void sleepUntil(long targetTimeMs) throws InterruptedException {
if(simulating.get()) {
try {
synchronized(sleepTimesLock) {
threadSleepTimes.put(Thread.currentThread(), new AtomicLong(targetTimeMs));
}
while(simulatedCurrTimeMs.get() < targetTimeMs) {
Thread.sleep(10);
}
} finally {
synchronized(sleepTimesLock) {
threadSleepTimes.remove(Thread.currentThread());
}
}
} else {
long sleepTime = targetTimeMs-currentTimeMillis();
if(sleepTime>0)
Thread.sleep(sleepTime);
}
}
|
private static Bitmap drawTextToBitmap(Context gContext, int gResId,
String gText) {
Resources resources = gContext.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
if (bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
paint.setTextSize((int) (15 * scale));
paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
Rect bounds = new Rect();
paint.getTextBounds(gText, 0, gText.length(), bounds);
int x = (bitmap.getWidth() - bounds.width()) / 2;
int y = (bitmap.getHeight() + bounds.height()) / 2;
canvas.drawText(gText, x * scale, y * scale, paint);
return bitmap;
}
| private static Bitmap drawTextToBitmap(Context gContext, int gResId,
String gText) {
Resources resources = gContext.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
if (bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
paint.setTextSize((int) (15 * scale));
paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
Rect bounds = new Rect();
paint.getTextBounds(gText, 0, gText.length(), bounds);
int x = (bitmap.getWidth() - bounds.width()) / 2;
int y = (bitmap.getHeight() + bounds.height()) * 5/12;
canvas.drawText(gText, x, y, paint);
return bitmap;
}
|
private static Template _makeTemplate(String path) throws IOException {
Template t = new Template();
String templateText = IOUtils.toString(DResourceUtils.getResourceAsStream(path));
Matcher m = HEAD_RE.matcher(templateText);
if(m.find()) {
ConfigObject co = new ConfigSlurper().parse(m.group(1));
try {
Iterator<Map.Entry> it = co.entrySet().iterator();
while(it.hasNext()) {
Map.Entry e = it.next();
if(e.getKey() instanceof String) {
BeanUtils.setProperty(t, (String)e.getKey(), e.getValue());
}
}
t.setTemplateText(templateText.substring(m.end()));
return t;
}catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
| private static Template _makeTemplate(String path) throws IOException {
Template t = new Template();
String templateText = IOUtils.toString(DResourceUtils.getResourceAsStream(path));
Matcher m = HEAD_RE.matcher(templateText);
if(m.find()) {
ConfigObject co = new ConfigSlurper().parse(m.group(1));
try {
Iterator<Map.Entry> it = co.entrySet().iterator();
while(it.hasNext()) {
Map.Entry e = it.next();
if(e.getKey() instanceof String) {
BeanUtils.setProperty(t, (String)e.getKey(), e.getValue());
}
}
t.setTemplateText(templateText.substring(m.end()));
t.setOriginTemplateText(t.getTemplateText());
return t;
}catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
|
public void authenticate() {
User user = userService.getUserByLogin(credentials.getUsername());
if (user == null) {
setStatus(AuthenticationStatus.FAILURE);
} else {
try {
PasswordCredential pc = (PasswordCredential) credentials.getCredential();
String pass = pc.getValue();
if (user.getPassword().equals(Crypto.encode(pass))) {
setStatus(AuthenticationStatus.SUCCESS);
org.picketlink.idm.api.User seamUser = new SimpleUser(user.getNick());
setUser(seamUser);
} else {
setStatus(AuthenticationStatus.FAILURE);
}
} catch (NoSuchAlgorithmException ex) {
log.error(ex);
} catch (UnsupportedEncodingException ex) {
log.error(ex);
}
}
}
| public void authenticate() {
User user = userService.getUserByLogin(credentials.getUsername());
if (user == null) {
setStatus(AuthenticationStatus.FAILURE);
} else {
try {
PasswordCredential pc = (PasswordCredential) credentials.getCredential();
String pass = pc.getValue();
if (user.getPassword().equals(Crypto.encode(pass))) {
setStatus(AuthenticationStatus.SUCCESS);
org.picketlink.idm.api.User seamUser = new SimpleUser(user.getId().toString());
setUser(seamUser);
} else {
setStatus(AuthenticationStatus.FAILURE);
}
} catch (NoSuchAlgorithmException ex) {
log.error(ex);
} catch (UnsupportedEncodingException ex) {
log.error(ex);
}
}
}
|
protected boolean loadImage()
{
try {
SVGDriver driver = new SVGDriver();
driver.addElementMapping("org.apache.fop.svg.SVGElementMapping");
driver.addPropertyList("org.apache.fop.svg.SVGPropertyListMapping");
XMLReader parser = SVGImage.createParser();
driver.buildSVGTree(parser, new InputSource(this.imageStream));
SVGDocument doc = driver.getSVGDocument();
SVGSVGElement svg = doc.getRootElement();
this.width = (int)svg.getWidth().getBaseVal().getValue() * 1000;
this.height = (int)svg.getHeight().getBaseVal().getValue() * 1000;
return true;
} catch (Exception e) {
MessageHandler.errorln("ERROR LOADING EXTERNAL SVG: " + e.getMessage());
return false;
}
}
| protected boolean loadImage()
{
try {
SVGDriver driver = new SVGDriver();
driver.addElementMapping("org.apache.fop.svg.SVGElementMapping");
driver.addPropertyList("org.apache.fop.svg.SVGPropertyListMapping");
XMLReader parser = SVGImage.createParser();
driver.buildSVGTree(parser, new InputSource(this.imageStream));
SVGDocument doc = driver.getSVGDocument();
SVGSVGElement svg = doc.getRootElement();
this.width = (int)svg.getWidth().getBaseVal().getValue() * 1000;
this.height = (int)svg.getHeight().getBaseVal().getValue() * 1000;
return true;
} catch (Exception e) {
return false;
}
}
|
public void create(){
IssueComment issueComment = new IssueComment();
issueComment.issue = Issue.findById(1l);
issueComment.contents = "create() test";
issueComment.authorId = getTestUser().id;
long id = IssueComment.create(issueComment);
assertThat(IssueComment.find.byId(id)).isNotNull();
}
| public void create(){
IssueComment issueComment = new IssueComment();
issueComment.contents = "create() test";
issueComment.authorId = getTestUser().id;
long id = IssueComment.create(issueComment);
assertThat(IssueComment.findCommentsByIssueId(id)).isNotNull();
}
|
public Piece classicPromotion(Piece p, boolean verified, String promo) {
lastPromoted = p.getName();
if (!verified && promo == null&&g.isBlackMove()==p.isBlack()) {
klazz = "";
if(p.getPromotesTo().size()==1)
klazz = p.getPromotesTo().get(0);
while (klazz.equals("")) {
String result = (String) JOptionPane.showInputDialog(null, "Select the Promotion type:",
"Promo choice", JOptionPane.PLAIN_MESSAGE, null,
p.getPromotesTo().toArray(), null);
if (result == null) {
continue;
}
try {
klazz = result;
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (promo != null) {
klazz = promo;
}
try {
Piece promoted = PieceBuilder.makePiece(klazz,p.isBlack(), p.getSquare(), p.getBoard());
if (promoted.isBlack()) {
g.getBlackTeam().set(g.getBlackTeam().indexOf(p), promoted);
} else {
g.getWhiteTeam().set(g.getWhiteTeam().indexOf(p), promoted);
}
promoted.getLegalDests().clear();
promoted.setMoveCount(p.getMoveCount());
return promoted;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
| public Piece classicPromotion(Piece p, boolean verified, String promo) {
lastPromoted = p.getName();
klazz = p.getName();
if(p.getPromotesTo()==null) return p;
if (!verified && promo == null&&g.isBlackMove()==p.isBlack()) {
klazz = "";
if(p.getPromotesTo().size()==1)
klazz = p.getPromotesTo().get(0);
while (klazz.equals("")) {
String result = (String) JOptionPane.showInputDialog(null, "Select the Promotion type:",
"Promo choice", JOptionPane.PLAIN_MESSAGE, null,
p.getPromotesTo().toArray(), null);
if (result == null) {
continue;
}
try {
klazz = result;
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (promo != null) {
klazz = promo;
}
try {
Piece promoted = PieceBuilder.makePiece(klazz,p.isBlack(), p.getSquare(), p.getBoard());
if (promoted.isBlack()) {
g.getBlackTeam().set(g.getBlackTeam().indexOf(p), promoted);
} else {
g.getWhiteTeam().set(g.getWhiteTeam().indexOf(p), promoted);
}
promoted.getLegalDests().clear();
promoted.setMoveCount(p.getMoveCount());
return promoted;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
|
public void rewrite(SpliceList<Symbol> l){
System.out.println("rewriting:");
System.out.println(" " + l + "\n=========================================");
if(l.isEmpty()) return;
SLIterator<Symbol> first;
SLIterator<Symbol> second;
SLIterator<Symbol> lastRepl = null;
State currentState;
ActionState as;
Symbol symbol;
boolean changed;
boolean atOrPastLastChange;
boolean firstIteration = true;
DONE:
do {
currentState = s0;
atOrPastLastChange = false;
changed = false;
first = l.head();
second = l.head();
symbol = second.get();
System.out.println("******************outer*****" + firstIteration);
while(true){
as = get(currentState).get(symbol);
System.out.println("*" + symbol + " -- " + as);
if(currentState == s0 && as.getState() == s0){
System.out.println("false 0 transition");
if(!first.next()) break;
}
else {
for(int i = 0; i < as.getAction(); ++i){
first.next();
}
}
if(as.getState().getMatch() != null){
AbstractSequence repl = as.getState().getMatch().getRhs();
if(repl instanceof Fail){
System.out.println("Fail!");
return;
}
if(repl instanceof Succeed){
System.out.println("Succeed!");
return;
}
if(repl instanceof Sequence){
changed = true;
atOrPastLastChange = false;
System.out.println("==========Replacing==============" + first);
System.out.println("==========Replacing==============" + second);
System.out.println("in: " + l);
first.nonDestructiveSplice(second, (Sequence) repl);
if(l.isEmpty()) break DONE;
System.out.println("out: " + l);
System.out.println("out: " + first);
lastRepl = second;
System.out.println("lastRepl: " + lastRepl);
second = first.copy();
System.out.println("first: " + first);
System.out.println("second: " + second);
currentState = s0;
symbol = second.get();
if(symbol == null) break;
continue;
}
}
currentState = as.getState();
if(as.getAction() == 0){
if(!second.next()) break;
System.out.println("*********first " + second);
System.out.println("*********second " + second);
System.out.println("*********lastRepl " + lastRepl);
if(!firstIteration){
if(second.equals(lastRepl)){
atOrPastLastChange = true;
}
if(atOrPastLastChange && currentState == s0){
System.out.println("early exit at symbol " + second);
break DONE;
}
}
symbol = second.get();
}
}
firstIteration = false;
} while(changed);
System.out.println("substituted form = " + l.toString());
}
| public void rewrite(SpliceList<Symbol> l){
System.out.println("rewriting:");
System.out.println(" " + l + "\n=========================================");
if(l.isEmpty()) return;
SLIterator<Symbol> first;
SLIterator<Symbol> second;
SLIterator<Symbol> lastRepl = null;
State currentState;
ActionState as;
Symbol symbol;
boolean changed;
boolean atOrPastLastChange;
DONE:
do {
currentState = s0;
atOrPastLastChange = false;
changed = false;
first = l.head();
second = l.head();
symbol = second.get();
System.out.println("******************outer*****");
while(true){
as = get(currentState).get(symbol);
System.out.println("*" + symbol + " -- " + as);
if(currentState == s0 && as.getState() == s0){
System.out.println("false 0 transition");
if(!first.next()) break;
}
else {
for(int i = 0; i < as.getAction(); ++i){
first.next();
}
}
if(as.getState().getMatch() != null){
AbstractSequence repl = as.getState().getMatch().getRhs();
if(repl instanceof Fail){
System.out.println("Fail!");
return;
}
if(repl instanceof Succeed){
System.out.println("Succeed!");
return;
}
if(repl instanceof Sequence){
changed = true;
atOrPastLastChange = false;
System.out.println("==========Replacing==============" + first);
System.out.println("==========Replacing==============" + second);
System.out.println("in: " + l);
first.nonDestructiveSplice(second, (Sequence) repl);
if(l.isEmpty()) break DONE;
System.out.println("out: " + l);
System.out.println("out: " + first);
lastRepl = second;
System.out.println("lastRepl: " + lastRepl);
second = first.copy();
System.out.println("first: " + first);
System.out.println("second: " + second);
currentState = s0;
symbol = second.get();
if(symbol == null) break;
continue;
}
}
currentState = as.getState();
if(as.getAction() == 0){
if(!second.next()) break;
System.out.println("*********first " + second);
System.out.println("*********second " + second);
System.out.println("*********lastRepl " + lastRepl);
if(!changed){
if(second.equals(lastRepl)){
atOrPastLastChange = true;
}
if(atOrPastLastChange && currentState == s0){
System.out.println("early exit at symbol " + second);
break DONE;
}
}
symbol = second.get();
}
}
} while(changed);
System.out.println("substituted form = " + l.toString());
}
|
void export(final Component parentframe, final MapModel map) {
final ExportController exportEngineRegistry = ExportController.getContoller();
if (exportEngineRegistry.getFilterMap().isEmpty()) {
JOptionPane.showMessageDialog(parentframe, TextUtils.getText("xslt_export_not_possible"));
return;
}
final String absolutePathWithoutExtension;
final File xmlSourceFile = map.getFile();
if (xmlSourceFile != null) {
absolutePathWithoutExtension = FileUtils.removeExtension(xmlSourceFile.getAbsolutePath());
}
else {
absolutePathWithoutExtension = null;
}
final PropertyChangeListener filterChangeListener = new PropertyChangeListener() {
final private File selectedFile = absolutePathWithoutExtension == null ? null : new File(
absolutePathWithoutExtension);
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(JFileChooser.FILE_FILTER_CHANGED_PROPERTY)) {
final ExampleFileFilter filter = (ExampleFileFilter) evt.getNewValue();
if (filter == null) {
return;
}
final File acceptableFile = getAcceptableFile(selectedFile, filter);
EventQueue.invokeLater(new Runnable() {
public void run() {
fileChooser.setSelectedFile(acceptableFile);
}
});
return;
}
if (selectedFile != null && evt.getPropertyName().equals(JFileChooser.DIRECTORY_CHANGED_PROPERTY)) {
final FileFilter filter = fileChooser.getFileFilter();
if(! (filter instanceof ExampleFileFilter)){
return;
}
final File acceptableFile = getAcceptableFile(selectedFile, (ExampleFileFilter) filter);
final File currentDirectory = fileChooser.getCurrentDirectory();
if(currentDirectory != null){
final File file = new File (currentDirectory, acceptableFile.getName());
fileChooser.setSelectedFile(file);
}
else
fileChooser.setSelectedFile(acceptableFile);
return;
}
}
};
filterChangeListener.propertyChange(new PropertyChangeEvent(fileChooser,
JFileChooser.FILE_FILTER_CHANGED_PROPERTY, null, fileChooser.getFileFilter()));
try {
fileChooser.addPropertyChangeListener(filterChangeListener);
final int returnVal = fileChooser.showSaveDialog(parentframe);
if (returnVal == JFileChooser.APPROVE_OPTION) {
if(! (fileChooser.getFileFilter() instanceof ExampleFileFilter)){
UITools.errorMessage(TextUtils.getText("invalid_export_file"));
return;
}
final ExampleFileFilter fileFilter = (ExampleFileFilter) fileChooser.getFileFilter();
final File selectedFile = getAcceptableFile(fileChooser.getSelectedFile(), fileFilter);
if (selectedFile == null) {
return;
}
if (selectedFile.isDirectory()) {
return;
}
if (selectedFile.exists()) {
final String overwriteText = MessageFormat.format(TextUtils.getText("file_already_exists"),
new Object[] { selectedFile.toString() });
final int overwriteMap = JOptionPane.showConfirmDialog(UITools.getFrame(), overwriteText,
overwriteText, JOptionPane.YES_NO_OPTION);
if (overwriteMap != JOptionPane.YES_OPTION) {
return;
}
}
final IExportEngine exportEngine = exportEngineRegistry.getFilterMap().get(fileFilter);
exportEngine.export(map, selectedFile);
}
}
finally {
fileChooser.removePropertyChangeListener(filterChangeListener);
}
}
| void export(final Component parentframe, final MapModel map) {
final ExportController exportEngineRegistry = ExportController.getContoller();
if (exportEngineRegistry.getFilterMap().isEmpty()) {
JOptionPane.showMessageDialog(parentframe, TextUtils.getText("xslt_export_not_possible"));
return;
}
final String absolutePathWithoutExtension;
final File xmlSourceFile = map.getFile();
if (xmlSourceFile != null) {
absolutePathWithoutExtension = FileUtils.removeExtension(xmlSourceFile.getAbsolutePath());
}
else {
absolutePathWithoutExtension = null;
}
final PropertyChangeListener filterChangeListener = new PropertyChangeListener() {
final private File selectedFile = absolutePathWithoutExtension == null ? null : new File(
absolutePathWithoutExtension);
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(JFileChooser.FILE_FILTER_CHANGED_PROPERTY)) {
final FileFilter filter = fileChooser.getFileFilter();
if(! (filter instanceof ExampleFileFilter)){
return;
}
final File acceptableFile = getAcceptableFile(selectedFile, (ExampleFileFilter) filter);
EventQueue.invokeLater(new Runnable() {
public void run() {
fileChooser.setSelectedFile(acceptableFile);
}
});
return;
}
if (selectedFile != null && evt.getPropertyName().equals(JFileChooser.DIRECTORY_CHANGED_PROPERTY)) {
final FileFilter filter = fileChooser.getFileFilter();
if(! (filter instanceof ExampleFileFilter)){
return;
}
final File acceptableFile = getAcceptableFile(selectedFile, (ExampleFileFilter) filter);
final File currentDirectory = fileChooser.getCurrentDirectory();
if(currentDirectory != null){
final File file = new File (currentDirectory, acceptableFile.getName());
fileChooser.setSelectedFile(file);
}
else
fileChooser.setSelectedFile(acceptableFile);
return;
}
}
};
filterChangeListener.propertyChange(new PropertyChangeEvent(fileChooser,
JFileChooser.FILE_FILTER_CHANGED_PROPERTY, null, fileChooser.getFileFilter()));
try {
fileChooser.addPropertyChangeListener(filterChangeListener);
final int returnVal = fileChooser.showSaveDialog(parentframe);
if (returnVal == JFileChooser.APPROVE_OPTION) {
if(! (fileChooser.getFileFilter() instanceof ExampleFileFilter)){
UITools.errorMessage(TextUtils.getText("invalid_export_file"));
return;
}
final ExampleFileFilter fileFilter = (ExampleFileFilter) fileChooser.getFileFilter();
final File selectedFile = getAcceptableFile(fileChooser.getSelectedFile(), fileFilter);
if (selectedFile == null) {
return;
}
if (selectedFile.isDirectory()) {
return;
}
if (selectedFile.exists()) {
final String overwriteText = MessageFormat.format(TextUtils.getText("file_already_exists"),
new Object[] { selectedFile.toString() });
final int overwriteMap = JOptionPane.showConfirmDialog(UITools.getFrame(), overwriteText,
overwriteText, JOptionPane.YES_NO_OPTION);
if (overwriteMap != JOptionPane.YES_OPTION) {
return;
}
}
final IExportEngine exportEngine = exportEngineRegistry.getFilterMap().get(fileFilter);
exportEngine.export(map, selectedFile);
}
}
finally {
fileChooser.removePropertyChangeListener(filterChangeListener);
}
}
|