input
stringlengths
20
285k
output
stringlengths
20
285k
public Cohort saveCohort(Cohort cohort) throws APIException { if (cohort.getCohortId() == null) { Context.requirePrivilege(PrivilegeConstants.ADD_COHORTS); } else { Context.requirePrivilege(PrivilegeConstants.EDIT_COHORTS); } if (cohort.getName() == null) { throw new APIException("Cohort name is required"); } if (log.isInfoEnabled()) log.info("Saving cohort " + cohort); return dao.saveCohort(cohort); }
public Cohort saveCohort(Cohort cohort) throws APIException { if (cohort.getCohortId() == null) { Context.requirePrivilege(PrivilegeConstants.ADD_COHORTS); } else { Context.requirePrivilege(PrivilegeConstants.EDIT_COHORTS); } if (cohort.getName() == null) { throw new APIException(Context.getMessageSourceService().getMessage("Cohort.save.nameRequired", null, "Cohort name is required", Context.getLocale())); } if (cohort.getDescription() == null) { throw new APIException(Context.getMessageSourceService().getMessage("Cohort.save.descriptionRequired", null, "Cohort description is required", Context.getLocale())); } if (log.isInfoEnabled()) log.info("Saving cohort " + cohort); return dao.saveCohort(cohort); }
public void initializeDefaultPreferences() { IPreferenceStore store = EMFTextRuntimeUIPlugin.getDefault() .getPreferenceStore(); Map<String, Object> extensionToFactoryMap = Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap(); for (String extension : extensionToFactoryMap.keySet()) { ResourceSet rs = new ResourceSetImpl(); Resource tempResource = rs.createResource(URI.createURI("temp." + extension)); if (tempResource instanceof ITextResource) { ITextResource tr = (ITextResource) tempResource; String languageId = extension; int z = 0;; for(int i=6; i<tr.getTokenNames().length; i++) { String originalTokenName = tr.getTokenNames()[i]; String tokenName = originalTokenName; if (tokenName.startsWith("'") && tokenName.endsWith("'")) { tokenName = tokenName.substring(1, tokenName.length()-1); } ITokenStyle style = tr.getDefaultTokenStyle(tokenName); if (style != null) { String color = getColorString(style.getColorAsRGB()); setProperties(store, languageId, tokenName, color, style.isBold(), true, style.isItalic(), style.isStrikethrough(), style.isUnderline()); } else if (originalTokenName.matches("[A-Z]+") && !originalTokenName.equals(EPredefinedTokens.STANDARD.getTokenName())) { String color = "0,0,0"; if (z == 0) { color = "42,0,255"; z++; } else if (z == 1) { color = "63,127,95"; z++; } setProperties(store, languageId, originalTokenName, color, false, true, false, false, false); } else if (originalTokenName.matches(".[a-zA-Z][a-zA-Z0-9:]+.")) { setProperties(store, languageId, originalTokenName, "127,0,85", true, true, false, false, false); } else { setProperties(store, languageId, originalTokenName, "0,0,0", false, false, false, false, false); } } } } }
public void initializeDefaultPreferences() { IPreferenceStore store = EMFTextRuntimeUIPlugin.getDefault() .getPreferenceStore(); Map<String, Object> extensionToFactoryMap = Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap(); for (String extension : extensionToFactoryMap.keySet()) { ResourceSet rs = new ResourceSetImpl(); Resource tempResource = rs.createResource(URI.createURI("temp." + extension)); if (tempResource instanceof ITextResource) { ITextResource tr = (ITextResource) tempResource; String languageId = extension; int z = 0;; for(int i=6; i<tr.getTokenNames().length; i++) { String originalTokenName = tr.getTokenNames()[i]; String tokenName = originalTokenName; if (tokenName.startsWith("'") && tokenName.endsWith("'")) { tokenName = tokenName.substring(1, tokenName.length()-1); } ITokenStyle style = tr.getDefaultTokenStyle(tokenName); if (style != null) { String color = getColorString(style.getColorAsRGB()); setProperties(store, languageId, tokenName, color, style.isBold(), true, style.isItalic(), style.isStrikethrough(), style.isUnderline()); } else if (originalTokenName.matches("[A-Z]+") && !originalTokenName.equals(EPredefinedTokens.STANDARD.getTokenName())) { String color = "0,0,0"; if (z == 0) { color = "42,0,255"; z++; } else if (z == 1) { color = "63,127,95"; z++; } setProperties(store, languageId, tokenName, color, false, true, false, false, false); } else if (originalTokenName.matches(".[a-zA-Z][a-zA-Z0-9:]+.")) { setProperties(store, languageId, tokenName, "127,0,85", true, true, false, false, false); } else { setProperties(store, languageId, tokenName, "0,0,0", false, false, false, false, false); } } } } }
public Iterable<Part> parse(SoneTextParserContext context, Reader source) throws IOException { PartContainer parts = new PartContainer(); BufferedReader bufferedReader = (source instanceof BufferedReader) ? (BufferedReader) source : new BufferedReader(source); String line; boolean lastLineEmpty = true; int emptyLines = 0; while ((line = bufferedReader.readLine()) != null) { if (line.trim().length() == 0) { if (lastLineEmpty) { continue; } parts.add(new PlainTextPart("\n")); ++emptyLines; lastLineEmpty = emptyLines == 2; continue; } emptyLines = 0; boolean lineComplete = true; while (line.length() > 0) { int nextKsk = line.indexOf("KSK@"); int nextChk = line.indexOf("CHK@"); int nextSsk = line.indexOf("SSK@"); int nextUsk = line.indexOf("USK@"); int nextHttp = line.indexOf("http://"); int nextHttps = line.indexOf("https://"); int nextSone = line.indexOf("sone://"); int nextPost = line.indexOf("post://"); if ((nextKsk == -1) && (nextChk == -1) && (nextSsk == -1) && (nextUsk == -1) && (nextHttp == -1) && (nextHttps == -1) && (nextSone == -1) && (nextPost == -1)) { if (lineComplete && !lastLineEmpty) { parts.add(new PlainTextPart("\n" + line)); } else { parts.add(new PlainTextPart(line)); } break; } int next = Integer.MAX_VALUE; LinkType linkType = null; if ((nextKsk > -1) && (nextKsk < next)) { next = nextKsk; linkType = LinkType.KSK; } if ((nextChk > -1) && (nextChk < next)) { next = nextChk; linkType = LinkType.CHK; } if ((nextSsk > -1) && (nextSsk < next)) { next = nextSsk; linkType = LinkType.SSK; } if ((nextUsk > -1) && (nextUsk < next)) { next = nextUsk; linkType = LinkType.USK; } if ((nextHttp > -1) && (nextHttp < next)) { next = nextHttp; linkType = LinkType.HTTP; } if ((nextHttps > -1) && (nextHttps < next)) { next = nextHttps; linkType = LinkType.HTTPS; } if ((nextSone > -1) && (nextSone < next)) { next = nextSone; linkType = LinkType.SONE; } if ((nextPost > -1) && (nextPost < next)) { next = nextPost; linkType = LinkType.POST; } if (linkType == LinkType.SONE) { if (next > 0) { parts.add(new PlainTextPart(line.substring(0, next))); } if (line.length() >= (next + 7 + 43)) { String soneId = line.substring(next + 7, next + 50); Sone sone = soneProvider.getSone(soneId, false); if ((sone != null) && (sone.getName() != null)) { parts.add(new SonePart(sone)); } else { parts.add(new PlainTextPart(line.substring(next, next + 50))); } line = line.substring(next + 50); } else { parts.add(new PlainTextPart(line.substring(next))); line = ""; } continue; } if (linkType == LinkType.POST) { if (next > 0) { parts.add(new PlainTextPart(line.substring(0, next))); } if (line.length() >= (next + 7 + 36)) { String postId = line.substring(next + 7, next + 43); Post post = postProvider.getPost(postId, false); if ((post != null) && (post.getSone() != null)) { parts.add(new PostPart(post)); } else { parts.add(new PlainTextPart(line.substring(next, next + 43))); } line = line.substring(next + 43); } else { parts.add(new PlainTextPart(line.substring(next))); line = ""; } continue; } if ((next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) { next -= 8; line = line.substring(0, next) + line.substring(next + 8); } Matcher matcher = whitespacePattern.matcher(line); int nextSpace = matcher.find(next) ? matcher.start() : line.length(); if (nextSpace > (next + 4)) { if (!lastLineEmpty && lineComplete) { parts.add(new PlainTextPart("\n" + line.substring(0, next))); } else { if (next > 0) { parts.add(new PlainTextPart(line.substring(0, next))); } } String link = line.substring(next, nextSpace); String name = link; logger.log(Level.FINER, "Found link: %s", link); logger.log(Level.FINEST, "Next: %d, CHK: %d, SSK: %d, USK: %d", new Object[] { next, nextChk, nextSsk, nextUsk }); if ((linkType == LinkType.KSK) || (linkType == LinkType.CHK) || (linkType == LinkType.SSK) || (linkType == LinkType.USK)) { FreenetURI uri; if (name.indexOf('?') > -1) { name = name.substring(0, name.indexOf('?')); } if (name.endsWith("/")) { name = name.substring(0, name.length() - 1); } try { uri = new FreenetURI(name); name = uri.lastMetaString(); if (name == null) { name = uri.getDocName(); } if (name == null) { name = link.substring(0, Math.min(9, link.length())); } boolean fromPostingSone = ((linkType == LinkType.SSK) || (linkType == LinkType.USK)) && (context != null) && (context.getPostingSone() != null) && link.substring(4, Math.min(link.length(), 47)).equals(context.getPostingSone().getId()); parts.add(new FreenetLinkPart(link, name, fromPostingSone)); } catch (MalformedURLException mue1) { parts.add(new PlainTextPart(link)); } catch (NullPointerException npe1) { parts.add(new PlainTextPart(link)); } catch (ArrayIndexOutOfBoundsException aioobe1) { parts.add(new PlainTextPart(link)); } } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) { name = link.substring(linkType == LinkType.HTTP ? 7 : 8); int firstSlash = name.indexOf('/'); int lastSlash = name.lastIndexOf('/'); if ((lastSlash - firstSlash) > 3) { name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash); } if (name.endsWith("/")) { name = name.substring(0, name.length() - 1); } if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) { name = name.substring(4); } if (name.indexOf('?') > -1) { name = name.substring(0, name.indexOf('?')); } parts.add(new LinkPart(link, name)); } line = line.substring(nextSpace); } else { if (!lastLineEmpty && lineComplete) { parts.add(new PlainTextPart("\n" + line.substring(0, next + 4))); } else { parts.add(new PlainTextPart(line.substring(0, next + 4))); } line = line.substring(next + 4); } lineComplete = false; } lastLineEmpty = false; } for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) { Part part = parts.getPart(partIndex); if (!(part instanceof PlainTextPart) || !"\n".equals(((PlainTextPart) part).getText())) { break; } parts.removePart(partIndex); } return parts; }
public Iterable<Part> parse(SoneTextParserContext context, Reader source) throws IOException { PartContainer parts = new PartContainer(); BufferedReader bufferedReader = (source instanceof BufferedReader) ? (BufferedReader) source : new BufferedReader(source); String line; boolean lastLineEmpty = true; int emptyLines = 0; while ((line = bufferedReader.readLine()) != null) { if (line.trim().length() == 0) { if (lastLineEmpty) { continue; } parts.add(new PlainTextPart("\n")); ++emptyLines; lastLineEmpty = emptyLines == 2; continue; } emptyLines = 0; boolean lineComplete = true; while (line.length() > 0) { int nextKsk = line.indexOf("KSK@"); int nextChk = line.indexOf("CHK@"); int nextSsk = line.indexOf("SSK@"); int nextUsk = line.indexOf("USK@"); int nextHttp = line.indexOf("http://"); int nextHttps = line.indexOf("https://"); int nextSone = line.indexOf("sone://"); int nextPost = line.indexOf("post://"); if ((nextKsk == -1) && (nextChk == -1) && (nextSsk == -1) && (nextUsk == -1) && (nextHttp == -1) && (nextHttps == -1) && (nextSone == -1) && (nextPost == -1)) { if (lineComplete && !lastLineEmpty) { parts.add(new PlainTextPart("\n" + line)); } else { parts.add(new PlainTextPart(line)); } break; } int next = Integer.MAX_VALUE; LinkType linkType = null; if ((nextKsk > -1) && (nextKsk < next)) { next = nextKsk; linkType = LinkType.KSK; } if ((nextChk > -1) && (nextChk < next)) { next = nextChk; linkType = LinkType.CHK; } if ((nextSsk > -1) && (nextSsk < next)) { next = nextSsk; linkType = LinkType.SSK; } if ((nextUsk > -1) && (nextUsk < next)) { next = nextUsk; linkType = LinkType.USK; } if ((nextHttp > -1) && (nextHttp < next)) { next = nextHttp; linkType = LinkType.HTTP; } if ((nextHttps > -1) && (nextHttps < next)) { next = nextHttps; linkType = LinkType.HTTPS; } if ((nextSone > -1) && (nextSone < next)) { next = nextSone; linkType = LinkType.SONE; } if ((nextPost > -1) && (nextPost < next)) { next = nextPost; linkType = LinkType.POST; } if (linkType == LinkType.SONE) { if (next > 0) { if (lineComplete && !lastLineEmpty) { parts.add(new PlainTextPart("\n" + line.substring(0, next))); } else { parts.add(new PlainTextPart(line.substring(0, next))); } } if (line.length() >= (next + 7 + 43)) { String soneId = line.substring(next + 7, next + 50); Sone sone = soneProvider.getSone(soneId, false); if ((sone != null) && (sone.getName() != null)) { parts.add(new SonePart(sone)); } else { parts.add(new PlainTextPart(line.substring(next, next + 50))); } line = line.substring(next + 50); } else { parts.add(new PlainTextPart(line.substring(next))); line = ""; } lineComplete = false; continue; } if (linkType == LinkType.POST) { if (next > 0) { parts.add(new PlainTextPart(line.substring(0, next))); } if (line.length() >= (next + 7 + 36)) { String postId = line.substring(next + 7, next + 43); Post post = postProvider.getPost(postId, false); if ((post != null) && (post.getSone() != null)) { parts.add(new PostPart(post)); } else { parts.add(new PlainTextPart(line.substring(next, next + 43))); } line = line.substring(next + 43); } else { parts.add(new PlainTextPart(line.substring(next))); line = ""; } continue; } if ((next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) { next -= 8; line = line.substring(0, next) + line.substring(next + 8); } Matcher matcher = whitespacePattern.matcher(line); int nextSpace = matcher.find(next) ? matcher.start() : line.length(); if (nextSpace > (next + 4)) { if (!lastLineEmpty && lineComplete) { parts.add(new PlainTextPart("\n" + line.substring(0, next))); } else { if (next > 0) { parts.add(new PlainTextPart(line.substring(0, next))); } } String link = line.substring(next, nextSpace); String name = link; logger.log(Level.FINER, "Found link: %s", link); logger.log(Level.FINEST, "Next: %d, CHK: %d, SSK: %d, USK: %d", new Object[] { next, nextChk, nextSsk, nextUsk }); if ((linkType == LinkType.KSK) || (linkType == LinkType.CHK) || (linkType == LinkType.SSK) || (linkType == LinkType.USK)) { FreenetURI uri; if (name.indexOf('?') > -1) { name = name.substring(0, name.indexOf('?')); } if (name.endsWith("/")) { name = name.substring(0, name.length() - 1); } try { uri = new FreenetURI(name); name = uri.lastMetaString(); if (name == null) { name = uri.getDocName(); } if (name == null) { name = link.substring(0, Math.min(9, link.length())); } boolean fromPostingSone = ((linkType == LinkType.SSK) || (linkType == LinkType.USK)) && (context != null) && (context.getPostingSone() != null) && link.substring(4, Math.min(link.length(), 47)).equals(context.getPostingSone().getId()); parts.add(new FreenetLinkPart(link, name, fromPostingSone)); } catch (MalformedURLException mue1) { parts.add(new PlainTextPart(link)); } catch (NullPointerException npe1) { parts.add(new PlainTextPart(link)); } catch (ArrayIndexOutOfBoundsException aioobe1) { parts.add(new PlainTextPart(link)); } } else if ((linkType == LinkType.HTTP) || (linkType == LinkType.HTTPS)) { name = link.substring(linkType == LinkType.HTTP ? 7 : 8); int firstSlash = name.indexOf('/'); int lastSlash = name.lastIndexOf('/'); if ((lastSlash - firstSlash) > 3) { name = name.substring(0, firstSlash + 1) + "…" + name.substring(lastSlash); } if (name.endsWith("/")) { name = name.substring(0, name.length() - 1); } if (((name.indexOf('/') > -1) && (name.indexOf('.') < name.lastIndexOf('.', name.indexOf('/'))) || ((name.indexOf('/') == -1) && (name.indexOf('.') < name.lastIndexOf('.')))) && name.startsWith("www.")) { name = name.substring(4); } if (name.indexOf('?') > -1) { name = name.substring(0, name.indexOf('?')); } parts.add(new LinkPart(link, name)); } line = line.substring(nextSpace); } else { if (!lastLineEmpty && lineComplete) { parts.add(new PlainTextPart("\n" + line.substring(0, next + 4))); } else { parts.add(new PlainTextPart(line.substring(0, next + 4))); } line = line.substring(next + 4); } lineComplete = false; } lastLineEmpty = false; } for (int partIndex = parts.size() - 1; partIndex >= 0; --partIndex) { Part part = parts.getPart(partIndex); if (!(part instanceof PlainTextPart) || !"\n".equals(((PlainTextPart) part).getText())) { break; } parts.removePart(partIndex); } return parts; }
public void run(Timeout timeout) throws Exception { if (clientClosed.get()) { timeoutsHolder.cancel(); return; } if (!nettyResponseFuture.isDone() && !nettyResponseFuture.isCancelled()) { long now = millisTime(); long currentIdleConnectionTimeoutInstant = idleConnectionTimeout - nettyResponseFuture.getLastTouch(); long durationBeforeCurrentIdleConnectionTimeout = currentIdleConnectionTimeoutInstant - now; if (durationBeforeCurrentIdleConnectionTimeout <= 0L) { long durationSinceLastTouch = now - nettyResponseFuture.getLastTouch(); expire("Connection reached idle timeout of " + idleConnectionTimeout + " ms after " + durationSinceLastTouch + " ms"); nettyResponseFuture.setIdleConnectionTimeoutReached(); } else if (currentIdleConnectionTimeoutInstant < requestTimeoutInstant) { timeoutsHolder.idleConnectionTimeout = channels.newTimeoutInMs(this, durationBeforeCurrentIdleConnectionTimeout); } else { timeoutsHolder.idleConnectionTimeout = null; } } else { timeoutsHolder.cancel(); } }
public void run(Timeout timeout) throws Exception { if (clientClosed.get()) { timeoutsHolder.cancel(); return; } if (!nettyResponseFuture.isDone() && !nettyResponseFuture.isCancelled()) { long now = millisTime(); long currentIdleConnectionTimeoutInstant = idleConnectionTimeout + nettyResponseFuture.getLastTouch(); long durationBeforeCurrentIdleConnectionTimeout = currentIdleConnectionTimeoutInstant - now; if (durationBeforeCurrentIdleConnectionTimeout <= 0L) { long durationSinceLastTouch = now - nettyResponseFuture.getLastTouch(); expire("Connection reached idle timeout of " + idleConnectionTimeout + " ms after " + durationSinceLastTouch + " ms"); nettyResponseFuture.setIdleConnectionTimeoutReached(); } else if (currentIdleConnectionTimeoutInstant < requestTimeoutInstant) { timeoutsHolder.idleConnectionTimeout = channels.newTimeoutInMs(this, durationBeforeCurrentIdleConnectionTimeout); } else { timeoutsHolder.idleConnectionTimeout = null; } } else { timeoutsHolder.cancel(); } }
protected void onSyncStateUpdated() { final ConnectivityManager connManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); final boolean backgroundDataSetting = connManager.getBackgroundDataSetting(); mBackgroundDataCheckBox.setChecked(backgroundDataSetting); boolean masterSyncAutomatically = ContentResolver.getMasterSyncAutomatically(); mAutoSyncCheckbox.setChecked(masterSyncAutomatically); SyncInfo currentSync = ContentResolver.getCurrentSync(); boolean anySyncFailed = false; final SyncAdapterType[] syncAdapters = ContentResolver.getSyncAdapterTypes(); HashSet<String> userFacing = new HashSet<String>(); for (int k = 0, n = syncAdapters.length; k < n; k++) { final SyncAdapterType sa = syncAdapters[k]; if (sa.isUserVisible()) { userFacing.add(sa.authority); } } for (int i = 0, count = mManageAccountsCategory.getPreferenceCount(); i < count; i++) { Preference pref = mManageAccountsCategory.getPreference(i); if (! (pref instanceof AccountPreference)) { continue; } AccountPreference accountPref = (AccountPreference) pref; Account account = accountPref.getAccount(); int syncCount = 0; boolean syncIsFailing = false; final ArrayList<String> authorities = accountPref.getAuthorities(); if (authorities != null) { for (String authority : authorities) { SyncStatusInfo status = ContentResolver.getSyncStatus(account, authority); boolean syncEnabled = ContentResolver.getSyncAutomatically(account, authority) && masterSyncAutomatically && backgroundDataSetting && (ContentResolver.getIsSyncable(account, authority) > 0); boolean authorityIsPending = ContentResolver.isSyncPending(account, authority); boolean activelySyncing = currentSync != null && currentSync.authority.equals(authority) && new Account(currentSync.account.name, currentSync.account.type) .equals(account); boolean lastSyncFailed = status != null && syncEnabled && status.lastFailureTime != 0 && status.getLastFailureMesgAsInt(0) != ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS; if (lastSyncFailed && !activelySyncing && !authorityIsPending) { syncIsFailing = true; anySyncFailed = true; } syncCount += syncEnabled && userFacing.contains(authority) ? 1 : 0; } } else { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "no syncadapters found for " + account); } } int syncStatus = AccountPreference.SYNC_DISABLED; if (syncIsFailing) { syncStatus = AccountPreference.SYNC_ERROR; } else if (syncCount == 0) { syncStatus = AccountPreference.SYNC_DISABLED; } else if (syncCount > 0) { syncStatus = AccountPreference.SYNC_ENABLED; } accountPref.setSyncStatus(syncStatus); } mErrorInfoView.setVisibility(anySyncFailed ? View.VISIBLE : View.GONE); }
protected void onSyncStateUpdated() { if (getActivity() == null) return; final ConnectivityManager connManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); final boolean backgroundDataSetting = connManager.getBackgroundDataSetting(); mBackgroundDataCheckBox.setChecked(backgroundDataSetting); boolean masterSyncAutomatically = ContentResolver.getMasterSyncAutomatically(); mAutoSyncCheckbox.setChecked(masterSyncAutomatically); SyncInfo currentSync = ContentResolver.getCurrentSync(); boolean anySyncFailed = false; final SyncAdapterType[] syncAdapters = ContentResolver.getSyncAdapterTypes(); HashSet<String> userFacing = new HashSet<String>(); for (int k = 0, n = syncAdapters.length; k < n; k++) { final SyncAdapterType sa = syncAdapters[k]; if (sa.isUserVisible()) { userFacing.add(sa.authority); } } for (int i = 0, count = mManageAccountsCategory.getPreferenceCount(); i < count; i++) { Preference pref = mManageAccountsCategory.getPreference(i); if (! (pref instanceof AccountPreference)) { continue; } AccountPreference accountPref = (AccountPreference) pref; Account account = accountPref.getAccount(); int syncCount = 0; boolean syncIsFailing = false; final ArrayList<String> authorities = accountPref.getAuthorities(); if (authorities != null) { for (String authority : authorities) { SyncStatusInfo status = ContentResolver.getSyncStatus(account, authority); boolean syncEnabled = ContentResolver.getSyncAutomatically(account, authority) && masterSyncAutomatically && backgroundDataSetting && (ContentResolver.getIsSyncable(account, authority) > 0); boolean authorityIsPending = ContentResolver.isSyncPending(account, authority); boolean activelySyncing = currentSync != null && currentSync.authority.equals(authority) && new Account(currentSync.account.name, currentSync.account.type) .equals(account); boolean lastSyncFailed = status != null && syncEnabled && status.lastFailureTime != 0 && status.getLastFailureMesgAsInt(0) != ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS; if (lastSyncFailed && !activelySyncing && !authorityIsPending) { syncIsFailing = true; anySyncFailed = true; } syncCount += syncEnabled && userFacing.contains(authority) ? 1 : 0; } } else { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "no syncadapters found for " + account); } } int syncStatus = AccountPreference.SYNC_DISABLED; if (syncIsFailing) { syncStatus = AccountPreference.SYNC_ERROR; } else if (syncCount == 0) { syncStatus = AccountPreference.SYNC_DISABLED; } else if (syncCount > 0) { syncStatus = AccountPreference.SYNC_ENABLED; } accountPref.setSyncStatus(syncStatus); } mErrorInfoView.setVisibility(anySyncFailed ? View.VISIBLE : View.GONE); }
public CytoscapeMenus(CytoscapeMenuBar menuBar, CytoscapeToolBar toolBar) { this.menuBar = menuBar; this.toolBar = toolBar; menuBar.addMenu("File", 0.0); menuBar.addMenu("File.New", 0.0); menuBar.addMenu("File.New.Network", 0.0); menuBar.addMenu("File.Import", 5.0); menuBar.addMenu("File.Export", 5.1); menuBar.addMenu("Edit", 0.0); menuBar.addMenu("View", 0.0); menuBar.addMenu("Select", 0.0); menuBar.addMenu("Select.Nodes", 1.0); menuBar.addMenu("Select.Edges", 1.1); menuBar.addMenu("Layout", 0.0); menuBar.addMenu("Plugins", 0.0); menuBar.addMenu("Tools", 0.0); menuBar.addMenu("Help", 0.0); menuBar.addSeparator("File", 2.0); menuBar.addSeparator("File", 4.0); menuBar.addSeparator("File", 6.0); menuBar.addSeparator("File", 8.0); menuBar.addSeparator("Edit", 2.0); menuBar.addSeparator("Edit", 4.0); menuBar.addSeparator("Edit", 6.0); menuBar.addMenu("Edit.Preferences", 10.0); menuBar.addSeparator("View", 2.0); menuBar.addSeparator("View", 6.0); menuBar.addSeparator("Select", 2.0); menuBar.addSeparator("Select", 4.0); menuBar.addSeparator("Select", 6.0); menuBar.addSeparator("Layout", 2.0); menuBar.addSeparator("Layout", 4.0); menuBar.addSeparator("Layout", 6.0); menuBar.addSeparator("Plugins", 2.0); menuBar.addSeparator("Help", 2.0); toolBar.addSeparator(2.0f); toolBar.addSeparator(4.0f); toolBar.addSeparator(6.0f); toolBar.addSeparator(8.0f); }
public CytoscapeMenus(CytoscapeMenuBar menuBar, CytoscapeToolBar toolBar) { this.menuBar = menuBar; this.toolBar = toolBar; menuBar.addMenu("File", 0.0); menuBar.addMenu("File.Recent Session", 0.0); menuBar.addMenu("File.New", 0.5); menuBar.addMenu("File.New.Network", 0.0); menuBar.addMenu("File.Import", 5.0); menuBar.addMenu("File.Export", 5.1); menuBar.addMenu("Edit", 0.0); menuBar.addMenu("View", 0.0); menuBar.addMenu("Select", 0.0); menuBar.addMenu("Select.Nodes", 1.0); menuBar.addMenu("Select.Edges", 1.1); menuBar.addMenu("Layout", 0.0); menuBar.addMenu("Plugins", 0.0); menuBar.addMenu("Tools", 0.0); menuBar.addMenu("Help", 0.0); menuBar.addSeparator("File", 2.0); menuBar.addSeparator("File", 4.0); menuBar.addSeparator("File", 6.0); menuBar.addSeparator("File", 8.0); menuBar.addSeparator("Edit", 2.0); menuBar.addSeparator("Edit", 4.0); menuBar.addSeparator("Edit", 6.0); menuBar.addMenu("Edit.Preferences", 10.0); menuBar.addSeparator("View", 2.0); menuBar.addSeparator("View", 6.0); menuBar.addSeparator("Select", 2.0); menuBar.addSeparator("Select", 4.0); menuBar.addSeparator("Select", 6.0); menuBar.addSeparator("Layout", 2.0); menuBar.addSeparator("Layout", 4.0); menuBar.addSeparator("Layout", 6.0); menuBar.addSeparator("Plugins", 2.0); menuBar.addSeparator("Help", 2.0); toolBar.addSeparator(2.0f); toolBar.addSeparator(4.0f); toolBar.addSeparator(6.0f); toolBar.addSeparator(8.0f); }
private void computeText() { Map bindings = new HashMap(); if (isDirty()) { bindings.put(CVSDecoratorConfiguration.DIRTY_FLAG, preferences.getString(ICVSUIConstants.PREF_DIRTY_FLAG)); } if (isAdded()) { bindings.put(CVSDecoratorConfiguration.ADDED_FLAG, preferences.getString(ICVSUIConstants.PREF_ADDED_FLAG)); } else if(isHasRemote()){ bindings.put(CVSDecoratorConfiguration.FILE_REVISION, getRevision()); bindings.put(CVSDecoratorConfiguration.RESOURCE_TAG, getTag()); } bindings.put(CVSDecoratorConfiguration.FILE_KEYWORD, getKeywordSubstitution()); if ((resourceType == IResource.FOLDER || resourceType == IResource.PROJECT) && location != null) { bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_HOST, location.getHost()); bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_METHOD, location.getMethod().getName()); bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_USER, location.getUsername()); bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_ROOT, location.getRootDirectory()); bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_REPOSITORY, repository); RepositoryManager repositoryManager = CVSUIPlugin.getPlugin().getRepositoryManager(); RepositoryRoot root = repositoryManager.getRepositoryRootFor(location); CVSUIPlugin.getPlugin().getRepositoryManager(); String label = root.getName(); if (label == null) { label = location.getLocation(true); } bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_LABEL, label); } CVSDecoratorConfiguration.decorate(this, getTextFormatter(), bindings); }
private void computeText() { if (isIgnored()) return; Map bindings = new HashMap(); if (isDirty()) { bindings.put(CVSDecoratorConfiguration.DIRTY_FLAG, preferences.getString(ICVSUIConstants.PREF_DIRTY_FLAG)); } if (isAdded()) { bindings.put(CVSDecoratorConfiguration.ADDED_FLAG, preferences.getString(ICVSUIConstants.PREF_ADDED_FLAG)); } else if(isHasRemote()){ bindings.put(CVSDecoratorConfiguration.FILE_REVISION, getRevision()); bindings.put(CVSDecoratorConfiguration.RESOURCE_TAG, getTag()); } bindings.put(CVSDecoratorConfiguration.FILE_KEYWORD, getKeywordSubstitution()); if ((resourceType == IResource.FOLDER || resourceType == IResource.PROJECT) && location != null) { bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_HOST, location.getHost()); bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_METHOD, location.getMethod().getName()); bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_USER, location.getUsername()); bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_ROOT, location.getRootDirectory()); bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_REPOSITORY, repository); RepositoryManager repositoryManager = CVSUIPlugin.getPlugin().getRepositoryManager(); RepositoryRoot root = repositoryManager.getRepositoryRootFor(location); CVSUIPlugin.getPlugin().getRepositoryManager(); String label = root.getName(); if (label == null) { label = location.getLocation(true); } bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_LABEL, label); } CVSDecoratorConfiguration.decorate(this, getTextFormatter(), bindings); }
public static String error(final int code, final Throwable t) { final StringWriter writer = new StringWriter(); final PrintWriter printWriter = new PrintWriter(writer); if (t.getMessage() != null) printWriter.append(t.getMessage()); t.printStackTrace(printWriter); return new JSONObject().element("code", code).element("body", writer.toString()).toString(); }
public static String error(final int code, final Throwable t) { final StringWriter writer = new StringWriter(); final PrintWriter printWriter = new PrintWriter(writer); if (t.getMessage() != null) { printWriter.append(t.getMessage()); printWriter.append("\n"); } t.printStackTrace(printWriter); return new JSONObject().element("code", code).element("body", "<pre>"+ writer + "</pre>").toString(); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.player); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); if(Util.isICSOrLater()) getWindow().getDecorView().findViewById(android.R.id.content).setOnSystemUiVisibilityChangeListener( new OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int visibility) { if (visibility == mUiVisibility) return; setSurfaceSize(mVideoWidth, mVideoHeight, mSarNum, mSarDen); if (visibility == View.SYSTEM_UI_FLAG_VISIBLE && !mShowing) { showOverlay(); mHandler.sendMessageDelayed(mHandler.obtainMessage(HIDE_NAV), OVERLAY_TIMEOUT); } mUiVisibility = visibility; } } ); mOverlayHeader = findViewById(R.id.player_overlay_header); mOverlay = findViewById(R.id.player_overlay); mOverlaySlider = (SlidingPanel) findViewById(R.id.player_overlay_slider); View sliderContent = findViewById(R.id.slider_content); sliderContent.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); mOverlaySlider.setOnDrawerScrollListener(new OnDrawerScrollListener() { @Override public void onScrollStarted() { showOverlay(OVERLAY_INFINITE); } @Override public void onScrollEnded() { if (mOverlaySlider.isOpened()) { mOverlaySlider.ExpandHandle(); showOverlay(OVERLAY_INFINITE); } else { mOverlaySlider.CollapseHandle(); showOverlay(OVERLAY_TIMEOUT); } } }); mOverlaySlider.setOnDrawerOpenListener(new OnDrawerOpenListener() { @Override public void onDrawerOpened() { mOverlaySlider.ExpandHandle(); showOverlay(OVERLAY_INFINITE); } }); mOverlaySlider.setOnDrawerCloseListener(new OnDrawerCloseListener() { @Override public void onDrawerClosed() { mOverlaySlider.CollapseHandle(); showOverlay(OVERLAY_TIMEOUT); } }); mTitle = (TextView) findViewById(R.id.player_overlay_title); mSysTime = (TextView) findViewById(R.id.player_overlay_systime); mBattery = (TextView) findViewById(R.id.player_overlay_battery); mTime = (TextView) findViewById(R.id.player_overlay_time); mLength = (TextView) findViewById(R.id.player_overlay_length); mInfo = (TextView) findViewById(R.id.player_overlay_info); mEnableWheelbar = pref.getBoolean("enable_wheel_bar", false); mEnableBrightnessGesture = pref.getBoolean("enable_gesture_brightness", true); mControls = mEnableWheelbar ? new PlayerControlWheel(this) : new PlayerControlClassic(this); mControls.setOnPlayerControlListener(mPlayerControlListener); FrameLayout mControlContainer = (FrameLayout) findViewById(R.id.player_control); mControlContainer.addView((View) mControls); mAudio = (Spinner) findViewById(R.id.player_overlay_audio); mSubtitles = (Spinner) findViewById(R.id.player_overlay_subtitle); mLock = (ImageButton) findViewById(R.id.player_overlay_lock); mLock.setOnClickListener(mLockListener); mSize = (ImageButton) findViewById(R.id.player_overlay_size); mSize.setOnClickListener(mSizeListener); mSpeedLabel = (TextView) findViewById(R.id.player_overlay_speed); mSpeedLabel.setOnClickListener(mSpeedLabelListener); mSurface = (SurfaceView) findViewById(R.id.player_surface); mSurfaceHolder = mSurface.getHolder(); mSurfaceHolder.setFormat(PixelFormat.RGBX_8888); mSurfaceHolder.addCallback(mSurfaceCallback); mSeekbar = (SeekBar) findViewById(R.id.player_overlay_seekbar); mSeekbar.setOnSeekBarChangeListener(mSeekListener); mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE); mAudioMax = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); mSwitchingView = false; mEndReached = false; registerReceiver(mBatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); try { LibVLC.useIOMX(this); mLibVLC = LibVLC.getInstance(); } catch (LibVlcException e) { e.printStackTrace(); } EventManager em = EventManager.getInstance(); em.addHandler(eventHandler); this.setVolumeControlStream(AudioManager.STREAM_MUSIC); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.player); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); if(Util.isICSOrLater()) getWindow().getDecorView().findViewById(android.R.id.content).setOnSystemUiVisibilityChangeListener( new OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int visibility) { if (visibility == mUiVisibility) return; setSurfaceSize(mVideoWidth, mVideoHeight, mSarNum, mSarDen); if (visibility == View.SYSTEM_UI_FLAG_VISIBLE && !mShowing) { showOverlay(); mHandler.sendMessageDelayed(mHandler.obtainMessage(HIDE_NAV), OVERLAY_TIMEOUT); } mUiVisibility = visibility; } } ); mOverlayHeader = findViewById(R.id.player_overlay_header); mOverlay = findViewById(R.id.player_overlay); mOverlaySlider = (SlidingPanel) findViewById(R.id.player_overlay_slider); View sliderContent = findViewById(R.id.slider_content); sliderContent.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); mOverlaySlider.setOnDrawerScrollListener(new OnDrawerScrollListener() { @Override public void onScrollStarted() { showOverlay(OVERLAY_INFINITE); setTracksAndSubtitles(); } @Override public void onScrollEnded() { if (mOverlaySlider.isOpened()) { mOverlaySlider.ExpandHandle(); showOverlay(OVERLAY_INFINITE); } else { mOverlaySlider.CollapseHandle(); showOverlay(OVERLAY_TIMEOUT); } } }); mOverlaySlider.setOnDrawerOpenListener(new OnDrawerOpenListener() { @Override public void onDrawerOpened() { mOverlaySlider.ExpandHandle(); showOverlay(OVERLAY_INFINITE); } }); mOverlaySlider.setOnDrawerCloseListener(new OnDrawerCloseListener() { @Override public void onDrawerClosed() { mOverlaySlider.CollapseHandle(); showOverlay(OVERLAY_TIMEOUT); } }); mTitle = (TextView) findViewById(R.id.player_overlay_title); mSysTime = (TextView) findViewById(R.id.player_overlay_systime); mBattery = (TextView) findViewById(R.id.player_overlay_battery); mTime = (TextView) findViewById(R.id.player_overlay_time); mLength = (TextView) findViewById(R.id.player_overlay_length); mInfo = (TextView) findViewById(R.id.player_overlay_info); mEnableWheelbar = pref.getBoolean("enable_wheel_bar", false); mEnableBrightnessGesture = pref.getBoolean("enable_gesture_brightness", true); mControls = mEnableWheelbar ? new PlayerControlWheel(this) : new PlayerControlClassic(this); mControls.setOnPlayerControlListener(mPlayerControlListener); FrameLayout mControlContainer = (FrameLayout) findViewById(R.id.player_control); mControlContainer.addView((View) mControls); mAudio = (Spinner) findViewById(R.id.player_overlay_audio); mSubtitles = (Spinner) findViewById(R.id.player_overlay_subtitle); mLock = (ImageButton) findViewById(R.id.player_overlay_lock); mLock.setOnClickListener(mLockListener); mSize = (ImageButton) findViewById(R.id.player_overlay_size); mSize.setOnClickListener(mSizeListener); mSpeedLabel = (TextView) findViewById(R.id.player_overlay_speed); mSpeedLabel.setOnClickListener(mSpeedLabelListener); mSurface = (SurfaceView) findViewById(R.id.player_surface); mSurfaceHolder = mSurface.getHolder(); mSurfaceHolder.setFormat(PixelFormat.RGBX_8888); mSurfaceHolder.addCallback(mSurfaceCallback); mSeekbar = (SeekBar) findViewById(R.id.player_overlay_seekbar); mSeekbar.setOnSeekBarChangeListener(mSeekListener); mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE); mAudioMax = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); mSwitchingView = false; mEndReached = false; registerReceiver(mBatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); try { LibVLC.useIOMX(this); mLibVLC = LibVLC.getInstance(); } catch (LibVlcException e) { e.printStackTrace(); } EventManager em = EventManager.getInstance(); em.addHandler(eventHandler); this.setVolumeControlStream(AudioManager.STREAM_MUSIC); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); }
public void reduceHealth(int Health, GameLogic logic) { if (this.Health-Health > 0){ System.out.println("!" + (this.Health-Health)); this.Health = this.Health-Health; System.out.println("Health verloren! Health: " + this.Health); } else { lives--; if(lives<=0){ this.Health -= Health; System.out.println("!TOT! (x.x) Health: " + this.Health); } else { this.Health = 1000; logic.teleportElement(this, logic.getCheckPoint()); } } }
public void reduceHealth(int Health, GameLogic logic) { if (this.Health-Health > 0){ this.Health = this.Health-Health; System.out.println("Health verloren! Health: " + this.Health); } else { lives--; if(lives<=0){ this.Health -= Health; System.out.println("!TOT! (x.x) Health: " + this.Health); } else { this.Health -= Health; System.out.println("!TOT! (x.x) Health: " + this.Health); this.Health = 1000; logic.teleportElement(this, logic.getCheckPoint()); } } }
public void handleEvent(EventBundle eventBundle) throws ClientException { if (!(eventBundle instanceof ReconnectedEventBundle)) { log.error("Incorrect event bundle type: " + eventBundle); return; } CoreSession session = null; Set<Serializable> ids = new HashSet<Serializable>(); for (Event event : eventBundle) { if (!event.getName().equals(EVENT_NAME)) { continue; } EventContext eventContext = event.getContext(); ids.addAll(getIdsFromEventContext(eventContext)); CoreSession s = eventContext.getCoreSession(); if (session == null) { session = s; } else if (session != s) { throw new ClientException( "Several CoreSessions in one EventBundle"); } } if (session == null) { if (ids.isEmpty()) { return; } throw new ClientException("Null CoreSession"); } boolean save = false; BlobsExtractor extractor = new BlobsExtractor(); for (Serializable id : ids) { IdRef docRef = new IdRef(((String) id)); if (!session.exists(docRef)) { continue; } DocumentModel doc = session.getDocument(docRef); List<Blob> blobs = extractor.getBlobs(doc); String text = blobsToText(blobs); try { session.setDocumentSystemProp(docRef, SQLDocument.BINARY_TEXT_SYS_PROP, text); } catch (DocumentException e) { log.error("Couldn't set fulltext on: " + id, e); continue; } save = true; } if (save) { session.save(); } }
public void handleEvent(EventBundle eventBundle) throws ClientException { if (!(eventBundle instanceof ReconnectedEventBundle)) { log.error("Incorrect event bundle type: " + eventBundle); return; } CoreSession session = null; Set<Serializable> ids = new HashSet<Serializable>(); for (Event event : eventBundle) { if (!event.getName().equals(EVENT_NAME)) { continue; } EventContext eventContext = event.getContext(); ids.addAll(getIdsFromEventContext(eventContext)); CoreSession s = eventContext.getCoreSession(); if (session == null) { session = s; } else if (session != s) { throw new ClientException( "Several CoreSessions in one EventBundle"); } } if (session == null) { if (ids.isEmpty()) { return; } throw new ClientException("Null CoreSession"); } boolean save = false; BlobsExtractor extractor = new BlobsExtractor(); for (Serializable id : ids) { IdRef docRef = new IdRef(((String) id)); if (!session.exists(docRef)) { continue; } DocumentModel doc = session.getDocument(docRef); if (doc.isProxy()) { continue; } List<Blob> blobs = extractor.getBlobs(doc); String text = blobsToText(blobs); try { session.setDocumentSystemProp(docRef, SQLDocument.BINARY_TEXT_SYS_PROP, text); } catch (DocumentException e) { log.error("Couldn't set fulltext on: " + id, e); continue; } save = true; } if (save) { session.save(); } }
public void drawSprite(Graphics g, int x, int y) { if (tick == 9) { tick = 0; currentFrame++; currentFrame = (currentFrame % 3); } if (kangaroo.getVerticalSpeed() != 0) { if(kangaroo.getDirection() == Direction.DIRECTION_EAST || lastSheet == "rightSheet") { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, widthPerFrame*2, 1, widthPerFrame*3, height, null, null); } else if (kangaroo.getDirection() == Direction.DIRECTION_WEST || lastSheet == "leftSheet") { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, widthPerFrame*2, 1, widthPerFrame*3, height, null, null); } } else if(kangaroo.getDirection() == Direction.DIRECTION_EAST) { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, (currentFrame * widthPerFrame), 1, (currentFrame * widthPerFrame) + widthPerFrame, height, null, null); this.lastSheet = "rightSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_WEST) { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, (currentFrame * widthPerFrame), 1, (currentFrame * widthPerFrame) + widthPerFrame, height, null, null); this.lastSheet = "leftSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_NONE) { if(lastSheet == "leftSheet") { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, 1, 1, widthPerFrame, height, null, null); } if(lastSheet == "rightSheet") { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, 1, 1, widthPerFrame, height, null, null); } } tick++; }
public void drawSprite(Graphics g, int x, int y) { if (tick == 9) { tick = 0; currentFrame++; currentFrame = (currentFrame % 3); } if (kangaroo.getVerticalSpeed() != 0) { if(kangaroo.getDirection() == Direction.DIRECTION_EAST) { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, widthPerFrame*2, 1, widthPerFrame*3, height, null, null); this.lastSheet = "rightSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_WEST) { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, widthPerFrame*2, 1, widthPerFrame*3, height, null, null); this.lastSheet = "leftSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_NONE) { if(lastSheet == "leftSheet") { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, 1, 1, widthPerFrame, height, null, null); } if(lastSheet == "rightSheet") { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, 1, 1, widthPerFrame, height, null, null); } } } else if(kangaroo.getDirection() == Direction.DIRECTION_EAST) { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, (currentFrame * widthPerFrame), 1, (currentFrame * widthPerFrame) + widthPerFrame, height, null, null); this.lastSheet = "rightSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_WEST) { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, (currentFrame * widthPerFrame), 1, (currentFrame * widthPerFrame) + widthPerFrame, height, null, null); this.lastSheet = "leftSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_NONE) { if(lastSheet == "leftSheet") { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, 1, 1, widthPerFrame, height, null, null); } if(lastSheet == "rightSheet") { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, 1, 1, widthPerFrame, height, null, null); } } tick++; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_player, null); final LinearLayout playerLinearLayout = (LinearLayout) view.findViewById(R.id.player_linearlayout); playerLinearLayout.setBackground(new ColorDrawable(Color.parseColor("#88000000"))); final LinearLayout playerMainInfoLinearLayout = (LinearLayout) view.findViewById(R.id.player_maininfo_linearlayout); playerMainInfoLinearLayout.setBackground(new ColorDrawable(Color.parseColor("#dd000000"))); ImageButton showContentButton = (ImageButton) view.findViewById(R.id.showContentButton); showContentButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (playerMainInfoLinearLayout.getVisibility() == View.VISIBLE) { AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f); anim.setDuration(250); anim.setFillAfter(true); playerMainInfoLinearLayout.startAnimation(anim); playerMainInfoLinearLayout.setVisibility(View.INVISIBLE); playerMainInfoLinearLayout.setClickable(false); } else { AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f); anim.setDuration(250); anim.setFillAfter(true); playerMainInfoLinearLayout.startAnimation(anim); playerMainInfoLinearLayout.setVisibility(View.VISIBLE); playerMainInfoLinearLayout.setClickable(true); } } }); return view; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_player, null); final LinearLayout playerLinearLayout = (LinearLayout) view.findViewById(R.id.player_linearlayout); final LinearLayout playerMainInfoLinearLayout = (LinearLayout) view.findViewById(R.id.player_maininfo_linearlayout); ImageButton showContentButton = (ImageButton) view.findViewById(R.id.showContentButton); showContentButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (playerMainInfoLinearLayout.getVisibility() == View.VISIBLE) { AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f); anim.setDuration(250); anim.setFillAfter(true); playerMainInfoLinearLayout.startAnimation(anim); playerMainInfoLinearLayout.setVisibility(View.INVISIBLE); playerMainInfoLinearLayout.setClickable(false); } else { AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f); anim.setDuration(250); anim.setFillAfter(true); playerMainInfoLinearLayout.startAnimation(anim); playerMainInfoLinearLayout.setVisibility(View.VISIBLE); playerMainInfoLinearLayout.setClickable(true); } } }); return view; }
private void translateFromXML(Node xmlNode, Class stateClass, TranslationSpace translationSpace, boolean doRecursiveDescent) throws XmlTranslationException { if (xmlNode.hasAttributes()) { NamedNodeMap xmlNodeAttributes = xmlNode.getAttributes(); for (int i = 0; i < xmlNodeAttributes.getLength(); i++) { Node xmlAttr = xmlNodeAttributes.item(i); if (xmlAttr.getNodeValue() != null) { String xmlAttrName = xmlAttr.getNodeName(); String methodName = XmlTools.methodNameFromTagName(xmlAttrName); String value = xmlAttr.getNodeValue(); if (xmlAttrName.equals("id")) this.elementByIdMap.put(value, this); if (value != null) value = XmlTools.unescapeXML(value); try { Class[] parameters = new Class[1]; parameters[0] = STRING_CLASS; Method attrMethod = stateClass.getMethod(methodName, parameters); Object[] args = new Object[1]; args[0] = value; try { attrMethod.invoke(this,args); } catch (InvocationTargetException e) { println("WEIRD: couldnt run set method for " + xmlAttrName + " even though we found it"); e.printStackTrace(); } catch (IllegalAccessException e) { println("WEIRD: couldnt run set method for " + xmlAttrName + " even though we found it"); e.printStackTrace(); } } catch (NoSuchMethodException e) { String fieldName = XmlTools.fieldNameFromElementName(xmlAttr.getNodeName()); int colonIndex = fieldName.indexOf(':'); String nameSpaceName = null; if (colonIndex > -1) { nameSpaceName = fieldName.substring(0, colonIndex); fieldName = fieldName.substring(colonIndex + 1); } setField(fieldName, value); } } } } if (!doRecursiveDescent) return; NodeList childNodes = xmlNode.getChildNodes(); int numChilds = childNodes.getLength(); for (int i = 0; i < numChilds; i++) { Node childNode = childNodes.item(i); short childNodeType = childNode.getNodeType(); if ((childNodeType != Node.TEXT_NODE) && (childNodeType != Node.CDATA_SECTION_NODE)) { TranslationSpace nameSpaceForTranslation = translationSpace; String childTag = childNode.getNodeName(); int colonIndex = childTag.indexOf(':'); if (colonIndex > 0) { String nameSpaceName = childTag.substring(0, colonIndex); nameSpaceForTranslation = TranslationSpace.get(nameSpaceName); childTag = childTag.substring(colonIndex+1); } String childFieldName = XmlTools.fieldNameFromElementName(childTag); try { Field childField = stateClass.getField(childFieldName); Class childClass = childField.getType(); HashMap leafElementFields = leafElementFields(); if (leafElementFields != null) { if (leafElementFields.get(childFieldName) != null) { Node textElementChild = childNode.getFirstChild(); if (textElementChild != null) { String textNodeValue = textElementChild.getNodeValue(); if (textNodeValue != null) { textNodeValue = XmlTools.unescapeXML(textNodeValue); textNodeValue = textNodeValue.trim(); if (textNodeValue.length() > 0) this.setField(childField, textNodeValue); } } else { } continue; } } ElementState childElementState = getElementState(childClass); childElementState.elementByIdMap = this.elementByIdMap; childElementState.translateFromXML(childNode, childClass, nameSpaceForTranslation, true); addNestedElement(childField, childElementState); } catch (NoSuchFieldException e) { String tagName = childNode.getNodeName(); Class childStateClass= translationSpace.xmlTagToClass(tagName); if (childStateClass != null) { ElementState childElementState = getElementState(childStateClass); childElementState.elementByIdMap = this.elementByIdMap; childElementState.translateFromXML(childNode, childStateClass, translationSpace, true); if (childElementState != null) addNestedElement(childElementState); } } } else if (numChilds == 1) { String text = childNode.getNodeValue(); if (text != null) setTextNodeString(text); } } }
protected void translateFromXML(Node xmlNode, Class stateClass, TranslationSpace translationSpace, boolean doRecursiveDescent) throws XmlTranslationException { if (xmlNode.hasAttributes()) { NamedNodeMap xmlNodeAttributes = xmlNode.getAttributes(); for (int i = 0; i < xmlNodeAttributes.getLength(); i++) { Node xmlAttr = xmlNodeAttributes.item(i); if (xmlAttr.getNodeValue() != null) { String xmlAttrName = xmlAttr.getNodeName(); String methodName = XmlTools.methodNameFromTagName(xmlAttrName); String value = xmlAttr.getNodeValue(); if (xmlAttrName.equals("id")) this.elementByIdMap.put(value, this); if (value != null) value = XmlTools.unescapeXML(value); try { Class[] parameters = new Class[1]; parameters[0] = STRING_CLASS; Method attrMethod = stateClass.getMethod(methodName, parameters); Object[] args = new Object[1]; args[0] = value; try { attrMethod.invoke(this,args); } catch (InvocationTargetException e) { println("WEIRD: couldnt run set method for " + xmlAttrName + " even though we found it"); e.printStackTrace(); } catch (IllegalAccessException e) { println("WEIRD: couldnt run set method for " + xmlAttrName + " even though we found it"); e.printStackTrace(); } } catch (NoSuchMethodException e) { String fieldName = XmlTools.fieldNameFromElementName(xmlAttr.getNodeName()); int colonIndex = fieldName.indexOf(':'); String nameSpaceName = null; if (colonIndex > -1) { nameSpaceName = fieldName.substring(0, colonIndex); fieldName = fieldName.substring(colonIndex + 1); } setField(fieldName, value); } } } } if (!doRecursiveDescent) return; NodeList childNodes = xmlNode.getChildNodes(); int numChilds = childNodes.getLength(); for (int i = 0; i < numChilds; i++) { Node childNode = childNodes.item(i); short childNodeType = childNode.getNodeType(); if ((childNodeType != Node.TEXT_NODE) && (childNodeType != Node.CDATA_SECTION_NODE)) { TranslationSpace nameSpaceForTranslation = translationSpace; String childTag = childNode.getNodeName(); int colonIndex = childTag.indexOf(':'); if (colonIndex > 0) { String nameSpaceName = childTag.substring(0, colonIndex); nameSpaceForTranslation = TranslationSpace.get(nameSpaceName); childTag = childTag.substring(colonIndex+1); } String childFieldName = XmlTools.fieldNameFromElementName(childTag); try { Field childField = stateClass.getField(childFieldName); Class childClass = childField.getType(); HashMap leafElementFields = leafElementFields(); if (leafElementFields != null) { if (leafElementFields.get(childFieldName) != null) { Node textElementChild = childNode.getFirstChild(); if (textElementChild != null) { String textNodeValue = textElementChild.getNodeValue(); if (textNodeValue != null) { textNodeValue = XmlTools.unescapeXML(textNodeValue); textNodeValue = textNodeValue.trim(); if (textNodeValue.length() > 0) this.setField(childField, textNodeValue); } } else { } continue; } } ElementState childElementState = getElementState(childClass); childElementState.elementByIdMap = this.elementByIdMap; childElementState.translateFromXML(childNode, childClass, nameSpaceForTranslation, true); addNestedElement(childField, childElementState); } catch (NoSuchFieldException e) { String tagName = childNode.getNodeName(); Class childStateClass= translationSpace.xmlTagToClass(tagName); if (childStateClass != null) { ElementState childElementState = getElementState(childStateClass); childElementState.elementByIdMap = this.elementByIdMap; childElementState.translateFromXML(childNode, childStateClass, translationSpace, true); if (childElementState != null) addNestedElement(childElementState); } } } else if (numChilds == 1) { String text = childNode.getNodeValue(); if (text != null) setTextNodeString(text); } } }
public void tallyCCInd(byte[] a, int cc){ if (cc == 2) cc = 0; byte a1 = a[0]; byte a2 = a[1]; if (a1 >= 5 && a2 >= 5){ counts[cc][0]++; counts[cc][1]++; if (allele1 == 0){ allele1 = (byte)(a1 - 4); allele2 = (byte)(a2 - 4); } }else{ if (allele1 == 0){ allele1 = a1; if (a1 != a2){ allele2 = a2; } }else if (allele2 == 0){ if (a1 != allele1){ allele2 = a1; }else if (a2 != allele1){ allele2 = a2; } } if (a1 != 0){ if (a1 == allele1){ counts[cc][0] ++; }else{ counts[cc][1] ++; } } if (a2 != 0){ if (a2 == allele1){ counts[cc][0]++; }else{ counts[cc][1]++; } } } }
public void tallyCCInd(byte[] a, int cc){ if (cc == 0) return; if (cc == 2) cc = 0; byte a1 = a[0]; byte a2 = a[1]; if (a1 >= 5 && a2 >= 5){ counts[cc][0]++; counts[cc][1]++; if (allele1 == 0){ allele1 = (byte)(a1 - 4); allele2 = (byte)(a2 - 4); } }else{ if (allele1 == 0){ allele1 = a1; if (a1 != a2){ allele2 = a2; } }else if (allele2 == 0){ if (a1 != allele1){ allele2 = a1; }else if (a2 != allele1){ allele2 = a2; } } if (a1 != 0){ if (a1 == allele1){ counts[cc][0] ++; }else{ counts[cc][1] ++; } } if (a2 != 0){ if (a2 == allele1){ counts[cc][0]++; }else{ counts[cc][1]++; } } } }
public void onEnable() { try { final File configFile = new File(this.getDataFolder(), "config.yml"); if (!configFile.exists()) { this.saveDefaultConfig(); this.autoDisable(); return; } this.configuration = new Configuration(configFile); this.configuration.load(); this.cancelChat = this.configuration.getBoolean("settings.cancel-chat", false); this.endpoints = new HashMap<String, EndPoint>(); this.tags = new HashMap<EndPoint, String>(); this.irccmds = new HashMap<String, CommandEndPoint>(); this.taggroups = new HashMap<String, List<String>>(); final PluginDescriptionFile desc = this.getDescription(); CraftIRC.VERSION = desc.getVersion(); this.server = this.getServer(); this.bots = new ArrayList<ConfigurationNode>(this.configuration.getNodeList("bots", null)); this.channodes = new HashMap<Integer, ArrayList<ConfigurationNode>>(); for (int botID = 0; botID < this.bots.size(); botID++) { this.channodes.put(botID, new ArrayList<ConfigurationNode>(this.bots.get(botID).getNodeList("channels", null))); } this.colormap = new ArrayList<ConfigurationNode>(this.configuration.getNodeList("colormap", null)); this.paths = new HashMap<Path, ConfigurationNode>(); for (final ConfigurationNode path : this.configuration.getNodeList("paths", new LinkedList<ConfigurationNode>())) { final Path identifier = new Path(path.getString("source"), path.getString("target")); if (!identifier.getSourceTag().equals(identifier.getTargetTag()) && !this.paths.containsKey(identifier)) { this.paths.put(identifier, path); } } this.replaceFilters = new HashMap<String, Map<String, String>>(); try { for (String key : this.configuration.getNode("filters").getKeys()) { Map<String, String> replaceMap = new HashMap<String, String>(); this.replaceFilters.put(key, replaceMap); for (ConfigurationNode fieldNode : this.configuration.getNodeList("filters." + key, null)) { Map<String, Object> patterns = fieldNode.getAll(); if (patterns != null) for (String pattern : patterns.keySet()) replaceMap.put(pattern, patterns.get(pattern).toString()); } for (String unMappedEntry : this.configuration.getStringList("filters." + key, null)) if (unMappedEntry.length() > 0 && unMappedEntry.charAt(0) != '{') replaceMap.put(unMappedEntry, ""); } } catch (NullPointerException e) { } this.retry = new HashMap<String, RetryTask>(); this.retryTimer = new Timer(); this.getServer().getPluginManager().registerEvents(this.listener, this); this.getServer().getPluginManager().registerEvents(this.sayListener, this); if ((this.cMinecraftTag() != null) && !this.cMinecraftTag().equals("")) { this.registerEndPoint(this.cMinecraftTag(), new MinecraftPoint(this, this.getServer())); for (final String cmd : this.cCmdWordSay(null)) { this.registerCommand(this.cMinecraftTag(), cmd); } for (final String cmd : this.cCmdWordPlayers(null)) { this.registerCommand(this.cMinecraftTag(), cmd); } if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cMinecraftTag(), this.cMinecraftTagGroup()); } } if ((this.cCancelledTag() != null) && !this.cCancelledTag().equals("")) { this.registerEndPoint(this.cCancelledTag(), new MinecraftPoint(this, this.getServer())); if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cCancelledTag(), this.cMinecraftTagGroup()); } } if ((this.cConsoleTag() != null) && !this.cConsoleTag().equals("")) { this.registerEndPoint(this.cConsoleTag(), new ConsolePoint(this, this.getServer())); for (final String cmd : this.cCmdWordCmd(null)) { this.registerCommand(this.cConsoleTag(), cmd); } if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cConsoleTag(), this.cMinecraftTagGroup()); } } this.instances = new ArrayList<Minebot>(); for (int i = 0; i < this.bots.size(); i++) { this.instances.add(new Minebot(this, i, this.cDebug())); } this.loadTagGroups(); CraftIRC.dolog("Enabled."); this.hold = new HashMap<HoldType, Boolean>(); this.holdTimer = new Timer(); if (this.cHold("chat") > 0) { this.hold.put(HoldType.CHAT, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.CHAT), this.cHold("chat")); } else { this.hold.put(HoldType.CHAT, false); } if (this.cHold("joins") > 0) { this.hold.put(HoldType.JOINS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.JOINS), this.cHold("joins")); } else { this.hold.put(HoldType.JOINS, false); } if (this.cHold("quits") > 0) { this.hold.put(HoldType.QUITS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.QUITS), this.cHold("quits")); } else { this.hold.put(HoldType.QUITS, false); } if (this.cHold("kicks") > 0) { this.hold.put(HoldType.KICKS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.KICKS), this.cHold("kicks")); } else { this.hold.put(HoldType.KICKS, false); } if (this.cHold("bans") > 0) { this.hold.put(HoldType.BANS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.BANS), this.cHold("bans")); } else { this.hold.put(HoldType.BANS, false); } if (this.cHold("deaths") > 0) { this.hold.put(HoldType.DEATHS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.DEATHS), this.cHold("deaths")); } else { this.hold.put(HoldType.DEATHS, false); } this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { if (CraftIRC.this.getServer().getPluginManager().isPluginEnabled("Vault")) { try { CraftIRC.this.vault = CraftIRC.this.getServer().getServicesManager().getRegistration(Chat.class).getProvider(); } catch (final Exception e) { } } } }); this.setDebug(this.cDebug()); } catch (final Exception e) { e.printStackTrace(); } try { new Metrics(this).start(); } catch (final IOException e) { } } private void autoDisable() { CraftIRC.dolog("Auto-disabling..."); this.getServer().getPluginManager().disablePlugin(this); } @Override public void onDisable() { try { this.retryTimer.cancel(); this.holdTimer.cancel(); if (this.bots != null) { for (int i = 0; i < this.bots.size(); i++) { this.instances.get(i).disconnect(); this.instances.get(i).dispose(); } } CraftIRC.dolog("Disabled."); } catch (final Exception e) { e.printStackTrace(); } } @Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { final String commandName = command.getName().toLowerCase(); try { if (commandName.equals("ircsay")){ if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgSay(sender,args); } if (commandName.equals("ircmsg")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgToTag(sender, args); } else if (commandName.equals("ircmsguser")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgToUser(sender, args); } else if (commandName.equals("ircusers")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdGetUserList(sender, args); } else if (commandName.equals("admins!")) { if (!sender.hasPermission("craftirc.admins")) { return false; } return this.cmdNotifyIrcAdmins(sender, args); } else if (commandName.equals("ircraw")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdRawIrcCommand(sender, args); } else if (commandName.equals("ircreload")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } this.getServer().getPluginManager().disablePlugin(this); this.getServer().getPluginManager().enablePlugin(this); return true; } else { return false; } } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgSay(CommandSender sender, String[] args) { try{ RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), null, "chat"); if (msg == null) { return true; } String senderName=sender.getName(); String world=""; String prefix=""; String suffix=""; if(sender instanceof Player){ Player player = (Player) sender; senderName = player.getDisplayName(); world = player.getWorld().getName(); prefix = this.getPrefix(player); suffix = this.getSuffix(player); } msg.setField("sender", senderName); msg.setField("message", Util.combineSplit(0, args, " ")); msg.setField("world", world); msg.setField("realSender", sender.getName()); msg.setField("prefix", prefix); msg.setField("suffix", suffix); msg.doNotColor("message"); msg.post(); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgToTag(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdMsgToAll()"); } if (args.length < 2) { return false; } final String msgToSend = Util.combineSplit(1, args, " "); final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), this.getEndPoint(args[0]), "chat"); if (msg == null) { return true; } if (sender instanceof Player) { msg.setField("sender", ((Player) sender).getDisplayName()); } else { msg.setField("sender", sender.getName()); } msg.setField("message", msgToSend); msg.doNotColor("message"); msg.post(); sender.sendMessage("Message sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgToUser(CommandSender sender, String[] args) { try { if (args.length < 3) { return false; } final String msgToSend = Util.combineSplit(2, args, " "); final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), this.getEndPoint(args[0]), "private"); if (msg == null) { return true; } if (sender instanceof Player) { msg.setField("sender", ((Player) sender).getDisplayName()); } else { msg.setField("sender", sender.getName()); }; msg.setField("message", msgToSend); msg.doNotColor("message"); boolean sameEndPoint = this.getEndPoint(this.cMinecraftTag()).equals(this.getEndPoint(args[0])); if (sameEndPoint && sender instanceof Player) { Player recipient = getServer().getPlayer(args[1]); if (recipient != null && recipient.isOnline() && ((Player)sender).canSee(recipient)) msg.postToUser(args[1]); } else msg.postToUser(args[1]); sender.sendMessage("Message sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdGetUserList(CommandSender sender, String[] args) { try { if (args.length == 0) { return false; } sender.sendMessage("Users in " + args[0] + ":"); final List<String> userlists = this.ircUserLists(args[0]); for (final String string : userlists) { sender.sendMessage(string); } return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdNotifyIrcAdmins(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdNotifyIrcAdmins()"); } if ((args.length == 0) || !(sender instanceof Player)) { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdNotifyIrcAdmins() - args.length == 0 or Sender != player "); } return false; } final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), null, "admin"); if (msg == null) { return true; } msg.setField("sender", ((Player) sender).getDisplayName()); msg.setField("message", Util.combineSplit(0, args, " ")); msg.setField("world", ((Player) sender).getWorld().getName()); msg.doNotColor("message"); msg.post(true); sender.sendMessage("Admin notice sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdRawIrcCommand(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("cmdRawIrcCommand(sender=" + sender.toString() + ", args=" + Util.combineSplit(0, args, " ")); } if (args.length < 2) { return false; } this.sendRawToBot(Util.combineSplit(1, args, " "), Integer.parseInt(args[0])); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } public RelayedMessage newMsg(EndPoint source, EndPoint target, String eventType) { if (source == null) { return null; } if ((target == null) || this.cPathExists(this.getTag(source), this.getTag(target))) { return new RelayedMessage(this, source, target, eventType); } else { if (this.isDebug()) { CraftIRC.dolog("Failed to prepare message: " + this.getTag(source) + " -> " + this.getTag(target) + " (missing path)"); } return null; } } public RelayedMessage newMsgToTag(EndPoint source, String target, String eventType) { if (source == null) { return null; } EndPoint targetpoint = null; if (target != null) { if (this.cPathExists(this.getTag(source), target)) { targetpoint = this.getEndPoint(target); if (targetpoint == null) { CraftIRC.dolog("The requested target tag '" + target + "' isn't registered."); } } else { return null; } } return new RelayedMessage(this, source, targetpoint, eventType); } public RelayedCommand newCmd(EndPoint source, String command) { if (source == null) { return null; } final CommandEndPoint target = this.irccmds.get(command); if (target == null) { return null; } if (!this.cPathExists(this.getTag(source), this.getTag(target))) { return null; } final RelayedCommand cmd = new RelayedCommand(this, source, target); cmd.setField("command", command); return cmd; } public boolean registerEndPoint(String tag, EndPoint ep) { if (this.isDebug()) { CraftIRC.dolog("Registering endpoint: " + tag); } if (tag == null) { CraftIRC.dolog("Failed to register endpoint - No tag!"); } if ((this.endpoints.get(tag) != null) || (this.tags.get(ep) != null)) { CraftIRC.dolog("Couldn't register an endpoint tagged '" + tag + "' because either the tag or the endpoint already exist."); return false; } if (tag == "*") { CraftIRC.dolog("Couldn't register an endpoint - the character * can't be used as a tag."); return false; } this.endpoints.put(tag, ep); this.tags.put(ep, tag); return true; } public boolean endPointRegistered(String tag) { return this.endpoints.get(tag) != null; } public EndPoint getEndPoint(String tag) { return this.endpoints.get(tag); } public String getTag(EndPoint ep) { return this.tags.get(ep); } public boolean registerCommand(String tag, String command) { if (this.isDebug()) { CraftIRC.dolog("Registering command: " + command + " to endpoint:" + tag); } final EndPoint ep = this.getEndPoint(tag); if (ep == null) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because there is no such tag."); return false; } if (!(ep instanceof CommandEndPoint)) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because it's not capable of handling commands."); return false; } if (this.irccmds.containsKey(command)) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because that command is already registered."); return false; } this.irccmds.put(command, (CommandEndPoint) ep); return true; } public boolean unregisterCommand(String command) { if (!this.irccmds.containsKey(command)) { return false; } this.irccmds.remove(command); return true; } public boolean unregisterEndPoint(String tag) { final EndPoint ep = this.getEndPoint(tag); if (ep == null) { return false; } this.endpoints.remove(tag); this.tags.remove(ep); this.ungroupTag(tag); if (ep instanceof CommandEndPoint) { final CommandEndPoint cep = (CommandEndPoint) ep; for (final String cmd : this.irccmds.keySet()) { if (this.irccmds.get(cmd) == cep) { this.irccmds.remove(cmd); } } } return true; } public boolean groupTag(String tag, String group) { if (this.getEndPoint(tag) == null) { return false; } List<String> tags = this.taggroups.get(group); if (tags == null) { tags = new ArrayList<String>(); this.taggroups.put(group, tags); } tags.add(tag); return true; } public void ungroupTag(String tag) { for (final String group : this.taggroups.keySet()) { this.taggroups.get(group).remove(tag); } } public void clearGroup(String group) { this.taggroups.remove(group); } public boolean checkTagsGrouped(String tagA, String tagB) { for (final String group : this.taggroups.keySet()) { if (this.taggroups.get(group).contains(tagA) && this.taggroups.get(group).contains(tagB)) { return true; } } return false; } boolean delivery(RelayedMessage msg) { return this.delivery(msg, null, null, RelayedMessage.DeliveryMethod.STANDARD); } boolean delivery(RelayedMessage msg, List<EndPoint> destinations) { return this.delivery(msg, destinations, null, RelayedMessage.DeliveryMethod.STANDARD); } boolean delivery(RelayedMessage msg, List<EndPoint> knownDestinations, String username) { return this.delivery(msg, knownDestinations, username, RelayedMessage.DeliveryMethod.STANDARD); } boolean delivery(RelayedMessage msg, List<EndPoint> knownDestinations, String username, RelayedMessage.DeliveryMethod dm) { final String sourceTag = this.getTag(msg.getSource()); msg.setField("source", sourceTag); List<EndPoint> destinations; if (this.isDebug()) { CraftIRC.dolog("X->" + (knownDestinations.size() > 0 ? knownDestinations.toString() : "*") + ": " + msg.toString()); } if (knownDestinations.size() < 1) { destinations = new LinkedList<EndPoint>(); for (final String targetTag : this.cPathsFrom(sourceTag)) { final EndPoint ep = this.getEndPoint(targetTag); if (ep == null) { continue; } if ((ep instanceof SecuredEndPoint) && SecuredEndPoint.Security.REQUIRE_TARGET.equals(((SecuredEndPoint) ep).getSecurity())) { continue; } if (!this.cPathAttribute(sourceTag, targetTag, "attributes." + msg.getEvent())) { continue; } if ((dm == RelayedMessage.DeliveryMethod.ADMINS) && !this.cPathAttribute(sourceTag, targetTag, "attributes.admin")) { continue; } destinations.add(ep); } if (this.cAutoPaths()) { for (final EndPoint ep : this.endpoints.values()) { if (ep == null) { continue; } if (msg.getSource().equals(ep) || destinations.contains(ep)) { continue; } if ((ep instanceof SecuredEndPoint) && !SecuredEndPoint.Security.UNSECURED.equals(((SecuredEndPoint) ep).getSecurity())) { continue; } final String targetTag = this.getTag(ep); if (this.checkTagsGrouped(sourceTag, targetTag)) { continue; } if (!this.cPathAttribute(sourceTag, targetTag, "attributes." + msg.getEvent())) { continue; } if ((dm == RelayedMessage.DeliveryMethod.ADMINS) && !this.cPathAttribute(sourceTag, targetTag, "attributes.admin")) { continue; } if (this.cPathAttribute(sourceTag, targetTag, "disabled")) { continue; } destinations.add(ep); } } } else { destinations = new LinkedList<EndPoint>(knownDestinations); } if (destinations.size() < 1) { return false; } boolean success = true; for (final EndPoint destination : destinations) { final String targetTag = this.getTag(destination); if(targetTag.equals(this.cCancelledTag())){ continue; } msg.setField("target", targetTag); if ((msg instanceof RelayedCommand) && this.matchesFilter(msg, this.cPathFilters(sourceTag, targetTag))) { if (knownDestinations != null) { success = false; } continue; } if (this.isDebug()) { CraftIRC.dolog("-->X: " + msg.toString()); } if (username != null) { success = success && destination.userMessageIn(username, msg); } else if (dm == RelayedMessage.DeliveryMethod.ADMINS) { success = destination.adminMessageIn(msg); } else if (dm == RelayedMessage.DeliveryMethod.COMMAND) { if (!(destination instanceof CommandEndPoint)) { continue; } ((CommandEndPoint) destination).commandIn((RelayedCommand) msg); } else { destination.messageIn(msg); } } return success; } boolean matchesFilter(RelayedMessage msg, List<ConfigurationNode> filters) { if (filters == null) { return false; } newFilter: for (final ConfigurationNode filter : filters) { for (final String key : filter.getKeys()) { final Pattern condition = Pattern.compile(filter.getString(key, "")); if (condition == null) { continue newFilter; } final String subject = msg.getField(key); if (subject == null) { continue newFilter; } final Matcher check = condition.matcher(subject); if (!check.find()) { continue newFilter; } } return true; } return false; } public Minebot getBot(int bot){ return this.instances.get(bot); } public void sendRawToBot(String rawMessage, int bot) { if (this.isDebug()) { CraftIRC.dolog("sendRawToBot(bot=" + bot + ", message=" + rawMessage); } final Minebot targetBot = this.instances.get(bot); targetBot.sendRawLineViaQueue(rawMessage); } public void sendMsgToTargetViaBot(String message, String target, int bot) { final Minebot targetBot = this.instances.get(bot); targetBot.sendMessage(target, message); } public List<String> ircUserLists(String tag) { return this.getEndPoint(tag).listDisplayUsers(); } void setDebug(boolean d) { this.debug = d; for (int i = 0; i < this.bots.size(); i++) { this.instances.get(i).setVerbose(d); } CraftIRC.dolog("DEBUG [" + (d ? "ON" : "OFF") + "]"); } public String getPrefix(Player p) { String result = ""; if (this.vault != null) { try { result = this.vault.getPlayerPrefix(p); } catch (final Exception e) { } } return result; } public String getSuffix(Player p) { String result = ""; if (this.vault != null) { try { result = this.vault.getPlayerSuffix(p); } catch (final Exception e) { } } return result; } public boolean isDebug() { return this.debug; } boolean checkPerms(Player pl, String path) { return pl.hasPermission(path); } boolean checkPerms(String pl, String path) { final Player pit = this.getServer().getPlayer(pl); if (pit != null) { return pit.hasPermission(path); } return false; } public String colorizeName(String name) { final Pattern color_codes = Pattern.compile(ChatColor.COLOR_CHAR + "[0-9a-f]"); Matcher find_colors = color_codes.matcher(name); while (find_colors.find()) { name = find_colors.replaceFirst(Character.toString((char) 3) + this.cColorIrcFromGame(find_colors.group())); find_colors = color_codes.matcher(name); } return name; } protected void enqueueConsoleCommand(String cmd) { try { this.getServer().dispatchCommand(this.getServer().getConsoleSender(), cmd); } catch (final Exception e) { e.printStackTrace(); } } void scheduleForRetry(Minebot bot, String channel) { this.retryTimer.schedule(new RetryTask(this, bot, channel), this.cRetryDelay()); } private ConfigurationNode getChanNode(int bot, String channel) { final ArrayList<ConfigurationNode> botChans = this.channodes.get(bot); for (final ConfigurationNode chan : botChans) { if (chan.getString("name").equalsIgnoreCase(channel)) { return chan; } } return Configuration.getEmptyNode(); } public List<ConfigurationNode> cChannels(int bot) { return this.channodes.get(bot); } private ConfigurationNode getPathNode(String source, String target) { ConfigurationNode result = this.paths.get(new Path(source, target)); if (result == null) { return this.configuration.getNode("default-attributes"); } ConfigurationNode basepath; if (result.getKeys().contains("base") && ((basepath = result.getNode("base")) != null)) { final ConfigurationNode basenode = this.paths.get(new Path(basepath.getString("source", ""), basepath.getString("target", ""))); if (basenode != null) { result = basenode; } } return result; } public String cMinecraftTag() { return this.configuration.getString("settings.minecraft-tag", "minecraft"); } public String cCancelledTag() { return this.configuration.getString("settings.cancelled-tag", "cancelled"); } public String cConsoleTag() { return this.configuration.getString("settings.console-tag", "console"); } public String cMinecraftTagGroup() { return this.configuration.getString("settings.minecraft-group-name", "minecraft"); } public String cIrcTagGroup() { return this.configuration.getString("settings.irc-group-name", "irc"); } public boolean cAutoPaths() { return this.configuration.getBoolean("settings.auto-paths", false); } public boolean cCancelChat() { return cancelChat; } public boolean cDebug() { return this.configuration.getBoolean("settings.debug", false); } public ArrayList<String> cConsoleCommands() { return new ArrayList<String>(this.configuration.getStringList("settings.console-commands", null)); } public int cHold(String eventType) { return this.configuration.getInt("settings.hold-after-enable." + eventType, 0); } public String cFormatting(String eventType, RelayedMessage msg) { return this.cFormatting(eventType, msg, null); } public String cFormatting(String eventType, RelayedMessage msg, EndPoint realTarget) { final String source = this.getTag(msg.getSource()), target = this.getTag(realTarget != null ? realTarget : msg.getTarget()); if ((source == null) || (target == null)) { CraftIRC.dowarn("Attempted to obtain formatting for invalid path " + source + " -> " + target + " ."); return this.cDefaultFormatting(eventType, msg); } final ConfigurationNode pathConfig = this.paths.get(new Path(source, target)); if ((pathConfig != null) && (pathConfig.getString("formatting." + eventType, null) != null)) { return pathConfig.getString("formatting." + eventType, null); } else { return this.cDefaultFormatting(eventType, msg); } } public String cDefaultFormatting(String eventType, RelayedMessage msg) { if (msg.getSource().getType() == EndPoint.Type.MINECRAFT) { return this.configuration.getString("settings.formatting.from-game." + eventType); } if (msg.getSource().getType() == EndPoint.Type.IRC) { return this.configuration.getString("settings.formatting.from-irc." + eventType); } if (msg.getSource().getType() == EndPoint.Type.PLAIN) { return this.configuration.getString("settings.formatting.from-plain." + eventType); } return ""; } public String cColorIrcFromGame(String game) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("game").equals(game)) { return (color.getString("irc").length() == 1 ? "0" : "") + color.getString("irc", this.cColorIrcFromName("foreground")); } } return this.cColorIrcFromName("foreground"); } public String cColorIrcFromName(String name) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("name").equalsIgnoreCase(name) && (color.getProperty("irc") != null)) { return color.getString("irc", "01"); } } if (name.equalsIgnoreCase("foreground")) { return "01"; } else { return this.cColorIrcFromName("foreground"); } } public String cColorGameFromIrc(String irc) { if (irc.length() == 1) irc = "0"+irc; ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("irc", "").equals(irc) || "0".concat(color.getString("irc", "")).equals(irc)) { return color.getString("game", this.cColorGameFromName("foreground")); } } return this.cColorGameFromName("foreground"); } public String cColorGameFromName(String name) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("name").equalsIgnoreCase(name) && (color.getProperty("game") != null)) { return color.getString("game", "\u00C2\u00A7f"); } } if (name.equalsIgnoreCase("foreground")) { return "\u00C2\u00A7f"; } else { return this.cColorGameFromName("foreground"); } } public String cBindLocalAddr() { return this.configuration.getString("settings.bind-address", ""); } public int cRetryDelay() { return this.configuration.getInt("settings.retry-delay", 10) * 1000; } public String cBotNickname(int bot) { return this.bots.get(bot).getString("nickname", "CraftIRCbot"); } public String cBotServer(int bot) { return this.bots.get(bot).getString("server", "irc.esper.net"); } public int cBotPort(int bot) { return this.bots.get(bot).getInt("port", 6667); } public int cBotBindPort(int bot) { return this.bots.get(bot).getInt("bind-port", 0); } public String cBotLogin(int bot) { return this.bots.get(bot).getString("userident", ""); } public String cBotPassword(int bot) { return this.bots.get(bot).getString("serverpass", ""); } public boolean cBotSsl(int bot) { return this.bots.get(bot).getBoolean("ssl", false); } public int cBotMessageDelay(int bot) { return this.bots.get(bot).getInt("message-delay", 1000); } public int cBotQueueSize(int bot) { return this.bots.get(bot).getInt("queue-size", 5); } public String cCommandPrefix(int bot) { return this.bots.get(bot).getString("command-prefix", this.configuration.getString("settings.command-prefix", ".")); } public List<String> cCmdWordCmd(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("cmd"); final List<String> result = this.configuration.getStringList("settings.irc-commands.cmd", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.cmd", result); } return result; } public List<String> cCmdWordSay(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("say"); final List<String> result = this.configuration.getStringList("settings.irc-commands.say", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.say", result); } return result; } public List<String> cCmdWordPlayers(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("players"); final List<String> result = this.configuration.getStringList("settings.irc-commands.players", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.players", result); } return result; } public ArrayList<String> cBotAdminPrefixes(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("admin-prefixes", null)); } public ArrayList<String> cBotIgnoredUsers(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("ignored-users", null)); } public String cBotAuthMethod(int bot) { return this.bots.get(bot).getString("auth.method", "nickserv"); } public String cBotAuthUsername(int bot) { return this.bots.get(bot).getString("auth.username", ""); } public String cBotAuthPassword(int bot) { return this.bots.get(bot).getString("auth.password", ""); } public ArrayList<String> cBotOnConnect(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("on-connect", null)); } public String cChanName(int bot, String channel) { return this.getChanNode(bot, channel).getString("name", "#changeme"); } public String cChanTag(int bot, String channel) { return this.getChanNode(bot, channel).getString("tag", String.valueOf(bot) + "_" + channel); } public String cChanPassword(int bot, String channel) { return this.getChanNode(bot, channel).getString("password", ""); } public ArrayList<String> cChanOnJoin(int bot, String channel) { return new ArrayList<String>(this.getChanNode(bot, channel).getStringList("on-join", null)); } public List<String> cPathsFrom(String source) { final List<String> results = new LinkedList<String>(); for (final Path path : this.paths.keySet()) { if (!path.getSourceTag().equals(source)) { continue; } if (this.paths.get(path).getBoolean("disable", false)) { continue; } results.add(path.getTargetTag()); } return results; } List<String> cPathsTo(String target) { final List<String> results = new LinkedList<String>(); for (final Path path : this.paths.keySet()) { if (!path.getTargetTag().equals(target)) { continue; } if (this.paths.get(path).getBoolean("disable", false)) { continue; } results.add(path.getSourceTag()); } return results; } public boolean cPathExists(String source, String target) { final ConfigurationNode pathNode = this.getPathNode(source, target); return (pathNode != null) && !pathNode.getBoolean("disabled", false); } public boolean cPathAttribute(String source, String target, String attribute) { final ConfigurationNode node = this.getPathNode(source, target); if (node.getProperty(attribute) != null) { return node.getBoolean(attribute, false); } else { return this.configuration.getNode("default-attributes").getBoolean(attribute, false); } } public List<ConfigurationNode> cPathFilters(String source, String target) { return this.getPathNode(source, target).getNodeList("filters", new ArrayList<ConfigurationNode>()); } public Map<String, Map<String, String>> cReplaceFilters() { return this.replaceFilters; } void loadTagGroups() { final List<String> groups = this.configuration.getKeys("settings.tag-groups"); if (groups == null) { return; } for (final String group : groups) { for (final String tag : this.configuration.getStringList("settings.tag-groups." + group, new ArrayList<String>())) { this.groupTag(tag, group); } } } boolean cUseMapAsWhitelist(int bot) { return this.bots.get(bot).getBoolean("use-map-as-whitelist", false); } public String cIrcDisplayName(int bot, String nickname) { return this.bots.get(bot).getString("irc-nickname-map." + nickname, nickname); } public boolean cNicknameIsInIrcMap(int bot, String nickname) { return this.bots.get(bot).getString("irc-nickname-map." + nickname) != null; } public enum HoldType { CHAT, JOINS, QUITS, KICKS, BANS, DEATHS } class RemoveHoldTask extends TimerTask { private final CraftIRC plugin; private final HoldType ht; protected RemoveHoldTask(CraftIRC plugin, HoldType ht) { super(); this.plugin = plugin; this.ht = ht; } @Override public void run() { this.plugin.hold.put(this.ht, false); } } public boolean isHeld(HoldType ht) { return this.hold.get(ht); } public List<ConfigurationNode> getColorMap() { return this.colormap; } public String processAntiHighlight(String input) { String delimiter = this.configuration.getString("settings.anti-highlight"); if (delimiter != null && !delimiter.isEmpty()) { StringBuilder builder = new StringBuilder(); for (int i=0; i < input.length(); i++) { char c = input.charAt(i); builder.append(c); if (c != '\u00A7') { builder.append(delimiter); } } return builder.toString(); } else { return input; } } }
public void onEnable() { try { final File configFile = new File(this.getDataFolder(), "config.yml"); if (!configFile.exists()) { this.saveDefaultConfig(); this.autoDisable(); return; } this.configuration = new Configuration(configFile); this.configuration.load(); this.cancelChat = this.configuration.getBoolean("settings.cancel-chat", false); this.endpoints = new HashMap<String, EndPoint>(); this.tags = new HashMap<EndPoint, String>(); this.irccmds = new HashMap<String, CommandEndPoint>(); this.taggroups = new HashMap<String, List<String>>(); final PluginDescriptionFile desc = this.getDescription(); CraftIRC.VERSION = desc.getVersion(); this.server = this.getServer(); this.bots = new ArrayList<ConfigurationNode>(this.configuration.getNodeList("bots", null)); this.channodes = new HashMap<Integer, ArrayList<ConfigurationNode>>(); for (int botID = 0; botID < this.bots.size(); botID++) { this.channodes.put(botID, new ArrayList<ConfigurationNode>(this.bots.get(botID).getNodeList("channels", null))); } this.colormap = new ArrayList<ConfigurationNode>(this.configuration.getNodeList("colormap", null)); this.paths = new HashMap<Path, ConfigurationNode>(); for (final ConfigurationNode path : this.configuration.getNodeList("paths", new LinkedList<ConfigurationNode>())) { final Path identifier = new Path(path.getString("source"), path.getString("target")); if (!identifier.getSourceTag().equals(identifier.getTargetTag()) && !this.paths.containsKey(identifier)) { this.paths.put(identifier, path); } } this.replaceFilters = new HashMap<String, Map<String, String>>(); try { for (String key : this.configuration.getNode("filters").getKeys()) { Map<String, String> replaceMap = new HashMap<String, String>(); this.replaceFilters.put(key, replaceMap); for (ConfigurationNode fieldNode : this.configuration.getNodeList("filters." + key, null)) { Map<String, Object> patterns = fieldNode.getAll(); if (patterns != null) for (String pattern : patterns.keySet()) replaceMap.put(pattern, patterns.get(pattern).toString()); } for (String unMappedEntry : this.configuration.getStringList("filters." + key, null)) if (unMappedEntry.length() > 0 && unMappedEntry.charAt(0) != '{') replaceMap.put(unMappedEntry, ""); } } catch (NullPointerException e) { } this.retry = new HashMap<String, RetryTask>(); this.retryTimer = new Timer(); this.getServer().getPluginManager().registerEvents(this.listener, this); this.getServer().getPluginManager().registerEvents(this.sayListener, this); if ((this.cMinecraftTag() != null) && !this.cMinecraftTag().equals("")) { this.registerEndPoint(this.cMinecraftTag(), new MinecraftPoint(this, this.getServer())); for (final String cmd : this.cCmdWordSay(null)) { this.registerCommand(this.cMinecraftTag(), cmd); } for (final String cmd : this.cCmdWordPlayers(null)) { this.registerCommand(this.cMinecraftTag(), cmd); } if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cMinecraftTag(), this.cMinecraftTagGroup()); } } if ((this.cCancelledTag() != null) && !this.cCancelledTag().equals("")) { this.registerEndPoint(this.cCancelledTag(), new MinecraftPoint(this, this.getServer())); if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cCancelledTag(), this.cMinecraftTagGroup()); } } if ((this.cConsoleTag() != null) && !this.cConsoleTag().equals("")) { this.registerEndPoint(this.cConsoleTag(), new ConsolePoint(this, this.getServer())); for (final String cmd : this.cCmdWordCmd(null)) { this.registerCommand(this.cConsoleTag(), cmd); } if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cConsoleTag(), this.cMinecraftTagGroup()); } } this.instances = new ArrayList<Minebot>(); for (int i = 0; i < this.bots.size(); i++) { this.instances.add(new Minebot(this, i, this.cDebug())); } this.loadTagGroups(); CraftIRC.dolog("Enabled."); this.hold = new HashMap<HoldType, Boolean>(); this.holdTimer = new Timer(); if (this.cHold("chat") > 0) { this.hold.put(HoldType.CHAT, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.CHAT), this.cHold("chat")); } else { this.hold.put(HoldType.CHAT, false); } if (this.cHold("joins") > 0) { this.hold.put(HoldType.JOINS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.JOINS), this.cHold("joins")); } else { this.hold.put(HoldType.JOINS, false); } if (this.cHold("quits") > 0) { this.hold.put(HoldType.QUITS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.QUITS), this.cHold("quits")); } else { this.hold.put(HoldType.QUITS, false); } if (this.cHold("kicks") > 0) { this.hold.put(HoldType.KICKS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.KICKS), this.cHold("kicks")); } else { this.hold.put(HoldType.KICKS, false); } if (this.cHold("bans") > 0) { this.hold.put(HoldType.BANS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.BANS), this.cHold("bans")); } else { this.hold.put(HoldType.BANS, false); } if (this.cHold("deaths") > 0) { this.hold.put(HoldType.DEATHS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.DEATHS), this.cHold("deaths")); } else { this.hold.put(HoldType.DEATHS, false); } this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { if (CraftIRC.this.getServer().getPluginManager().isPluginEnabled("Vault")) { try { CraftIRC.this.vault = CraftIRC.this.getServer().getServicesManager().getRegistration(Chat.class).getProvider(); } catch (final Exception e) { } } } }); this.setDebug(this.cDebug()); } catch (final Exception e) { e.printStackTrace(); } try { new Metrics(this).start(); } catch (final IOException e) { } } private void autoDisable() { CraftIRC.dolog("Auto-disabling..."); this.getServer().getPluginManager().disablePlugin(this); } @Override public void onDisable() { try { this.retryTimer.cancel(); this.holdTimer.cancel(); if (this.bots != null) { for (int i = 0; i < this.bots.size(); i++) { this.instances.get(i).disconnect(); this.instances.get(i).dispose(); } } CraftIRC.dolog("Disabled."); } catch (final Exception e) { e.printStackTrace(); } } @Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { final String commandName = command.getName().toLowerCase(); try { if (commandName.equals("ircsay")){ if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgSay(sender,args); } if (commandName.equals("ircmsg")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgToTag(sender, args); } else if (commandName.equals("ircmsguser")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgToUser(sender, args); } else if (commandName.equals("ircusers")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdGetUserList(sender, args); } else if (commandName.equals("admins!")) { if (!sender.hasPermission("craftirc.admins")) { return false; } return this.cmdNotifyIrcAdmins(sender, args); } else if (commandName.equals("ircraw")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdRawIrcCommand(sender, args); } else if (commandName.equals("ircreload")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } this.getServer().getPluginManager().disablePlugin(this); this.getServer().getPluginManager().enablePlugin(this); return true; } else { return false; } } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgSay(CommandSender sender, String[] args) { try{ RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), null, "chat"); if (msg == null) { return true; } String senderName=sender.getName(); String world=""; String prefix=""; String suffix=""; if(sender instanceof Player){ Player player = (Player) sender; senderName = player.getDisplayName(); world = player.getWorld().getName(); prefix = this.getPrefix(player); suffix = this.getSuffix(player); } msg.setField("sender", senderName); msg.setField("message", Util.combineSplit(0, args, " ")); msg.setField("world", world); msg.setField("realSender", sender.getName()); msg.setField("prefix", prefix); msg.setField("suffix", suffix); msg.doNotColor("message"); msg.post(); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgToTag(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdMsgToAll()"); } if (args.length < 2) { return false; } final String msgToSend = Util.combineSplit(1, args, " "); final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), this.getEndPoint(args[0]), "chat"); if (msg == null) { return true; } if (sender instanceof Player) { msg.setField("sender", ((Player) sender).getDisplayName()); } else { msg.setField("sender", sender.getName()); } msg.setField("message", msgToSend); msg.doNotColor("message"); msg.post(); sender.sendMessage("Message sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgToUser(CommandSender sender, String[] args) { try { if (args.length < 3) { return false; } final String msgToSend = Util.combineSplit(2, args, " "); final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), this.getEndPoint(args[0]), "private"); if (msg == null) { return true; } if (sender instanceof Player) { msg.setField("sender", ((Player) sender).getDisplayName()); } else { msg.setField("sender", sender.getName()); }; msg.setField("message", msgToSend); msg.doNotColor("message"); boolean sameEndPoint = this.getEndPoint(this.cMinecraftTag()).equals(this.getEndPoint(args[0])); if (sameEndPoint && sender instanceof Player) { Player recipient = getServer().getPlayer(args[1]); if (recipient != null && recipient.isOnline() && ((Player)sender).canSee(recipient)) msg.postToUser(args[1]); } else msg.postToUser(args[1]); sender.sendMessage("Message sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdGetUserList(CommandSender sender, String[] args) { try { if (args.length == 0) { return false; } sender.sendMessage("Users in " + args[0] + ":"); final List<String> userlists = this.ircUserLists(args[0]); for (final String string : userlists) { sender.sendMessage(string); } return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdNotifyIrcAdmins(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdNotifyIrcAdmins()"); } if ((args.length == 0) || !(sender instanceof Player)) { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdNotifyIrcAdmins() - args.length == 0 or Sender != player "); } return false; } final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), null, "admin"); if (msg == null) { return true; } msg.setField("sender", ((Player) sender).getDisplayName()); msg.setField("message", Util.combineSplit(0, args, " ")); msg.setField("world", ((Player) sender).getWorld().getName()); msg.doNotColor("message"); msg.post(true); sender.sendMessage("Admin notice sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdRawIrcCommand(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("cmdRawIrcCommand(sender=" + sender.toString() + ", args=" + Util.combineSplit(0, args, " ")); } if (args.length < 2) { return false; } this.sendRawToBot(Util.combineSplit(1, args, " "), Integer.parseInt(args[0])); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } public RelayedMessage newMsg(EndPoint source, EndPoint target, String eventType) { if (source == null) { return null; } if ((target == null) || this.cPathExists(this.getTag(source), this.getTag(target))) { return new RelayedMessage(this, source, target, eventType); } else { if (this.isDebug()) { CraftIRC.dolog("Failed to prepare message: " + this.getTag(source) + " -> " + this.getTag(target) + " (missing path)"); } return null; } } public RelayedMessage newMsgToTag(EndPoint source, String target, String eventType) { if (source == null) { return null; } EndPoint targetpoint = null; if (target != null) { if (this.cPathExists(this.getTag(source), target)) { targetpoint = this.getEndPoint(target); if (targetpoint == null) { CraftIRC.dolog("The requested target tag '" + target + "' isn't registered."); } } else { return null; } } return new RelayedMessage(this, source, targetpoint, eventType); } public RelayedCommand newCmd(EndPoint source, String command) { if (source == null) { return null; } final CommandEndPoint target = this.irccmds.get(command); if (target == null) { return null; } if (!this.cPathExists(this.getTag(source), this.getTag(target))) { return null; } final RelayedCommand cmd = new RelayedCommand(this, source, target); cmd.setField("command", command); return cmd; } public boolean registerEndPoint(String tag, EndPoint ep) { if (this.isDebug()) { CraftIRC.dolog("Registering endpoint: " + tag); } if (tag == null) { CraftIRC.dolog("Failed to register endpoint - No tag!"); } if ((this.endpoints.get(tag) != null) || (this.tags.get(ep) != null)) { CraftIRC.dolog("Couldn't register an endpoint tagged '" + tag + "' because either the tag or the endpoint already exist."); return false; } if (tag == "*") { CraftIRC.dolog("Couldn't register an endpoint - the character * can't be used as a tag."); return false; } this.endpoints.put(tag, ep); this.tags.put(ep, tag); return true; } public boolean endPointRegistered(String tag) { return this.endpoints.get(tag) != null; } public EndPoint getEndPoint(String tag) { return this.endpoints.get(tag); } public String getTag(EndPoint ep) { return this.tags.get(ep); } public boolean registerCommand(String tag, String command) { if (this.isDebug()) { CraftIRC.dolog("Registering command: " + command + " to endpoint:" + tag); } final EndPoint ep = this.getEndPoint(tag); if (ep == null) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because there is no such tag."); return false; } if (!(ep instanceof CommandEndPoint)) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because it's not capable of handling commands."); return false; } if (this.irccmds.containsKey(command)) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because that command is already registered."); return false; } this.irccmds.put(command, (CommandEndPoint) ep); return true; } public boolean unregisterCommand(String command) { if (!this.irccmds.containsKey(command)) { return false; } this.irccmds.remove(command); return true; } public boolean unregisterEndPoint(String tag) { final EndPoint ep = this.getEndPoint(tag); if (ep == null) { return false; } this.endpoints.remove(tag); this.tags.remove(ep); this.ungroupTag(tag); if (ep instanceof CommandEndPoint) { final CommandEndPoint cep = (CommandEndPoint) ep; for (final String cmd : this.irccmds.keySet()) { if (this.irccmds.get(cmd) == cep) { this.irccmds.remove(cmd); } } } return true; } public boolean groupTag(String tag, String group) { if (this.getEndPoint(tag) == null) { return false; } List<String> tags = this.taggroups.get(group); if (tags == null) { tags = new ArrayList<String>(); this.taggroups.put(group, tags); } tags.add(tag); return true; } public void ungroupTag(String tag) { for (final String group : this.taggroups.keySet()) { this.taggroups.get(group).remove(tag); } } public void clearGroup(String group) { this.taggroups.remove(group); } public boolean checkTagsGrouped(String tagA, String tagB) { for (final String group : this.taggroups.keySet()) { if (this.taggroups.get(group).contains(tagA) && this.taggroups.get(group).contains(tagB)) { return true; } } return false; } boolean delivery(RelayedMessage msg) { return this.delivery(msg, null, null, RelayedMessage.DeliveryMethod.STANDARD); } boolean delivery(RelayedMessage msg, List<EndPoint> destinations) { return this.delivery(msg, destinations, null, RelayedMessage.DeliveryMethod.STANDARD); } boolean delivery(RelayedMessage msg, List<EndPoint> knownDestinations, String username) { return this.delivery(msg, knownDestinations, username, RelayedMessage.DeliveryMethod.STANDARD); } boolean delivery(RelayedMessage msg, List<EndPoint> knownDestinations, String username, RelayedMessage.DeliveryMethod dm) { final String sourceTag = this.getTag(msg.getSource()); msg.setField("source", sourceTag); List<EndPoint> destinations; if (this.isDebug()) { CraftIRC.dolog("X->" + (knownDestinations.size() > 0 ? knownDestinations.toString() : "*") + ": " + msg.toString()); } if (knownDestinations.size() < 1) { destinations = new LinkedList<EndPoint>(); for (final String targetTag : this.cPathsFrom(sourceTag)) { final EndPoint ep = this.getEndPoint(targetTag); if (ep == null) { continue; } if ((ep instanceof SecuredEndPoint) && SecuredEndPoint.Security.REQUIRE_TARGET.equals(((SecuredEndPoint) ep).getSecurity())) { continue; } if (!this.cPathAttribute(sourceTag, targetTag, "attributes." + msg.getEvent())) { continue; } if ((dm == RelayedMessage.DeliveryMethod.ADMINS) && !this.cPathAttribute(sourceTag, targetTag, "attributes.admin")) { continue; } destinations.add(ep); } if (this.cAutoPaths()) { for (final EndPoint ep : this.endpoints.values()) { if (ep == null) { continue; } if (msg.getSource().equals(ep) || destinations.contains(ep)) { continue; } if ((ep instanceof SecuredEndPoint) && !SecuredEndPoint.Security.UNSECURED.equals(((SecuredEndPoint) ep).getSecurity())) { continue; } final String targetTag = this.getTag(ep); if (this.checkTagsGrouped(sourceTag, targetTag)) { continue; } if (!this.cPathAttribute(sourceTag, targetTag, "attributes." + msg.getEvent())) { continue; } if ((dm == RelayedMessage.DeliveryMethod.ADMINS) && !this.cPathAttribute(sourceTag, targetTag, "attributes.admin")) { continue; } if (this.cPathAttribute(sourceTag, targetTag, "disabled")) { continue; } destinations.add(ep); } } } else { destinations = new LinkedList<EndPoint>(knownDestinations); } if (destinations.size() < 1) { return false; } boolean success = true; for (final EndPoint destination : destinations) { final String targetTag = this.getTag(destination); if(targetTag.equals(this.cCancelledTag())){ continue; } msg.setField("target", targetTag); if ((msg instanceof RelayedCommand) && this.matchesFilter(msg, this.cPathFilters(sourceTag, targetTag))) { if (knownDestinations != null) { success = false; } continue; } if (this.isDebug()) { CraftIRC.dolog("-->X: " + msg.toString()); } if (username != null) { success = success && destination.userMessageIn(username, msg); } else if (dm == RelayedMessage.DeliveryMethod.ADMINS) { success = destination.adminMessageIn(msg); } else if (dm == RelayedMessage.DeliveryMethod.COMMAND) { if (!(destination instanceof CommandEndPoint)) { continue; } ((CommandEndPoint) destination).commandIn((RelayedCommand) msg); } else { destination.messageIn(msg); } } return success; } boolean matchesFilter(RelayedMessage msg, List<ConfigurationNode> filters) { if (filters == null) { return false; } newFilter: for (final ConfigurationNode filter : filters) { for (final String key : filter.getKeys()) { final Pattern condition = Pattern.compile(filter.getString(key, "")); if (condition == null) { continue newFilter; } final String subject = msg.getField(key); if (subject == null) { continue newFilter; } final Matcher check = condition.matcher(subject); if (!check.find()) { continue newFilter; } } return true; } return false; } public Minebot getBot(int bot){ return this.instances.get(bot); } public void sendRawToBot(String rawMessage, int bot) { if (this.isDebug()) { CraftIRC.dolog("sendRawToBot(bot=" + bot + ", message=" + rawMessage); } final Minebot targetBot = this.instances.get(bot); targetBot.sendRawLineViaQueue(rawMessage); } public void sendMsgToTargetViaBot(String message, String target, int bot) { final Minebot targetBot = this.instances.get(bot); targetBot.sendMessage(target, message); } public List<String> ircUserLists(String tag) { return this.getEndPoint(tag).listDisplayUsers(); } void setDebug(boolean d) { this.debug = d; for (int i = 0; i < this.bots.size(); i++) { this.instances.get(i).setVerbose(d); } CraftIRC.dolog("DEBUG [" + (d ? "ON" : "OFF") + "]"); } public String getPrefix(Player p) { String result = ""; if (this.vault != null) { try { result = this.vault.getPlayerPrefix(p); } catch (final Exception e) { } } return result; } public String getSuffix(Player p) { String result = ""; if (this.vault != null) { try { result = this.vault.getPlayerSuffix(p); } catch (final Exception e) { } } return result; } public boolean isDebug() { return this.debug; } boolean checkPerms(Player pl, String path) { return pl.hasPermission(path); } boolean checkPerms(String pl, String path) { final Player pit = this.getServer().getPlayer(pl); if (pit != null) { return pit.hasPermission(path); } return false; } public String colorizeName(String name) { final Pattern color_codes = Pattern.compile(ChatColor.COLOR_CHAR + "[0-9a-fk-r]"); Matcher find_colors = color_codes.matcher(name); while (find_colors.find()) { name = find_colors.replaceFirst(Character.toString((char) 3) + this.cColorIrcFromGame(find_colors.group())); find_colors = color_codes.matcher(name); } return name; } protected void enqueueConsoleCommand(String cmd) { try { this.getServer().dispatchCommand(this.getServer().getConsoleSender(), cmd); } catch (final Exception e) { e.printStackTrace(); } } void scheduleForRetry(Minebot bot, String channel) { this.retryTimer.schedule(new RetryTask(this, bot, channel), this.cRetryDelay()); } private ConfigurationNode getChanNode(int bot, String channel) { final ArrayList<ConfigurationNode> botChans = this.channodes.get(bot); for (final ConfigurationNode chan : botChans) { if (chan.getString("name").equalsIgnoreCase(channel)) { return chan; } } return Configuration.getEmptyNode(); } public List<ConfigurationNode> cChannels(int bot) { return this.channodes.get(bot); } private ConfigurationNode getPathNode(String source, String target) { ConfigurationNode result = this.paths.get(new Path(source, target)); if (result == null) { return this.configuration.getNode("default-attributes"); } ConfigurationNode basepath; if (result.getKeys().contains("base") && ((basepath = result.getNode("base")) != null)) { final ConfigurationNode basenode = this.paths.get(new Path(basepath.getString("source", ""), basepath.getString("target", ""))); if (basenode != null) { result = basenode; } } return result; } public String cMinecraftTag() { return this.configuration.getString("settings.minecraft-tag", "minecraft"); } public String cCancelledTag() { return this.configuration.getString("settings.cancelled-tag", "cancelled"); } public String cConsoleTag() { return this.configuration.getString("settings.console-tag", "console"); } public String cMinecraftTagGroup() { return this.configuration.getString("settings.minecraft-group-name", "minecraft"); } public String cIrcTagGroup() { return this.configuration.getString("settings.irc-group-name", "irc"); } public boolean cAutoPaths() { return this.configuration.getBoolean("settings.auto-paths", false); } public boolean cCancelChat() { return cancelChat; } public boolean cDebug() { return this.configuration.getBoolean("settings.debug", false); } public ArrayList<String> cConsoleCommands() { return new ArrayList<String>(this.configuration.getStringList("settings.console-commands", null)); } public int cHold(String eventType) { return this.configuration.getInt("settings.hold-after-enable." + eventType, 0); } public String cFormatting(String eventType, RelayedMessage msg) { return this.cFormatting(eventType, msg, null); } public String cFormatting(String eventType, RelayedMessage msg, EndPoint realTarget) { final String source = this.getTag(msg.getSource()), target = this.getTag(realTarget != null ? realTarget : msg.getTarget()); if ((source == null) || (target == null)) { CraftIRC.dowarn("Attempted to obtain formatting for invalid path " + source + " -> " + target + " ."); return this.cDefaultFormatting(eventType, msg); } final ConfigurationNode pathConfig = this.paths.get(new Path(source, target)); if ((pathConfig != null) && (pathConfig.getString("formatting." + eventType, null) != null)) { return pathConfig.getString("formatting." + eventType, null); } else { return this.cDefaultFormatting(eventType, msg); } } public String cDefaultFormatting(String eventType, RelayedMessage msg) { if (msg.getSource().getType() == EndPoint.Type.MINECRAFT) { return this.configuration.getString("settings.formatting.from-game." + eventType); } if (msg.getSource().getType() == EndPoint.Type.IRC) { return this.configuration.getString("settings.formatting.from-irc." + eventType); } if (msg.getSource().getType() == EndPoint.Type.PLAIN) { return this.configuration.getString("settings.formatting.from-plain." + eventType); } return ""; } public String cColorIrcFromGame(String game) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("game").equals(game)) { return (color.getString("irc").length() == 1 ? "0" : "") + color.getString("irc", this.cColorIrcFromName("foreground")); } } return this.cColorIrcFromName("foreground"); } public String cColorIrcFromName(String name) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("name").equalsIgnoreCase(name) && (color.getProperty("irc") != null)) { return color.getString("irc", "01"); } } if (name.equalsIgnoreCase("foreground")) { return "01"; } else { return this.cColorIrcFromName("foreground"); } } public String cColorGameFromIrc(String irc) { if (irc.length() == 1) irc = "0"+irc; ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("irc", "").equals(irc) || "0".concat(color.getString("irc", "")).equals(irc)) { return color.getString("game", this.cColorGameFromName("foreground")); } } return this.cColorGameFromName("foreground"); } public String cColorGameFromName(String name) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("name").equalsIgnoreCase(name) && (color.getProperty("game") != null)) { return color.getString("game", "\u00C2\u00A7f"); } } if (name.equalsIgnoreCase("foreground")) { return "\u00C2\u00A7f"; } else { return this.cColorGameFromName("foreground"); } } public String cBindLocalAddr() { return this.configuration.getString("settings.bind-address", ""); } public int cRetryDelay() { return this.configuration.getInt("settings.retry-delay", 10) * 1000; } public String cBotNickname(int bot) { return this.bots.get(bot).getString("nickname", "CraftIRCbot"); } public String cBotServer(int bot) { return this.bots.get(bot).getString("server", "irc.esper.net"); } public int cBotPort(int bot) { return this.bots.get(bot).getInt("port", 6667); } public int cBotBindPort(int bot) { return this.bots.get(bot).getInt("bind-port", 0); } public String cBotLogin(int bot) { return this.bots.get(bot).getString("userident", ""); } public String cBotPassword(int bot) { return this.bots.get(bot).getString("serverpass", ""); } public boolean cBotSsl(int bot) { return this.bots.get(bot).getBoolean("ssl", false); } public int cBotMessageDelay(int bot) { return this.bots.get(bot).getInt("message-delay", 1000); } public int cBotQueueSize(int bot) { return this.bots.get(bot).getInt("queue-size", 5); } public String cCommandPrefix(int bot) { return this.bots.get(bot).getString("command-prefix", this.configuration.getString("settings.command-prefix", ".")); } public List<String> cCmdWordCmd(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("cmd"); final List<String> result = this.configuration.getStringList("settings.irc-commands.cmd", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.cmd", result); } return result; } public List<String> cCmdWordSay(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("say"); final List<String> result = this.configuration.getStringList("settings.irc-commands.say", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.say", result); } return result; } public List<String> cCmdWordPlayers(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("players"); final List<String> result = this.configuration.getStringList("settings.irc-commands.players", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.players", result); } return result; } public ArrayList<String> cBotAdminPrefixes(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("admin-prefixes", null)); } public ArrayList<String> cBotIgnoredUsers(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("ignored-users", null)); } public String cBotAuthMethod(int bot) { return this.bots.get(bot).getString("auth.method", "nickserv"); } public String cBotAuthUsername(int bot) { return this.bots.get(bot).getString("auth.username", ""); } public String cBotAuthPassword(int bot) { return this.bots.get(bot).getString("auth.password", ""); } public ArrayList<String> cBotOnConnect(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("on-connect", null)); } public String cChanName(int bot, String channel) { return this.getChanNode(bot, channel).getString("name", "#changeme"); } public String cChanTag(int bot, String channel) { return this.getChanNode(bot, channel).getString("tag", String.valueOf(bot) + "_" + channel); } public String cChanPassword(int bot, String channel) { return this.getChanNode(bot, channel).getString("password", ""); } public ArrayList<String> cChanOnJoin(int bot, String channel) { return new ArrayList<String>(this.getChanNode(bot, channel).getStringList("on-join", null)); } public List<String> cPathsFrom(String source) { final List<String> results = new LinkedList<String>(); for (final Path path : this.paths.keySet()) { if (!path.getSourceTag().equals(source)) { continue; } if (this.paths.get(path).getBoolean("disable", false)) { continue; } results.add(path.getTargetTag()); } return results; } List<String> cPathsTo(String target) { final List<String> results = new LinkedList<String>(); for (final Path path : this.paths.keySet()) { if (!path.getTargetTag().equals(target)) { continue; } if (this.paths.get(path).getBoolean("disable", false)) { continue; } results.add(path.getSourceTag()); } return results; } public boolean cPathExists(String source, String target) { final ConfigurationNode pathNode = this.getPathNode(source, target); return (pathNode != null) && !pathNode.getBoolean("disabled", false); } public boolean cPathAttribute(String source, String target, String attribute) { final ConfigurationNode node = this.getPathNode(source, target); if (node.getProperty(attribute) != null) { return node.getBoolean(attribute, false); } else { return this.configuration.getNode("default-attributes").getBoolean(attribute, false); } } public List<ConfigurationNode> cPathFilters(String source, String target) { return this.getPathNode(source, target).getNodeList("filters", new ArrayList<ConfigurationNode>()); } public Map<String, Map<String, String>> cReplaceFilters() { return this.replaceFilters; } void loadTagGroups() { final List<String> groups = this.configuration.getKeys("settings.tag-groups"); if (groups == null) { return; } for (final String group : groups) { for (final String tag : this.configuration.getStringList("settings.tag-groups." + group, new ArrayList<String>())) { this.groupTag(tag, group); } } } boolean cUseMapAsWhitelist(int bot) { return this.bots.get(bot).getBoolean("use-map-as-whitelist", false); } public String cIrcDisplayName(int bot, String nickname) { return this.bots.get(bot).getString("irc-nickname-map." + nickname, nickname); } public boolean cNicknameIsInIrcMap(int bot, String nickname) { return this.bots.get(bot).getString("irc-nickname-map." + nickname) != null; } public enum HoldType { CHAT, JOINS, QUITS, KICKS, BANS, DEATHS } class RemoveHoldTask extends TimerTask { private final CraftIRC plugin; private final HoldType ht; protected RemoveHoldTask(CraftIRC plugin, HoldType ht) { super(); this.plugin = plugin; this.ht = ht; } @Override public void run() { this.plugin.hold.put(this.ht, false); } } public boolean isHeld(HoldType ht) { return this.hold.get(ht); } public List<ConfigurationNode> getColorMap() { return this.colormap; } public String processAntiHighlight(String input) { String delimiter = this.configuration.getString("settings.anti-highlight"); if (delimiter != null && !delimiter.isEmpty()) { StringBuilder builder = new StringBuilder(); for (int i=0; i < input.length(); i++) { char c = input.charAt(i); builder.append(c); if (c != '\u00A7') { builder.append(delimiter); } } return builder.toString(); } else { return input; } } }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("changeFlushMode".equals(method.getName()) && method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(FlushModeType.class)) { changeFushMode((FlushModeType) args[0]); return null; } if ("getBeanType".equals(method.getName()) && method.getParameterTypes().length == 0) { return EntityManager.class; } if ("getQualifiers".equals(method.getName()) && method.getParameterTypes().length == 0) { return Collections.unmodifiableSet(qualifiers); } if ("getPersistenceProvider".equals(method.getName()) && method.getParameterTypes().length == 0) { return provider; } if ("closeAfterTransaction".equals(method.getName()) && method.getParameterTypes().length == 0) { closeAfterTransaction(); return null; } if (!"setFlushMode".equals(method.getName())) { if (!synchronizationRegistered) { joinTransaction(); } } touch((ManagedPersistenceContext) proxy); return super.invoke(proxy, method, args); }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("changeFlushMode".equals(method.getName()) && method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(FlushModeType.class)) { changeFushMode((FlushModeType) args[0]); return null; } if ("getBeanType".equals(method.getName()) && method.getParameterTypes().length == 0) { return EntityManager.class; } if ("getQualifiers".equals(method.getName()) && method.getParameterTypes().length == 0) { return Collections.unmodifiableSet(qualifiers); } if ("getPersistenceProvider".equals(method.getName()) && method.getParameterTypes().length == 0) { return provider; } if ("closeAfterTransaction".equals(method.getName()) && method.getParameterTypes().length == 0) { closeAfterTransaction(); return null; } if ("getTransaction".equals(method.getName()) && method.getParameterTypes().length == 0) { return super.invoke(proxy, method, args); } if (!"setFlushMode".equals(method.getName())) { if (!synchronizationRegistered) { joinTransaction(); } } touch((ManagedPersistenceContext) proxy); return super.invoke(proxy, method, args); }
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { String password = null; if(authentication!=null) password = (String) authentication.getCredentials(); Hashtable props = new Hashtable(); String principalName = username + '@' + domainName; props.put(Context.SECURITY_PRINCIPAL, principalName); props.put(Context.SECURITY_CREDENTIALS,password); DirContext context; try { context = LdapCtxFactory.getLdapCtxInstance( "ldap://" + DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName) + '/', props); } catch (NamingException e) { LOGGER.log(Level.WARNING,"Failed to bind to LDAP",e); throw new BadCredentialsException("Either no such user '"+username+"' or incorrect password",e); } try { SearchControls controls = new SearchControls(); controls.setSearchScope(SUBTREE_SCOPE); NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls); if(!renum.hasMore()) throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username); SearchResult result = renum.next(); List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>(); Attribute memberOf = result.getAttributes().get("memberOf"); if(memberOf!=null) { for(int i=0; i<memberOf.size(); i++) { Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[]{"CN"}); Attribute att = atts.get("CN"); groups.add(new GrantedAuthorityImpl(att.get().toString())); } } context.close(); return new ActiveDirectoryUserDetail( username, password, true, true, true, true, groups.toArray(new GrantedAuthority[groups.size()]) ); } catch (NamingException e) { LOGGER.log(Level.WARNING,"Failed to retrieve user information",e); throw new BadCredentialsException("Authentication was successful but more than one users in the directory matches the user name: "+username,e); } }
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { String password = null; if(authentication!=null) password = (String) authentication.getCredentials(); Hashtable props = new Hashtable(); String principalName = username + '@' + domainName; props.put(Context.SECURITY_PRINCIPAL, principalName); props.put(Context.SECURITY_CREDENTIALS,password); DirContext context; try { context = LdapCtxFactory.getLdapCtxInstance( "ldap://" + DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName) + '/', props); } catch (NamingException e) { LOGGER.log(Level.WARNING,"Failed to bind to LDAP",e); throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password",e); } try { SearchControls controls = new SearchControls(); controls.setSearchScope(SUBTREE_SCOPE); NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls); if(!renum.hasMore()) throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username); SearchResult result = renum.next(); List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>(); Attribute memberOf = result.getAttributes().get("memberOf"); if(memberOf!=null) { for(int i=0; i<memberOf.size(); i++) { Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[]{"CN"}); Attribute att = atts.get("CN"); groups.add(new GrantedAuthorityImpl(att.get().toString())); } } context.close(); return new ActiveDirectoryUserDetail( username, password, true, true, true, true, groups.toArray(new GrantedAuthority[groups.size()]) ); } catch (NamingException e) { LOGGER.log(Level.WARNING,"Failed to retrieve user information",e); throw new BadCredentialsException("Authentication was successful but more than one users in the directory matches the user name: "+username,e); } }
public void storeMatchDetails(Matchdetails details) { if (details != null) { final String[] where = { "MatchID" }; final String[] werte = { "" + details.getMatchID()}; delete(where, werte); String sql = null; try { sql = "INSERT INTO "+getTableName()+" ( MatchID, ArenaId, ArenaName, Fetchdatum, GastId, GastName, GastEinstellung, GastTore, " + "GastLeftAtt, GastLeftDef, GastMidAtt, GastMidDef, GastMidfield, GastRightAtt, GastRightDef, GastTacticSkill, GastTacticType, " + "HeimId, HeimName, HeimEinstellung, HeimTore, HeimLeftAtt, HeimLeftDef, HeimMidAtt, HeimMidDef, HeimMidfield, HeimRightAtt, HeimRightDef, " + "HeimTacticSkill, HeimTacticType, SpielDatum, WetterId, Zuschauer, " + "Matchreport, RegionID, soldTerraces, soldBasic, soldRoof, soldVIP" + ") VALUES (" + details.getMatchID() + ", " + details.getArenaID() + ", '" + DBZugriff.insertEscapeSequences(details.getArenaName()) + "', '" + details.getFetchDatum().toString() + "', " + details.getGastId() + ", '" + DBZugriff.insertEscapeSequences(details.getGastName()) + "', " + details.getGuestEinstellung() + ", " + details.getGuestGoals() + ", " + details.getGuestLeftAtt() + ", " + details.getGuestLeftDef() + ", " + details.getGuestMidAtt() + ", " + details.getGuestMidDef() + ", " + details.getGuestMidfield() + ", " + details.getGuestRightAtt() + ", " + details.getGuestRightDef() + ", " + details.getGuestTacticSkill() + ", " + details.getGuestTacticType() + ", " + details.getHeimId() + ", '" + DBZugriff.insertEscapeSequences(details.getHeimName()) + "', " + details.getHomeEinstellung() + ", " + details.getHomeGoals() + ", " + details.getHomeLeftAtt() + ", " + details.getHomeLeftDef() + ", " + details.getHomeMidAtt() + ", " + details.getHomeMidDef() + ", " + details.getHomeMidfield() + ", " + details.getHomeRightAtt() + ", " + details.getHomeRightDef() + ", " + details.getHomeTacticSkill() + ", " + details.getHomeTacticType() + ", '" + details.getSpielDatum().toString() + "', " + details.getWetterId() + ", " + details.getZuschauer() + ", '" + DBZugriff.insertEscapeSequences(details.getMatchreport()) + "', " + details.getRegionId() + "', " + details.getSoldTerraces() + "', " + details.getSoldBasic() + "', " + details.getSoldRoof() + "', " + details.getSoldVIP() + ")"; adapter.executeUpdate(sql); DBZugriff.instance().storeMatchHighlights(details); if (details.getZuschauer() > 0) { sql = "UPDATE MATCHESKURZINFO SET Status=1, HeimTore=" + details.getHomeGoals() + " , GastTore=" + details.getGuestGoals() + " WHERE MatchID=" + details.getMatchID(); adapter.executeUpdate(sql); } } catch (Exception e) { HOLogger.instance().log(getClass(),"DB.storeMatchDetails Error" + e); HOLogger.instance().log(getClass(),e); } } }
public void storeMatchDetails(Matchdetails details) { if (details != null) { final String[] where = { "MatchID" }; final String[] werte = { "" + details.getMatchID()}; delete(where, werte); String sql = null; try { sql = "INSERT INTO "+getTableName()+" ( MatchID, ArenaId, ArenaName, Fetchdatum, GastId, GastName, GastEinstellung, GastTore, " + "GastLeftAtt, GastLeftDef, GastMidAtt, GastMidDef, GastMidfield, GastRightAtt, GastRightDef, GastTacticSkill, GastTacticType, " + "HeimId, HeimName, HeimEinstellung, HeimTore, HeimLeftAtt, HeimLeftDef, HeimMidAtt, HeimMidDef, HeimMidfield, HeimRightAtt, HeimRightDef, " + "HeimTacticSkill, HeimTacticType, SpielDatum, WetterId, Zuschauer, " + "Matchreport, RegionID, soldTerraces, soldBasic, soldRoof, soldVIP" + ") VALUES (" + details.getMatchID() + ", " + details.getArenaID() + ", '" + DBZugriff.insertEscapeSequences(details.getArenaName()) + "', '" + details.getFetchDatum().toString() + "', " + details.getGastId() + ", '" + DBZugriff.insertEscapeSequences(details.getGastName()) + "', " + details.getGuestEinstellung() + ", " + details.getGuestGoals() + ", " + details.getGuestLeftAtt() + ", " + details.getGuestLeftDef() + ", " + details.getGuestMidAtt() + ", " + details.getGuestMidDef() + ", " + details.getGuestMidfield() + ", " + details.getGuestRightAtt() + ", " + details.getGuestRightDef() + ", " + details.getGuestTacticSkill() + ", " + details.getGuestTacticType() + ", " + details.getHeimId() + ", '" + DBZugriff.insertEscapeSequences(details.getHeimName()) + "', " + details.getHomeEinstellung() + ", " + details.getHomeGoals() + ", " + details.getHomeLeftAtt() + ", " + details.getHomeLeftDef() + ", " + details.getHomeMidAtt() + ", " + details.getHomeMidDef() + ", " + details.getHomeMidfield() + ", " + details.getHomeRightAtt() + ", " + details.getHomeRightDef() + ", " + details.getHomeTacticSkill() + ", " + details.getHomeTacticType() + ", '" + details.getSpielDatum().toString() + "', " + details.getWetterId() + ", " + details.getZuschauer() + ", '" + DBZugriff.insertEscapeSequences(details.getMatchreport()) + "', " + details.getRegionId() + ", " + details.getSoldTerraces() + ", " + details.getSoldBasic() + ", " + details.getSoldRoof() + ", " + details.getSoldVIP() + ")"; adapter.executeUpdate(sql); DBZugriff.instance().storeMatchHighlights(details); if (details.getZuschauer() > 0) { sql = "UPDATE MATCHESKURZINFO SET Status=1, HeimTore=" + details.getHomeGoals() + " , GastTore=" + details.getGuestGoals() + " WHERE MatchID=" + details.getMatchID(); adapter.executeUpdate(sql); } } catch (Exception e) { HOLogger.instance().log(getClass(),"DB.storeMatchDetails Error" + e); HOLogger.instance().log(getClass(),e); } } }
static String[] processCommandLine(String[] args) { if (args == null) return args; if (args.length == 0) return args; allArgs = args; int[] configArgs = new int[args.length]; configArgs[0] = -1; int configArgIndex = 0; for (int i = 0; i < args.length; i++) { boolean found = false; if (args[i].equalsIgnoreCase(CLASSLOADER_PROPERTIES)) found = true; if (args[i].equalsIgnoreCase(NO_PACKAGE_PREFIXES)) found = true; if (args[i].equalsIgnoreCase(PLUGINS)) found = true; if (args[i].equalsIgnoreCase(FIRST_USE)) found = true; if (args[i].equalsIgnoreCase(NO_UPDATE)) found = true; if (args[i].equalsIgnoreCase(NEW_UPDATES)) found = true; if (args[i].equalsIgnoreCase(UPDATE)) found = true; if (args[i].equalsIgnoreCase(BOOT)) found = true; if (args[i].equalsIgnoreCase(KEYRING)) found = true; if (args[i].equalsIgnoreCase(PASSWORD)) found = true; if (found) { configArgs[configArgIndex++] = i; if (i < args.length && !args[i + 1].startsWith("-")) configArgs[configArgIndex++] = ++i; continue; } if (i == args.length - 1 || args[i + 1].startsWith("-")) continue; String arg = args[++i]; if (args[i - 1].equalsIgnoreCase(PRODUCT) || args[i - 1].equalsIgnoreCase(FEATURE)) { product = arg; found = true; } if (args[i - 1].equalsIgnoreCase(APPLICATION)) { application = arg; found = true; } if (found) { configArgs[configArgIndex++] = i - 1; configArgs[configArgIndex++] = i; } } if (configArgIndex == 0) { appArgs = args; return args; } appArgs = new String[args.length - configArgIndex]; configArgIndex = 0; int j = 0; for (int i = 0; i < args.length; i++) { if (i == configArgs[configArgIndex]) configArgIndex++; else appArgs[j++] = args[i]; } return appArgs; }
static String[] processCommandLine(String[] args) { if (args == null) return args; if (args.length == 0) return args; allArgs = args; int[] configArgs = new int[args.length]; configArgs[0] = -1; int configArgIndex = 0; for (int i = 0; i < args.length; i++) { boolean found = false; if (args[i].equalsIgnoreCase(CLASSLOADER_PROPERTIES)) found = true; if (args[i].equalsIgnoreCase(NO_PACKAGE_PREFIXES)) found = true; if (args[i].equalsIgnoreCase(PLUGINS)) found = true; if (args[i].equalsIgnoreCase(FIRST_USE)) found = true; if (args[i].equalsIgnoreCase(NO_UPDATE)) found = true; if (args[i].equalsIgnoreCase(NEW_UPDATES)) found = true; if (args[i].equalsIgnoreCase(UPDATE)) found = true; if (args[i].equalsIgnoreCase(BOOT)) found = true; if (args[i].equalsIgnoreCase(KEYRING)) found = true; if (args[i].equalsIgnoreCase(PASSWORD)) found = true; if (found) { configArgs[configArgIndex++] = i; if (i < (args.length -1) && !args[i + 1].startsWith("-")) configArgs[configArgIndex++] = ++i; continue; } if (i == args.length - 1 || args[i + 1].startsWith("-")) continue; String arg = args[++i]; if (args[i - 1].equalsIgnoreCase(PRODUCT) || args[i - 1].equalsIgnoreCase(FEATURE)) { product = arg; found = true; } if (args[i - 1].equalsIgnoreCase(APPLICATION)) { application = arg; found = true; } if (found) { configArgs[configArgIndex++] = i - 1; configArgs[configArgIndex++] = i; } } if (configArgIndex == 0) { appArgs = args; return args; } appArgs = new String[args.length - configArgIndex]; configArgIndex = 0; int j = 0; for (int i = 0; i < args.length; i++) { if (i == configArgs[configArgIndex]) configArgIndex++; else appArgs[j++] = args[i]; } return appArgs; }
public Dialog onCreateDialog(Bundle savedInstanceState) { final ContentResolver resolver = getActivity().getContentResolver(); final OnClickListener okListener = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final ProgressDialog progressDialog = ProgressDialog.show(getActivity(), getString(R.string.clearCallLogProgress_title), "", true, false); final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { resolver.delete(Calls.CONTENT_URI_WITH_VOICEMAIL, null, null); return null; } @Override protected void onPostExecute(Void result) { progressDialog.dismiss(); } }; progressDialog.show(); task.execute(); } }; return new AlertDialog.Builder(getActivity()) .setTitle(R.string.clearCallLogConfirmation_title) .setIconAttribute(android.R.attr.alertDialogIcon) .setMessage(R.string.clearCallLogConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, okListener) .setCancelable(true) .create(); }
public Dialog onCreateDialog(Bundle savedInstanceState) { final ContentResolver resolver = getActivity().getContentResolver(); final OnClickListener okListener = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final ProgressDialog progressDialog = ProgressDialog.show(getActivity(), getString(R.string.clearCallLogProgress_title), "", true, false); final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { resolver.delete(Calls.CONTENT_URI, null, null); return null; } @Override protected void onPostExecute(Void result) { progressDialog.dismiss(); } }; progressDialog.show(); task.execute(); } }; return new AlertDialog.Builder(getActivity()) .setTitle(R.string.clearCallLogConfirmation_title) .setIconAttribute(android.R.attr.alertDialogIcon) .setMessage(R.string.clearCallLogConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, okListener) .setCancelable(true) .create(); }
public static void main(String[] args) { if (args.length != 12) { help(); } try { etType = args[0]; problem = ArgParser.problem(args[1]); sizes = ArgParser.intList(args[2]); dataSetSizes = ArgParser.intList(args[3]); trainingErrors = ArgParser.doubleList(args[4]); nFolds = ArgParser.intSingle(args[5]); dataLoader = problem.getDataLoader(activationThreshold,nFolds); } catch (helpers.ProblemDescriptionLoader.BadArgument e) { System.err.println("Could not create dataLoader - perhaps the mapper_type property is wrong"); e.printStackTrace(); } catch (BadArgument e) { help(); } try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.err.println("Could not find SQLite JDBC driver!"); } try { Properties prop = new Properties(); prop.load(new FileInputStream("config.properties")); String dbhost = prop.getProperty("dbhost"); String dbuser = prop.getProperty("dbuser"); String dbpass = prop.getProperty("dbpass"); String dbport = prop.getProperty("dbport"); String dbname = prop.getProperty("dbname"); String dbconn = "jdbc:mysql://" + dbhost + ":" + dbport + "/" + dbname; sqlConnection = DriverManager.getConnection(dbconn, dbuser, dbpass); loop(); } catch(SQLException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(sqlConnection != null) sqlConnection.close(); } catch(SQLException e) { System.err.println(e); } } System.exit(0); }
public static void main(String[] args) { if (args.length != 12) { help(); } try { etType = args[0]; problem = ArgParser.problem(args[1]); sizes = ArgParser.intList(args[2]); dataSetSizes = ArgParser.intList(args[3]); trainingErrors = ArgParser.doubleList(args[4]); nFolds = ArgParser.intSingle(args[5]); dataLoader = problem.getDataLoader(activationThreshold,nFolds); } catch (helpers.ProblemDescriptionLoader.BadArgument e) { System.err.println("Could not create dataLoader - perhaps the mapper_type property is wrong"); e.printStackTrace(); } catch (BadArgument e) { help(); } try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.err.println("Could not find MySQL JDBC driver!"); } try { Properties prop = new Properties(); prop.load(new FileInputStream("config.properties")); String dbhost = prop.getProperty("dbhost"); String dbuser = prop.getProperty("dbuser"); String dbpass = prop.getProperty("dbpass"); String dbport = prop.getProperty("dbport"); String dbname = prop.getProperty("dbname"); String dbconn = "jdbc:mysql://" + dbhost + ":" + dbport + "/" + dbname; sqlConnection = DriverManager.getConnection(dbconn, dbuser, dbpass); loop(); } catch(SQLException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(sqlConnection != null) sqlConnection.close(); } catch(SQLException e) { System.err.println(e); } } System.exit(0); }
public View getView(int position, View v, ViewGroup parent) { BuzzingViewHolder viewHolder; if (getItemViewType(position) == BuzzingType.PULL.ordinal()) { if (v == null) { LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = li.inflate(R.layout.buzzing_item_pull, parent, false); } } else { if (v == null) { LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = li.inflate(mResourceLayoutId, parent, false); viewHolder = new BuzzingViewHolder(); viewHolder.itemName = (TextView) v.findViewById(R.id.buzzingName); viewHolder.itemPoster = (ImageButton) v.findViewById(R.id.buzzingPoster); setButtonOnClickListener(viewHolder.itemPoster); viewHolder.itemTweetsToday = (TextView) v.findViewById(R.id.buzzingToday); viewHolder.itemTweetsTotal = (TextView) v.findViewById(R.id.buzzingTotal); viewHolder.popupMenuButton = (ImageButton) v.findViewById(R.id.buzzing_popup_menu); if (viewHolder.popupMenuButton != null) { viewHolder.popupMenuButton = (ImageButton) v.findViewById(R.id.buzzing_popup_menu); setButtonOnClickListener(viewHolder.popupMenuButton); } v.setTag(viewHolder); } else { viewHolder = (BuzzingViewHolder) v.getTag(); } if (viewHolder.itemName != null) viewHolder.itemName.setText(mBuzzingModel.getBuzzing().get(position).getName()); if (viewHolder.itemTweetsToday != null) viewHolder.itemTweetsToday.setText(v.getContext().getString(R.string.tweets_today, (int) mBuzzingModel.getBuzzing().get(position).getTweetsToday())); if (viewHolder.itemTweetsTotal != null) viewHolder.itemTweetsTotal.setText(v.getContext().getString(R.string.tweets_total, (int) mBuzzingModel.getBuzzing().get(position).getTweets())); if (viewHolder.itemPoster != null) { String imageUrl = "" + v.getContext().getString(R.string.base_url) + mBuzzingModel.getBuzzing().get(position).getPosterUrl(); Picasso.with(v.getContext()).load(imageUrl).transform(new CircleTransform()).placeholder(android.R.drawable.ic_menu_gallery).into(viewHolder.itemPoster); } if (viewHolder.itemPoster != null) viewHolder.itemPoster.setTag(mBuzzingModel.getBuzzing().get(position).getTrailer()); if (viewHolder.popupMenuButton != null) viewHolder.popupMenuButton.setTag(position); viewHolder.position = position; setButtonOnClickListener(v); } return v; }
public View getView(int position, View v, ViewGroup parent) { BuzzingViewHolder viewHolder; if (getItemViewType(position) == BuzzingType.PULL.ordinal()) { if (v == null) { LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = li.inflate(R.layout.buzzing_item_pull, parent, false); } } else { if (v == null) { LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = li.inflate(mResourceLayoutId, parent, false); viewHolder = new BuzzingViewHolder(); viewHolder.itemName = (TextView) v.findViewById(R.id.buzzingName); viewHolder.itemPoster = (ImageButton) v.findViewById(R.id.buzzingPoster); viewHolder.itemTweetsToday = (TextView) v.findViewById(R.id.buzzingToday); viewHolder.itemTweetsTotal = (TextView) v.findViewById(R.id.buzzingTotal); viewHolder.popupMenuButton = (ImageButton) v.findViewById(R.id.buzzing_popup_menu); if (viewHolder.popupMenuButton != null) { viewHolder.popupMenuButton = (ImageButton) v.findViewById(R.id.buzzing_popup_menu); setButtonOnClickListener(viewHolder.popupMenuButton); } v.setTag(viewHolder); } else { viewHolder = (BuzzingViewHolder) v.getTag(); } if (viewHolder.itemName != null) viewHolder.itemName.setText(mBuzzingModel.getBuzzing().get(position).getName()); if (viewHolder.itemTweetsToday != null) viewHolder.itemTweetsToday.setText(v.getContext().getString(R.string.tweets_today, (int) mBuzzingModel.getBuzzing().get(position).getTweetsToday())); if (viewHolder.itemTweetsTotal != null) viewHolder.itemTweetsTotal.setText(v.getContext().getString(R.string.tweets_total, (int) mBuzzingModel.getBuzzing().get(position).getTweets())); if (viewHolder.itemPoster != null) { String imageUrl = "" + v.getContext().getString(R.string.base_url) + mBuzzingModel.getBuzzing().get(position).getPosterUrl(); Picasso.with(v.getContext()).load(imageUrl).transform(new CircleTransform()).placeholder(android.R.drawable.ic_menu_gallery).into(viewHolder.itemPoster); } if (viewHolder.itemPoster != null) viewHolder.itemPoster.setTag(mBuzzingModel.getBuzzing().get(position).getTrailer()); if (viewHolder.popupMenuButton != null) viewHolder.popupMenuButton.setTag(position); viewHolder.position = position; setButtonOnClickListener(v); } return v; }
public TreeOptionsToolbar(TreeWindow _frame) { super(JToolBar.HORIZONTAL); frame = _frame; try { es = (ExtendedService)ServiceManager.lookup("javax.jnlp.ExtendedService"); } catch (UnavailableServiceException e) { es=null; } try{ FileContents fc = es.openFile(new File("images/collapse.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); collapseButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} collapseButton.setToolTipText("Collapse"); collapseButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.collapseTree(); } }); try{ FileContents fc = es.openFile(new File("images/expand.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); expandButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} expandButton.setToolTipText("Expand"); expandButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.uncollapseTree(); } }); add(collapseButton); add(expandButton); addSeparator(); try{ FileContents fc = es.openFile(new File("images/mirror_vert.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); mirrorvertButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} mirrorvertButton.setToolTipText("Flip Vertical"); mirrorvertButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.mirrorVert(); } }); try{ FileContents fc = es.openFile(new File("images/mirror_horiz.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); mirrorhorzButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} mirrorhorzButton.setToolTipText("Flip Horizontal"); mirrorhorzButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.mirrorHorz(); } }); add(mirrorvertButton); add(mirrorhorzButton); addSeparator(); try{ FileContents fc = es.openFile(new File("images/rectangular.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); rectButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} rectButton.setToolTipText("Rectangular"); rectButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.tree.setTreeLayout("Rectangular"); } }); try{ FileContents fc = es.openFile(new File("images/triangular.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); triButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} triButton.setToolTipText("Triangular"); triButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.tree.setTreeLayout("Triangular"); } }); try{ FileContents fc = es.openFile(new File("images/radial.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); radialButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} radialButton.setToolTipText("Radial"); radialButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.tree.setTreeLayout("Radial"); } }); try{ FileContents fc = es.openFile(new File("images/polar.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); polarButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} polarButton.setToolTipText("Polar"); polarButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.tree.setTreeLayout("Polar"); } }); add(rectButton); add(triButton); add(radialButton); add(polarButton); addSeparator(); add(treeStatus); setFloatable(false); }
public TreeOptionsToolbar(TreeWindow _frame) { super(JToolBar.HORIZONTAL); frame = _frame; try { es = (ExtendedService)ServiceManager.lookup("javax.jnlp.ExtendedService"); } catch (UnavailableServiceException e) { es=null; } try{ FileContents fc = es.openFile(new File("images/collapse.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); collapseButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} collapseButton.setToolTipText("Collapse"); collapseButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.collapseTree(); } }); try{ FileContents fc = es.openFile(new File("images/expand.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); expandButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} expandButton.setToolTipText("Expand"); expandButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.uncollapseTree(); } }); add(collapseButton); add(expandButton); addSeparator(); try{ FileContents fc = es.openFile(new File("images/mirror_vert.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); mirrorvertButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} mirrorvertButton.setToolTipText("Flip Vertical"); mirrorvertButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.mirrorVert(); } }); try{ FileContents fc = es.openFile(new File("images/mirror_horz.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); mirrorhorzButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} mirrorhorzButton.setToolTipText("Flip Horizontal"); mirrorhorzButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.mirrorHorz(); } }); add(mirrorvertButton); add(mirrorhorzButton); addSeparator(); try{ FileContents fc = es.openFile(new File("images/rectangular.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); rectButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} rectButton.setToolTipText("Rectangular"); rectButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.tree.setTreeLayout("Rectangular"); } }); try{ FileContents fc = es.openFile(new File("images/triangular.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); triButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} triButton.setToolTipText("Triangular"); triButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.tree.setTreeLayout("Triangular"); } }); try{ FileContents fc = es.openFile(new File("images/radial.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); radialButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} radialButton.setToolTipText("Radial"); radialButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.tree.setTreeLayout("Radial"); } }); try{ FileContents fc = es.openFile(new File("images/polar.gif")); byte[] buffer = new byte[(int)fc.getLength()]; fc.getInputStream().read(buffer); polarButton.setIcon(new ImageIcon(buffer)); } catch(java.io.IOException ex) {} polarButton.setToolTipText("Polar"); polarButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.tree.setTreeLayout("Polar"); } }); add(rectButton); add(triButton); add(radialButton); add(polarButton); addSeparator(); add(treeStatus); setFloatable(false); }
public void run() { int lastItemStorageId = 0; for (Item item : items) { Items itemInShop = null; try { itemInShop = Database.getDAO(Items.class).queryForId(item.databaseID); } catch (SQLException e) { Logger.error("Could not get Item", e); } if (itemInShop == null) { Logger.info("No item found to update"); continue; } Logger.debug("Item recalc for Item: " + itemInShop.getMeta().getId() + ":" + itemInShop.getMeta().getDataValue()); prepareCache(itemInShop.getId()); Integer sold = (itemInShop.getSold()) * 720; Integer bought = (itemInShop.getBought()) * 720; addToCache(itemInShop.getId(), bought, sold); sold = getAverage(itemInShop.getId(), "sell"); bought = getAverage(itemInShop.getId(), "buy"); Logger.debug("Item Recalc: " + bought + " / " + sold); Float sellPriceDiff = (float) sold / item.maxItemRecalc; Float buyPriceDiff; if (bought > 0) { buyPriceDiff = (float) bought / item.maxItemRecalc; } else { buyPriceDiff = 2.0F; } if (sellPriceDiff > 1.0) { if (sellPriceDiff > item.limitSellPriceFactor) { sellPriceDiff = item.limitSellPriceFactor; } } else { if (sellPriceDiff < item.limitSellPriceUnderFactor) { sellPriceDiff = item.limitSellPriceUnderFactor; } } if (buyPriceDiff > 1.0) { buyPriceDiff = buyPriceDiff * item.limitBuyPriceFactor; if(buyPriceDiff > item.limitBuyPriceFactor) { buyPriceDiff = item.limitBuyPriceFactor; } } else { if (buyPriceDiff < item.limitBuyPriceUnderFactor) { buyPriceDiff = item.limitBuyPriceUnderFactor; } } Logger.debug("Diffs: " + buyPriceDiff + " / " + sellPriceDiff); Float newSellPrice = Math.round(item.sell * sellPriceDiff * 100) / 100.0F; Float newBuyPrice = Math.round(item.buy * buyPriceDiff * 100) / 100.0F; itemInShop.setBuy(newBuyPrice); itemInShop.setSell(newSellPrice); itemInShop.setCurrentAmount(99999); itemInShop.setBought(0); itemInShop.setSold(0); Logger.debug("New Price: " + newBuyPrice + " / " + newSellPrice); try { Database.getDAO(Items.class).update(itemInShop); } catch (SQLException e) { Logger.error("Could not update Item", e); } CustomerSign customerSign = null; try { customerSign = Database.getDAO(CustomerSign.class).queryBuilder(). where(). eq("item_id", itemInShop.getId()). queryForFirst(); } catch (SQLException e) { Logger.error("Could not get Customer Sign", e); } final Items items = itemInShop; if (customerSign != null) { final CustomerSign syncCustomerSign = customerSign; Plugin.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(Plugin.getInstance(), new Runnable() { @Override public void run() { Block block = Plugin.getInstance().getServer().getWorld(syncCustomerSign.getRegion().getWorld()).getBlockAt(syncCustomerSign.getX(), syncCustomerSign.getY(), syncCustomerSign.getZ()); if (block.getType().equals(Material.SIGN_POST) || block.getType().equals(Material.WALL_SIGN)) { Sign sign = (Sign) block.getState(); ItemStack itemStack = ItemRepository.fromDBItem(items); String dataName = ItemName.getDataName(itemStack); String niceItemName; if (dataName.endsWith(" ")) { niceItemName = dataName + ItemName.nicer(itemStack.getType().toString()); } else if (!dataName.equals("")) { niceItemName = dataName; } else { niceItemName = ItemName.nicer(itemStack.getType().toString()); } if (itemStack.getItemMeta().hasDisplayName()) { niceItemName = "(" + itemStack.getItemMeta().getDisplayName() + ")"; } for (Integer line = 0; line < 4; line++) { sign.setLine(line, ConfigManager.language.Sign_Customer_SignText.get(line). replace("%id", items.getId().toString()). replace("%itemname", ItemName.nicer(niceItemName)). replace("%amount", items.getUnitAmount().toString()). replace("%sell", items.getSell().toString()). replace("%buy", items.getBuy().toString())); } sign.update(); } } }); } if (lastItemStorageId != itemInShop.getItemStorage().getId()) { try { itemInShop.getItemStorage().setItemAmount(0); Database.getDAO(ItemStorage.class).update(itemInShop.getItemStorage()); } catch (SQLException e) { Logger.error("Could not reset ItemStorage", e); } lastItemStorageId = itemInShop.getItemStorage().getId(); } } }
public void run() { int lastItemStorageId = 0; for (Item item : items) { Items itemInShop = null; try { itemInShop = Database.getDAO(Items.class).queryForId(item.databaseID); } catch (SQLException e) { Logger.error("Could not get Item", e); } if (itemInShop == null) { Logger.info("No item found to update"); continue; } Logger.debug("Item recalc for Item: " + itemInShop.getMeta().getId() + ":" + itemInShop.getMeta().getDataValue()); prepareCache(itemInShop.getId()); Integer sold = (itemInShop.getSold()); Integer bought = (itemInShop.getBought()); addToCache(itemInShop.getId(), bought, sold); sold = getAverage(itemInShop.getId(), "sell"); bought = getAverage(itemInShop.getId(), "buy"); Logger.debug("Item Recalc: " + bought + " / " + sold); Float sellPriceDiff = (float) sold / item.maxItemRecalc; Float buyPriceDiff; if (bought > 0) { buyPriceDiff = (float) bought / item.maxItemRecalc; } else { buyPriceDiff = 2.0F; } if (sellPriceDiff > 1.0) { if (sellPriceDiff > item.limitSellPriceFactor) { sellPriceDiff = item.limitSellPriceFactor; } } else { if (sellPriceDiff < item.limitSellPriceUnderFactor) { sellPriceDiff = item.limitSellPriceUnderFactor; } } if (buyPriceDiff > 1.0) { buyPriceDiff = buyPriceDiff * item.limitBuyPriceFactor; if(buyPriceDiff > item.limitBuyPriceFactor) { buyPriceDiff = item.limitBuyPriceFactor; } } else { if (buyPriceDiff < item.limitBuyPriceUnderFactor) { buyPriceDiff = item.limitBuyPriceUnderFactor; } } Logger.debug("Diffs: " + buyPriceDiff + " / " + sellPriceDiff); Float newSellPrice = Math.round(item.sell * sellPriceDiff * 100) / 100.0F; Float newBuyPrice = Math.round(item.buy * buyPriceDiff * 100) / 100.0F; itemInShop.setBuy(newBuyPrice); itemInShop.setSell(newSellPrice); itemInShop.setCurrentAmount(99999); itemInShop.setBought(0); itemInShop.setSold(0); Logger.debug("New Price: " + newBuyPrice + " / " + newSellPrice); try { Database.getDAO(Items.class).update(itemInShop); } catch (SQLException e) { Logger.error("Could not update Item", e); } CustomerSign customerSign = null; try { customerSign = Database.getDAO(CustomerSign.class).queryBuilder(). where(). eq("item_id", itemInShop.getId()). queryForFirst(); } catch (SQLException e) { Logger.error("Could not get Customer Sign", e); } final Items items = itemInShop; if (customerSign != null) { final CustomerSign syncCustomerSign = customerSign; Plugin.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(Plugin.getInstance(), new Runnable() { @Override public void run() { Block block = Plugin.getInstance().getServer().getWorld(syncCustomerSign.getRegion().getWorld()).getBlockAt(syncCustomerSign.getX(), syncCustomerSign.getY(), syncCustomerSign.getZ()); if (block.getType().equals(Material.SIGN_POST) || block.getType().equals(Material.WALL_SIGN)) { Sign sign = (Sign) block.getState(); ItemStack itemStack = ItemRepository.fromDBItem(items); String dataName = ItemName.getDataName(itemStack); String niceItemName; if (dataName.endsWith(" ")) { niceItemName = dataName + ItemName.nicer(itemStack.getType().toString()); } else if (!dataName.equals("")) { niceItemName = dataName; } else { niceItemName = ItemName.nicer(itemStack.getType().toString()); } if (itemStack.getItemMeta().hasDisplayName()) { niceItemName = "(" + itemStack.getItemMeta().getDisplayName() + ")"; } for (Integer line = 0; line < 4; line++) { sign.setLine(line, ConfigManager.language.Sign_Customer_SignText.get(line). replace("%id", items.getId().toString()). replace("%itemname", ItemName.nicer(niceItemName)). replace("%amount", items.getUnitAmount().toString()). replace("%sell", items.getSell().toString()). replace("%buy", items.getBuy().toString())); } sign.update(); } } }); } if (lastItemStorageId != itemInShop.getItemStorage().getId()) { try { itemInShop.getItemStorage().setItemAmount(0); Database.getDAO(ItemStorage.class).update(itemInShop.getItemStorage()); } catch (SQLException e) { Logger.error("Could not reset ItemStorage", e); } lastItemStorageId = itemInShop.getItemStorage().getId(); } } }
public Void run(Handler handler) { StringBuffer transconfig = new StringBuffer(); StringBuffer errorconfig = new StringBuffer(); StringBuffer transvalue = new StringBuffer(); StringBuffer errorvalue = new StringBuffer(); transconfig.append("graph_order down up\n"); transconfig.append("graph_title Network traffic\n"); transconfig.append("graph_args --base 1000\n"); transconfig.append("graph_vlabel bits in (-) / out (+) per ${graph_period}\n"); transconfig.append("graph_category network\n"); transconfig.append("graph_info This graph shows the traffic of the network interfaces. Please note that the traffic is shown in bits per second, not bytes. IMPORTANT: On 32 bit systems the data source for this plugin uses 32bit counters, which makes the plugin unreliable and unsuitable for most 100Mb (or faster) interfaces, where traffic is expected to exceed 50Mbps over a 5 minute period. This means that this plugin is unsuitable for most 32 bit production environments. To avoid this problem, use the ip_ plugin instead. There should be no problems on 64 bit systems running 64 bit kernels.\n"); errorconfig.append("\nmultigraph Network_Errors\n"); errorconfig.append("graph_order rcvd trans\n"); errorconfig.append("graph_title Network errors\n"); errorconfig.append("graph_args --base 1000\n"); errorconfig.append("graph_vlabel packets in (-) / out (+) per ${graph_period}\n"); errorconfig.append("graph_category network\n"); errorconfig.append("graph_info This graph shows the amount of errors on the network interfaces.\n"); Pattern network_pattern = Pattern.compile("([\\w\\d]+):\\s+([\\d]+)\\s+[\\d]+\\s+([\\d]+)\\s+[\\d]+\\s+\\s+[\\d]+\\s+[\\d]+\\s+[\\d]+\\s+[\\d]+\\s+([\\d]+)\\s+[\\d]+\\s+([\\d]+)\\s+"); BufferedReader in = null; try { in = new BufferedReader(new FileReader("/proc/net/dev")); String str; Integer count = 0; while ((str = in.readLine()) != null) { Matcher network_matcher = network_pattern.matcher(str); if(network_matcher.find()){ transconfig.append(network_matcher.group(1)+"down.label "+network_matcher.group(1)+" received\n"); transconfig.append(network_matcher.group(1)+"down.type COUNTER\n"); transconfig.append(network_matcher.group(1)+"down.graph yes\n"); transconfig.append(network_matcher.group(1)+"down.colour "+Colours[count]+"\n"); transconfig.append(network_matcher.group(1)+"down.cdef "+network_matcher.group(1)+"down,-8,*\n"); transconfig.append(network_matcher.group(1)+"up.label "+network_matcher.group(1)+" uploaded\n"); transconfig.append(network_matcher.group(1)+"up.type COUNTER\n"); transconfig.append(network_matcher.group(1)+"up.colour "+Colours[count]+"\n"); transconfig.append(network_matcher.group(1)+"up.cdef "+network_matcher.group(1)+"up,8,*\n"); errorconfig.append(network_matcher.group(1)+"rcvd.label "+network_matcher.group(1)+"\n"); errorconfig.append(network_matcher.group(1)+"rcvd.type COUNTER\n"); errorconfig.append(network_matcher.group(1)+"rcvd.graph yes\n"); errorconfig.append(network_matcher.group(1)+"rcvd.colour "+Colours[count]+"\n"); errorconfig.append(network_matcher.group(1)+"rcvd.warning 1\n"); errorconfig.append(network_matcher.group(1)+"trans.label "+network_matcher.group(1)+"\n"); errorconfig.append(network_matcher.group(1)+"trans.type COUNTER\n"); errorconfig.append(network_matcher.group(1)+"trans.colour "+Colours[count]+"\n"); errorconfig.append(network_matcher.group(1)+"trans.warning 1\n"); transvalue.append(network_matcher.group(1)+"down.value "+network_matcher.group(2)+"\n"); transvalue.append(network_matcher.group(1)+"up.value "+network_matcher.group(4)+"\n"); errorvalue.append(network_matcher.group(1)+"rcvd.value "+network_matcher.group(3)+"\n"); errorvalue.append(network_matcher.group(1)+"trans.value "+network_matcher.group(5)+"\n"); count++; } } } catch (FileNotFoundException e) { } catch (IOException e) { } Bundle bundle = new Bundle(); bundle.putString("name", this.getName()); bundle.putString("config", transconfig.toString()+errorconfig.toString()); bundle.putString("update", transvalue.toString()+errorvalue.toString()); Message msg = Message.obtain(handler, 42, bundle); handler.sendMessage(msg); return null; }
public Void run(Handler handler) { StringBuffer transconfig = new StringBuffer(); StringBuffer errorconfig = new StringBuffer(); StringBuffer transvalue = new StringBuffer(); StringBuffer errorvalue = new StringBuffer(); transconfig.append("graph_order down up\n"); transconfig.append("graph_title Network traffic\n"); transconfig.append("graph_args --base 1000\n"); transconfig.append("graph_vlabel bits in (-) / out (+) per ${graph_period}\n"); transconfig.append("graph_category network\n"); transconfig.append("graph_info This graph shows the traffic of the network interfaces. Please note that the traffic is shown in bits per second, not bytes. IMPORTANT: On 32 bit systems the data source for this plugin uses 32bit counters, which makes the plugin unreliable and unsuitable for most 100Mb (or faster) interfaces, where traffic is expected to exceed 50Mbps over a 5 minute period. This means that this plugin is unsuitable for most 32 bit production environments. To avoid this problem, use the ip_ plugin instead. There should be no problems on 64 bit systems running 64 bit kernels.\n"); errorconfig.append("\nmultigraph Network_Errors\n"); errorconfig.append("graph_order rcvd trans\n"); errorconfig.append("graph_title Network errors\n"); errorconfig.append("graph_args --base 1000\n"); errorconfig.append("graph_vlabel packets in (-) / out (+) per ${graph_period}\n"); errorconfig.append("graph_category network\n"); errorconfig.append("graph_info This graph shows the amount of errors on the network interfaces.\n"); Pattern network_pattern = Pattern.compile("([\\w\\d]+):\\s+([\\d]+)\\s+[\\d]+\\s+([\\d]+)\\s+[\\d]+\\s+\\s+[\\d]+\\s+[\\d]+\\s+[\\d]+\\s+[\\d]+\\s+([\\d]+)\\s+[\\d]+\\s+([\\d]+)\\s+"); BufferedReader in = null; try { in = new BufferedReader(new FileReader("/proc/net/dev")); String str; Integer count = 0; while ((str = in.readLine()) != null) { Matcher network_matcher = network_pattern.matcher(str); if(network_matcher.find()){ transconfig.append(network_matcher.group(1)+"down.label "+network_matcher.group(1)+" received\n"); transconfig.append(network_matcher.group(1)+"down.type COUNTER\n"); transconfig.append(network_matcher.group(1)+"down.graph yes\n"); transconfig.append(network_matcher.group(1)+"down.colour "+Colours[count]+"\n"); transconfig.append(network_matcher.group(1)+"down.cdef "+network_matcher.group(1)+"down,-8,*\n"); transconfig.append(network_matcher.group(1)+"up.label "+network_matcher.group(1)+" uploaded\n"); transconfig.append(network_matcher.group(1)+"up.type COUNTER\n"); transconfig.append(network_matcher.group(1)+"up.colour "+Colours[count]+"\n"); transconfig.append(network_matcher.group(1)+"up.cdef "+network_matcher.group(1)+"up,8,*\n"); errorconfig.append(network_matcher.group(1)+"rcvd.label "+network_matcher.group(1)+"\n"); errorconfig.append(network_matcher.group(1)+"rcvd.type COUNTER\n"); errorconfig.append(network_matcher.group(1)+"rcvd.graph yes\n"); errorconfig.append(network_matcher.group(1)+"rcvd.colour "+Colours[count]+"\n"); errorconfig.append(network_matcher.group(1)+"rcvd.warning 1\n"); errorconfig.append(network_matcher.group(1)+"trans.label "+network_matcher.group(1)+"\n"); errorconfig.append(network_matcher.group(1)+"trans.type COUNTER\n"); errorconfig.append(network_matcher.group(1)+"trans.colour "+Colours[count]+"\n"); errorconfig.append(network_matcher.group(1)+"trans.warning 1\n"); transvalue.append(network_matcher.group(1)+"down.value "+network_matcher.group(2)+"\n"); transvalue.append(network_matcher.group(1)+"up.value "+network_matcher.group(4)+"\n"); errorvalue.append(network_matcher.group(1)+"rcvd.value "+network_matcher.group(3)+"\n"); errorvalue.append(network_matcher.group(1)+"trans.value "+network_matcher.group(5)+"\n"); count++; } } } catch (FileNotFoundException e) { } catch (IOException e) { } Bundle bundle = new Bundle(); bundle.putString("name", this.getName()); bundle.putString("config", transconfig.toString()+errorconfig.toString()); bundle.putString("update", transvalue.toString()+"\nmultigraph Network_Errors\n"+errorvalue.toString()); Message msg = Message.obtain(handler, 42, bundle); handler.sendMessage(msg); return null; }
public void init() { System.out.println("Loading Module Resources"); Camera.setVantage(FluidVantage.create(0.04F)); Camera.getInstance().setPosition(CAMERA_START); try { this.vaughnTextureSheet = TextureLoader.getInstance().getTexture("sprites/Vaughn/world/Vaughn.png"); this.worldCeiling = new Sprite("maps/TheGrotto.png",ImageRenderMode.STANDING); this.environmentSheet = TextureLoader.getInstance().getTexture("maps/TreesRocksGate.gif"); } catch(Exception e) { System.out.println("BAD THINGS HAPPENED"); e.printStackTrace(); System.exit(1); } Table<Integer, Integer, Sprite> vaughnSpriteAtlas = createCharacterAtlas(); Animation.Builder builder = Animation.builder(); Animation toward = builder .addFrame(vaughnSpriteAtlas.get(0, 1), 175) .addFrame(vaughnSpriteAtlas.get(0, 2), 175) .addFrame(vaughnSpriteAtlas.get(0, 3), 175) .addFrame(vaughnSpriteAtlas.get(0, 0), 175) .build(); Animation left = builder .addFrame(vaughnSpriteAtlas.get(1, 1), 175) .addFrame(vaughnSpriteAtlas.get(1, 2), 175) .addFrame(vaughnSpriteAtlas.get(1, 3), 175) .addFrame(vaughnSpriteAtlas.get(1, 0), 175) .build(); Animation right = builder .addFrame(vaughnSpriteAtlas.get(2, 1), 175) .addFrame(vaughnSpriteAtlas.get(2, 2), 175) .addFrame(vaughnSpriteAtlas.get(2, 3), 175) .addFrame(vaughnSpriteAtlas.get(2, 0), 175) .build(); Animation away = builder .addFrame(vaughnSpriteAtlas.get(3, 1), 175) .addFrame(vaughnSpriteAtlas.get(3, 2), 175) .addFrame(vaughnSpriteAtlas.get(3, 3), 175) .addFrame(vaughnSpriteAtlas.get(3, 0), 175) .build(); Sprite tree = new Sprite(environmentSheet.getSubTexture(2*TILE, 0*TILE, 2*TILE, 3*TILE), ImageRenderMode.STANDING); Sprite bush = new Sprite(environmentSheet.getSubTexture(3*TILE, 3*TILE, 3*TILE, 3*TILE), ImageRenderMode.STANDING); Sprite rock = new Sprite(environmentSheet.getSubTexture(4*TILE, 2*TILE, 1*TILE, 1*TILE), ImageRenderMode.STANDING); Sprite spike= new Sprite(environmentSheet.getSubTexture(6*TILE, 0*TILE, 1*TILE, 2*TILE), ImageRenderMode.STANDING); world = new World(); renderSystem = new RenderSystem(800,600); world.setSystem(renderSystem, true); world.setSystem(new PlayerControlSystem()); world.setSystem(new MovementSystem()); world.setSystem(new SpriteControlSystem()); world.setSystem(new CameraSystem()); world.setSystem(new CollisionSystem()); world.initialize(); Position positionComponent = new Position(1150, 700); CameraMount cameraMount = new CameraMount( VAUGHN_TEXTURE_SHEET_WIDTH/2.0F , VAUGHN_TEXTURE_SHEET_HEIGHT/2.0F ); RenderComponent renderComponent = new RenderComponent(vaughnSpriteAtlas.get(0, 0)); SpriteControl spriteControl = addAnimations( addSprites( new SpriteControl() , vaughnSpriteAtlas.get(0, 0) , vaughnSpriteAtlas.get(3, 0) , vaughnSpriteAtlas.get(2, 0) , vaughnSpriteAtlas.get(1, 0) ) , toward , away , right , left ); DynamicBody body = new DynamicBody( 1150 , 700 , 16 , 12 , 16 , 36 ); vaughn = world.createEntity(); vaughn.addComponent(positionComponent); vaughn.addComponent(renderComponent); vaughn.addComponent(new Rotation(WorldProfile.WorldDirection.DOWN.getDirection())); vaughn.addComponent(new Velocity(WorldProfile.Speed.STOP.getSpeed())); vaughn.addComponent(new PlayerControl(WorldProfile.Control.ARROWS)); vaughn.addComponent(spriteControl); vaughn.addComponent(Camera.attachTo(cameraMount)); vaughn.addComponent(body); vaughn.addToWorld(); Entity treeEnt = world.createEntity(); treeEnt.addComponent(new Position(28*TILE, 14*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(28*TILE, 14*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); treeEnt = world.createEntity(); treeEnt.addComponent(new Position(15*TILE, 13*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(15*TILE, 13*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); treeEnt = world.createEntity(); treeEnt.addComponent(new Position(24*TILE, 19*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(24*TILE, 19*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); Entity rockEnt = world.createEntity(); rockEnt.addComponent(new Position(26*TILE,18*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(26*TILE, 18*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); rockEnt = world.createEntity(); rockEnt.addComponent(new Position(21*TILE,14*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(21*TILE, 14*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); rockEnt = world.createEntity(); rockEnt.addComponent(new Position(20*TILE,19*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(20*TILE, 19*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); Entity bushEnt = world.createEntity(); bushEnt.addComponent(new Position(38*TILE, 22*TILE)); bushEnt.addComponent(new RenderComponent(bush)); bushEnt.addComponent(new StaticBody(38*TILE, 22*TILE, 75, 50, 65, 90)); bushEnt.addToWorld(); Entity spireEnt = world.createEntity(); spireEnt.addComponent(new Position(34*TILE,20*TILE)); spireEnt.addComponent(new RenderComponent(spike)); spireEnt.addComponent(new StaticBody(34*TILE, 20*TILE,40, 30, 20, 60)); spireEnt.addToWorld(); try { map = new TiledMap("maps/grotto.tmx"); } catch(SlickException se) { se.printStackTrace(); System.exit(1); } System.out.println("Load Complete"); }
public void init() { System.out.println("Loading Module Resources"); Camera.setVantage(FluidVantage.create(0.04F)); Camera.getInstance().setPosition(CAMERA_START); try { this.vaughnTextureSheet = TextureLoader.getInstance().getTexture("sprites/Vaughn/world/Vaughn.png"); this.worldCeiling = new Sprite("maps/TheGrotto.png",ImageRenderMode.STANDING); this.environmentSheet = TextureLoader.getInstance().getTexture("maps/TreesRocksGate.gif"); } catch(Exception e) { System.out.println("BAD THINGS HAPPENED"); e.printStackTrace(); System.exit(1); } Table<Integer, Integer, Sprite> vaughnSpriteAtlas = createCharacterAtlas(); Animation.Builder builder = Animation.builder(); Animation toward = builder .addFrame(vaughnSpriteAtlas.get(0, 1), 175) .addFrame(vaughnSpriteAtlas.get(0, 2), 175) .addFrame(vaughnSpriteAtlas.get(0, 3), 175) .addFrame(vaughnSpriteAtlas.get(0, 0), 175) .build(); Animation left = builder .addFrame(vaughnSpriteAtlas.get(1, 1), 175) .addFrame(vaughnSpriteAtlas.get(1, 2), 175) .addFrame(vaughnSpriteAtlas.get(1, 3), 175) .addFrame(vaughnSpriteAtlas.get(1, 0), 175) .build(); Animation right = builder .addFrame(vaughnSpriteAtlas.get(2, 1), 175) .addFrame(vaughnSpriteAtlas.get(2, 2), 175) .addFrame(vaughnSpriteAtlas.get(2, 3), 175) .addFrame(vaughnSpriteAtlas.get(2, 0), 175) .build(); Animation away = builder .addFrame(vaughnSpriteAtlas.get(3, 1), 175) .addFrame(vaughnSpriteAtlas.get(3, 2), 175) .addFrame(vaughnSpriteAtlas.get(3, 3), 175) .addFrame(vaughnSpriteAtlas.get(3, 0), 175) .build(); Sprite tree = new Sprite(environmentSheet.getSubTexture(2*TILE, 0*TILE, 2*TILE, 3*TILE), ImageRenderMode.STANDING); Sprite bush = new Sprite(environmentSheet.getSubTexture(3*TILE, 3*TILE, 3*TILE, 3*TILE), ImageRenderMode.STANDING); Sprite rock = new Sprite(environmentSheet.getSubTexture(4*TILE, 2*TILE, 1*TILE, 1*TILE), ImageRenderMode.STANDING); Sprite spike= new Sprite(environmentSheet.getSubTexture(6*TILE, 0*TILE, 1*TILE, 2*TILE), ImageRenderMode.STANDING); world = new World(); renderSystem = new RenderSystem(800,600); world.setSystem(renderSystem, true); world.setSystem(new PlayerControlSystem()); world.setSystem(new MovementSystem()); world.setSystem(new SpriteControlSystem()); world.setSystem(new CameraSystem()); world.setSystem(new CollisionSystem()); world.initialize(); Position positionComponent = new Position(1150, 700); CameraMount cameraMount = new CameraMount( VAUGHN_TEXTURE_SHEET_WIDTH/2.0F , VAUGHN_TEXTURE_SHEET_HEIGHT/2.0F ); RenderComponent renderComponent = new RenderComponent(vaughnSpriteAtlas.get(0, 0)); SpriteControl spriteControl = addAnimations( addSprites( new SpriteControl() , vaughnSpriteAtlas.get(0, 0) , vaughnSpriteAtlas.get(3, 0) , vaughnSpriteAtlas.get(2, 0) , vaughnSpriteAtlas.get(1, 0) ) , toward , away , right , left ); DynamicBody body = new DynamicBody( 1150 , 700 , 16 , 12 , 16 , 36 ); vaughn = world.createEntity(); vaughn.addComponent(positionComponent); vaughn.addComponent(renderComponent); vaughn.addComponent(new Rotation(WorldProfile.WorldDirection.DOWN.getDirection())); vaughn.addComponent(new Velocity(WorldProfile.Speed.STOP.getSpeed())); vaughn.addComponent(new PlayerControl(WorldProfile.Control.ARROWS)); vaughn.addComponent(spriteControl); vaughn.addComponent(Camera.attachTo(cameraMount)); vaughn.addComponent(body); vaughn.addToWorld(); Entity treeEnt = world.createEntity(); treeEnt.addComponent(new Position(28*TILE, 14*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(28*TILE, 14*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); treeEnt = world.createEntity(); treeEnt.addComponent(new Position(15*TILE, 13*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(15*TILE, 13*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); treeEnt = world.createEntity(); treeEnt.addComponent(new Position(24*TILE, 19*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(24*TILE, 19*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); Entity rockEnt = world.createEntity(); rockEnt.addComponent(new Position(26*TILE,18*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(26*TILE, 18*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); rockEnt = world.createEntity(); rockEnt.addComponent(new Position(21*TILE,14*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(21*TILE, 14*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); rockEnt = world.createEntity(); rockEnt.addComponent(new Position(20*TILE,19*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(20*TILE, 19*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); Entity bushEnt = world.createEntity(); bushEnt.addComponent(new Position(38*TILE, 22*TILE)); bushEnt.addComponent(new RenderComponent(bush)); bushEnt.addComponent(new StaticBody(38*TILE, 22*TILE, 75, 50, 65, 90)); bushEnt.addToWorld(); Entity spireEnt = world.createEntity(); spireEnt.addComponent(new Position(34*TILE,20*TILE)); spireEnt.addComponent(new RenderComponent(spike)); spireEnt.addComponent(new StaticBody(34*TILE, 20*TILE,40, 30, 20, 60)); spireEnt.addToWorld(); try { map = new TiledMap("src/main/resources/maps/grotto.tmx"); } catch(SlickException se) { se.printStackTrace(); System.exit(1); } System.out.println("Load Complete"); }
public void testSearch() throws Exception { String queryStr = "test"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String dateStr = format.format(new java.util.Date(System.currentTimeMillis() - 24 * 3600 * 1000)); Query query = new Query(queryStr).until(dateStr); QueryResult queryResult = unauthenticated.search(query); assertTrue("sinceId", -1 != queryResult.getSinceId()); assertTrue(1265204883 < queryResult.getMaxId()); assertTrue(-1 != queryResult.getRefreshUrl().indexOf(queryStr)); assertEquals(15, queryResult.getResultsPerPage()); assertTrue(0 < queryResult.getCompletedIn()); assertEquals(1, queryResult.getPage()); assertEquals(queryStr + " until:"+ dateStr, queryResult.getQuery()); List<Tweet> tweets = queryResult.getTweets(); assertTrue(1<=tweets.size()); assertNotNull(tweets.get(0).getText()); assertNotNull(tweets.get(0).getCreatedAt()); assertNotNull("from user", tweets.get(0).getFromUser()); assertTrue("fromUserId", -1 != tweets.get(0).getFromUserId()); assertTrue(-1 != tweets.get(0).getId()); String profileImageURL = tweets.get(0).getProfileImageUrl(); assertTrue(-1 != profileImageURL.toLowerCase().indexOf(".jpg") || -1 != profileImageURL.toLowerCase().indexOf(".png") || -1 != profileImageURL.toLowerCase().indexOf(".gif")); String source = tweets.get(0).getSource(); assertTrue(-1 != source.indexOf("<a href=\"") || "web".equals(source) || "API".equals(source)); query = new Query("from:twit4j doesnothit"); queryResult = unauthenticated.search(query); assertEquals(0, queryResult.getSinceId()); assertNull(queryResult.getRefreshUrl()); assertEquals(15, queryResult.getResultsPerPage()); assertNull(queryResult.getWarning()); assertTrue(1 > queryResult.getCompletedIn()); assertEquals(1, queryResult.getPage()); assertEquals("from:twit4j doesnothit", queryResult.getQuery()); queryStr = "%... 日本語 "; twitterAPI1.updateStatus(queryStr + new Date()); query = new Query(queryStr); queryResult = unauthenticated.search(query); assertEquals(queryStr, queryResult.getQuery()); assertTrue(0 < queryResult.getTweets().size()); query.setQuery("from:al3x"); query.setGeoCode(new GeoLocation(37.78233252646689,-122.39301681518555) ,10,Query.KILOMETERS); queryResult = unauthenticated.search(query); assertTrue(0 < queryResult.getTweets().size()); query = new Query("from:beastieboys"); query.setSinceId(1671199128); queryResult = unauthenticated.search(query); assertEquals(0, queryResult.getTweets().size()); query = new Query("\\u5e30%u5e30 <%}& foobar").rpp(100).page(1); QueryResult result = twitterAPI1.search(query); }
public void testSearch() throws Exception { String queryStr = "test"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String dateStr = format.format(new java.util.Date(System.currentTimeMillis() - 24 * 3600 * 1000)); Query query = new Query(queryStr).until(dateStr); QueryResult queryResult = unauthenticated.search(query); assertTrue("sinceId", -1 != queryResult.getSinceId()); assertTrue(1265204883 < queryResult.getMaxId()); assertTrue(-1 != queryResult.getRefreshUrl().indexOf(queryStr)); assertEquals(15, queryResult.getResultsPerPage()); assertTrue(0 < queryResult.getCompletedIn()); assertEquals(1, queryResult.getPage()); assertEquals(queryStr + " until:"+ dateStr, queryResult.getQuery()); List<Tweet> tweets = queryResult.getTweets(); assertTrue(1<=tweets.size()); assertNotNull(tweets.get(0).getText()); assertNotNull(tweets.get(0).getCreatedAt()); assertNotNull("from user", tweets.get(0).getFromUser()); assertTrue("fromUserId", -1 != tweets.get(0).getFromUserId()); assertTrue(-1 != tweets.get(0).getId()); String profileImageURL = tweets.get(0).getProfileImageUrl(); assertTrue(-1 != profileImageURL.toLowerCase().indexOf(".jpg") || -1 != profileImageURL.toLowerCase().indexOf(".png") || -1 != profileImageURL.toLowerCase().indexOf(".gif")); String source = tweets.get(0).getSource(); assertTrue(-1 != source.indexOf("<a href=\"") || "web".equals(source) || "API".equals(source)); query = new Query("from:twit4j doesnothit"); queryResult = unauthenticated.search(query); assertEquals(0, queryResult.getSinceId()); assertEquals(15, queryResult.getResultsPerPage()); assertNull(queryResult.getWarning()); assertTrue(4 > queryResult.getCompletedIn()); assertEquals(1, queryResult.getPage()); assertEquals("from:twit4j doesnothit", queryResult.getQuery()); queryStr = "%... 日本語 "; twitterAPI1.updateStatus(queryStr + new Date()); query = new Query(queryStr); queryResult = unauthenticated.search(query); assertEquals(queryStr, queryResult.getQuery()); assertTrue(0 < queryResult.getTweets().size()); query.setQuery("from:al3x"); query.setGeoCode(new GeoLocation(37.78233252646689,-122.39301681518555) ,10,Query.KILOMETERS); queryResult = unauthenticated.search(query); assertTrue(0 <= queryResult.getTweets().size()); query = new Query("from:beastieboys"); query.setSinceId(1671199128); queryResult = unauthenticated.search(query); assertEquals(0, queryResult.getTweets().size()); query = new Query("\\u5e30%u5e30 <%}& foobar").rpp(100).page(1); QueryResult result = twitterAPI1.search(query); }
public GameVisualisation(int view, int n, int length, List<PokemonSpecies> speciesList) { this.setLayout(null); m_view = view; m_active = new VisualPokemon[2][n]; m_parties = new VisualPokemon[2][length]; m_pokeballs = new Pokeball[2][length]; m_speciesList = speciesList; int background = new Random().nextInt(BACKGROUND_COUNT) + 1; m_background = getImageFromResource("backgrounds/background" + background + ".png"); MediaTracker tracker = new MediaTracker(this); tracker.addImage(m_background, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { e.printStackTrace(); } int rows = length / 3; for (int i = 0; i < m_parties.length; i++) { for (int j = 0; j < m_parties[i].length; j++) { VisualPokemon p = new VisualPokemon(); m_parties[i][j] = p; Pokeball ball = new Pokeball(p); m_pokeballs[i][j] = ball; Dimension d = ball.getPreferredSize(); ball.setSize(d); int x, y; int w = m_background.getWidth(this); int h = m_background.getHeight(this); int row = j / 3; int buff = 1; x = (j - 3*row) * (d.width + buff) + 2; y = (d.width + buff) * row + 2; if (view == i) { x += w - 3 * (d.width + buff) - 2; y += h - rows * (d.width + buff); } ball.setLocation(x, y); this.add(ball); } } m_n = n; m_length = length; m_sprites = new Sprite[2][n]; for (int i = 0; i < m_sprites.length; i++) { for (int j = 0; j < m_sprites[i].length; j++) { boolean us = (i == m_view); Sprite s = new Sprite(i, j, !us, this); s.setSize(s.getPreferredSize()); s.setLocation(getSpriteLocation(us, j, m_n, 0, 0)); m_sprites[i][j] = s; this.add(s, new Integer(m_view * m_sprites[i].length + j)); } } setBorder(BorderFactory.createLineBorder(Color.GRAY)); Dimension d = getPreferredSize(); final BufferedImage image = new BufferedImage((int)d.getWidth(), (int)d.getHeight(), BufferedImage.TYPE_BYTE_BINARY, m_colours); m_mouseInput = image.createGraphics(); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { int x = e.getX(); int y = e.getY(); if ((x > image.getWidth()) || (y > image.getHeight())) return; Color c = new Color(image.getRGB(x, y)); if (c.equals(Color.WHITE)) { setToolTipText(null); return; } else if (c.getGreen() == 1) { displayInformation(c.getRed(), -1); } else if (c.equals(Color.BLACK)) { displayInformation(-1, -1); } } }); }
public GameVisualisation(int view, int n, int length, List<PokemonSpecies> speciesList) { this.setLayout(null); m_view = view; m_active = new VisualPokemon[2][n]; m_parties = new VisualPokemon[2][length]; m_pokeballs = new Pokeball[2][length]; m_speciesList = speciesList; int background = new Random().nextInt(BACKGROUND_COUNT) + 1; m_background = getImageFromResource("backgrounds/background" + background + ".png"); MediaTracker tracker = new MediaTracker(this); tracker.addImage(m_background, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { e.printStackTrace(); } int rows = (int)Math.ceil(length / 3d); for (int i = 0; i < m_parties.length; i++) { for (int j = 0; j < m_parties[i].length; j++) { VisualPokemon p = new VisualPokemon(); m_parties[i][j] = p; Pokeball ball = new Pokeball(p); m_pokeballs[i][j] = ball; Dimension d = ball.getPreferredSize(); ball.setSize(d); int x, y; int w = m_background.getWidth(this); int h = m_background.getHeight(this); int row = j / 3; int buff = 1; x = (j - 3*row) * (d.width + buff) + 2; y = (d.width + buff) * row + 2; if (view == i) { int pokeballWidth = Math.min(m_parties[i].length, 3) * (d.width + buff); x += w - pokeballWidth - 2; y += h - rows * (d.height + buff); } ball.setLocation(x, y); this.add(ball); } } m_n = n; m_length = length; m_sprites = new Sprite[2][n]; for (int i = 0; i < m_sprites.length; i++) { for (int j = 0; j < m_sprites[i].length; j++) { boolean us = (i == m_view); Sprite s = new Sprite(i, j, !us, this); s.setSize(s.getPreferredSize()); s.setLocation(getSpriteLocation(us, j, m_n, 0, 0)); m_sprites[i][j] = s; this.add(s, new Integer(m_view * m_sprites[i].length + j)); } } setBorder(BorderFactory.createLineBorder(Color.GRAY)); Dimension d = getPreferredSize(); final BufferedImage image = new BufferedImage((int)d.getWidth(), (int)d.getHeight(), BufferedImage.TYPE_BYTE_BINARY, m_colours); m_mouseInput = image.createGraphics(); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { int x = e.getX(); int y = e.getY(); if ((x > image.getWidth()) || (y > image.getHeight())) return; Color c = new Color(image.getRGB(x, y)); if (c.equals(Color.WHITE)) { setToolTipText(null); return; } else if (c.getGreen() == 1) { displayInformation(c.getRed(), -1); } else if (c.equals(Color.BLACK)) { displayInformation(-1, -1); } } }); }
public void preloadExpertItems() { if (evaluationDao.findAll(EvalScale.class).isEmpty()) { Set itemSet; Set groupSet; groupSet = new HashSet(); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("I learned a good deal of factual material in this course", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("I gained a good understanding of principals and concepts in this field", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("I developed the a working knowledge of this field", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); groupSet.add( saveObjectiveGroup("Knowledge", "", itemSet) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("I participated actively in group discussions", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("I developed leadership skills within this group", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("I developed new friendships within this group", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); groupSet.add( saveObjectiveGroup("Participation", "", itemSet) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("I gained a better understanding of myself through this course", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("I developed a greater sense of personal responsibility", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("I increased my awareness of my own interests and talents", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); groupSet.add( saveObjectiveGroup("Self-concept", "", itemSet) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("Group activities contributed significantly to my learning", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Collaborative group activities helped me learn the materials", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Working with others in the group helpded me learn more effectively", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); groupSet.add( saveObjectiveGroup("Interaction", "", itemSet) ); evaluationDao.save( new EvalItemGroup(new Date(), EvalConstants.ITEM_GROUP_TYPE_CATEGORY, "Student Development", "Determine how student development is perceived", null, groupSet) ); groupSet = new HashSet(); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("The instructor explained material clearly and understandably", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor handled questions well", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor appeared to have a thorough knowledge of the subject and field", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor taught in a manner that served my needs", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); groupSet.add( saveObjectiveGroup("Skill", "", itemSet) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("The instructor was friendly", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor was permissive and flexible", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor treated students with respect", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); groupSet.add( saveObjectiveGroup("Climate", "", itemSet) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("The instructor suggested specific ways students could improve", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor gave positive feedback when students did especially well", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor kept students informed of their progress", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); groupSet.add( saveObjectiveGroup("Feedback", "", itemSet) ); evaluationDao.save( new EvalItemGroup(new Date(), EvalConstants.ITEM_GROUP_TYPE_CATEGORY, "Instructor Effectiveness", "Determine the perceived effectiveness of the instructor", null, groupSet) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("Examinations covered the important aspects of the course", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Exams were creative and required original thought", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Exams were reasonable in length and difficulty", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Examination items were clearly worded", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Exam length was appropriate for the time alloted", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); evaluationDao.save( new EvalItemGroup(new Date(), EvalConstants.ITEM_GROUP_TYPE_CATEGORY, "Exams", "Measure the perception of examinations", itemSet, null) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("Assignments were interesting and stimulating", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Assignments made students think", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Assignments required a reasonable amount of time and effort", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Assignments were relevant to what was presented", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Assignments were graded fairly", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); evaluationDao.save( new EvalItemGroup(new Date(), EvalConstants.ITEM_GROUP_TYPE_CATEGORY, "Assignments", "Measure the perception of out of class assignments", itemSet, null) ); log.info("Preloaded " + evaluationDao.countAll(EvalItem.class) + " evaluation items"); } }
public void preloadExpertItems() { if (evaluationDao.findAll(EvalItem.class).isEmpty()) { Set itemSet; Set groupSet; groupSet = new HashSet(); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("I learned a good deal of factual material in this course", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("I gained a good understanding of principals and concepts in this field", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("I developed the a working knowledge of this field", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); groupSet.add( saveObjectiveGroup("Knowledge", "", itemSet) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("I participated actively in group discussions", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("I developed leadership skills within this group", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("I developed new friendships within this group", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); groupSet.add( saveObjectiveGroup("Participation", "", itemSet) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("I gained a better understanding of myself through this course", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("I developed a greater sense of personal responsibility", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("I increased my awareness of my own interests and talents", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); groupSet.add( saveObjectiveGroup("Self-concept", "", itemSet) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("Group activities contributed significantly to my learning", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Collaborative group activities helped me learn the materials", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Working with others in the group helpded me learn more effectively", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); groupSet.add( saveObjectiveGroup("Interaction", "", itemSet) ); evaluationDao.save( new EvalItemGroup(new Date(), EvalConstants.ITEM_GROUP_TYPE_CATEGORY, "Student Development", "Determine how student development is perceived", null, groupSet) ); groupSet = new HashSet(); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("The instructor explained material clearly and understandably", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor handled questions well", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor appeared to have a thorough knowledge of the subject and field", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor taught in a manner that served my needs", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); groupSet.add( saveObjectiveGroup("Skill", "", itemSet) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("The instructor was friendly", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor was permissive and flexible", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor treated students with respect", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); groupSet.add( saveObjectiveGroup("Climate", "", itemSet) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("The instructor suggested specific ways students could improve", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor gave positive feedback when students did especially well", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); itemSet.add( saveScaledExpertItem("The instructor kept students informed of their progress", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_INSTRUCTOR) ); groupSet.add( saveObjectiveGroup("Feedback", "", itemSet) ); evaluationDao.save( new EvalItemGroup(new Date(), EvalConstants.ITEM_GROUP_TYPE_CATEGORY, "Instructor Effectiveness", "Determine the perceived effectiveness of the instructor", null, groupSet) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("Examinations covered the important aspects of the course", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Exams were creative and required original thought", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Exams were reasonable in length and difficulty", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Examination items were clearly worded", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Exam length was appropriate for the time alloted", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); evaluationDao.save( new EvalItemGroup(new Date(), EvalConstants.ITEM_GROUP_TYPE_CATEGORY, "Exams", "Measure the perception of examinations", itemSet, null) ); itemSet = new HashSet(); itemSet.add( saveScaledExpertItem("Assignments were interesting and stimulating", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Assignments made students think", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Assignments required a reasonable amount of time and effort", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Assignments were relevant to what was presented", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); itemSet.add( saveScaledExpertItem("Assignments were graded fairly", null, null, agreeDisagree, EvalConstants.ITEM_CATEGORY_COURSE) ); evaluationDao.save( new EvalItemGroup(new Date(), EvalConstants.ITEM_GROUP_TYPE_CATEGORY, "Assignments", "Measure the perception of out of class assignments", itemSet, null) ); log.info("Preloaded " + evaluationDao.countAll(EvalItem.class) + " evaluation items"); } }
private int evaluateOperationTime(final Entity operationComponent, final boolean includeTpz, final boolean includeAdditionalTime, final Map<Entity, BigDecimal> operationRuns, final Entity productionLine, final boolean maxForWorkstation, final Map<Entity, BigDecimal> productComponentQuantities) { String entityType = operationComponent.getStringField("entityType"); if (L_REFERENCE_TECHNOLOGY.equals(entityType)) { EntityTreeNode actualOperationComponent = operationComponent.getBelongsToField("referenceTechnology") .getTreeField("operationComponents").getRoot(); return evaluateOperationTime(actualOperationComponent, includeTpz, includeAdditionalTime, operationRuns, productionLine, maxForWorkstation, productComponentQuantities); } else if (L_OPERATION.equals(entityType)) { int operationTime = evaluateSingleOperationTime(operationComponent, includeTpz, includeAdditionalTime, operationRuns, productionLine, maxForWorkstation); int offset = 0; for (Entity child : operationComponent.getHasManyField("children")) { int childTime = evaluateOperationTime(child, includeTpz, includeAdditionalTime, operationRuns, productionLine, maxForWorkstation, productComponentQuantities); if ("02specified".equals(child.getStringField("nextOperationAfterProducedType"))) { int childTimeTotal = evaluateSingleOperationTime(child, includeTpz, false, operationRuns, productionLine, true); int childTimeForQuantity = evaluateSingleOperationTimeIncludedNextOperationAfterProducedQuantity(child, includeTpz, false, operationRuns, productionLine, true, productComponentQuantities); int difference = childTimeTotal - childTimeForQuantity; childTime -= difference; } if (childTime > offset) { offset = childTime; } } if (L_TECHNOLOGY_INSTANCE_OPERATION_COMPONENT.equals(operationComponent.getDataDefinition().getName())) { operationComponent.setField("effectiveOperationRealizationTime", operationTime); operationComponent.setField("operationOffSet", offset); operationComponent.getDataDefinition().save(operationComponent); } return offset + operationTime; } throw new IllegalStateException("entityType has to be either operation or referenceTechnology"); }
private int evaluateOperationTime(final Entity operationComponent, final boolean includeTpz, final boolean includeAdditionalTime, final Map<Entity, BigDecimal> operationRuns, final Entity productionLine, final boolean maxForWorkstation, final Map<Entity, BigDecimal> productComponentQuantities) { String entityType = operationComponent.getStringField("entityType"); if (L_REFERENCE_TECHNOLOGY.equals(entityType)) { EntityTreeNode actualOperationComponent = operationComponent.getBelongsToField("referenceTechnology") .getTreeField("operationComponents").getRoot(); return evaluateOperationTime(actualOperationComponent, includeTpz, includeAdditionalTime, operationRuns, productionLine, maxForWorkstation, productComponentQuantities); } else if (L_OPERATION.equals(entityType)) { int operationTime = evaluateSingleOperationTime(operationComponent, includeTpz, false, operationRuns, productionLine, maxForWorkstation); int offset = 0; for (Entity child : operationComponent.getHasManyField("children")) { int childTime = evaluateOperationTime(child, includeTpz, includeAdditionalTime, operationRuns, productionLine, maxForWorkstation, productComponentQuantities); if ("02specified".equals(child.getStringField("nextOperationAfterProducedType"))) { int childTimeTotal = evaluateSingleOperationTime(child, includeTpz, false, operationRuns, productionLine, true); int childTimeForQuantity = evaluateSingleOperationTimeIncludedNextOperationAfterProducedQuantity(child, includeTpz, false, operationRuns, productionLine, true, productComponentQuantities); int difference = childTimeTotal - childTimeForQuantity; childTime -= difference; } if (childTime > offset) { offset = childTime; } } if (L_TECHNOLOGY_INSTANCE_OPERATION_COMPONENT.equals(operationComponent.getDataDefinition().getName())) { operationComponent.setField("effectiveOperationRealizationTime", operationTime); operationComponent.setField("operationOffSet", offset); operationComponent.getDataDefinition().save(operationComponent); } return offset + operationTime; } throw new IllegalStateException("entityType has to be either operation or referenceTechnology"); }
public String getSchemaPage(@RequestParam(value="file", required=false) MultipartFile file, @RequestParam(value="fileUrl", required=false) String fileUrl, @RequestParam(value="firstRowAsHeader", required=false) String firstRowAsHeader, @RequestParam(value="delimiter", required=false) String delimiter, ModelMap model, Principal principal) { User user = (User) ((Authentication) principal).getPrincipal(); ObjectMapper mapper = new ObjectMapper(); try { String data = mapper.writeValueAsString(new String[] { "1", fileUrl }); datastoreService.logUserAction(user.getId(), UserActionLog.ActionCode.GET_SCHEMA_PAGE, data); } catch (Exception e) { logger.debug("Failed to log action", e); } if (file == null && (fileUrl == null || StringUtils.isEmptyOrWhitespaceOnly(fileUrl))) { model.addAttribute("errorMsg", "Null input file or file address."); return "upload"; } String filename = file.getOriginalFilename(); int index = filename.lastIndexOf("."); String type = filename.substring(index + 1); filename = filename.substring(0, index); long size = file.getSize(); logger.debug("UPLOAD FILE: Received {} file. Size {}", filename, size); if (size <= 0) { model.addAttribute("errorMsg", "Cannot determine file size."); return "upload"; } DataParser parser; if (type.equals("xls") || type.equals("xlsx")) { parser = DataParserFactory.getDataParser(FileType.EXCEL); } else if (type.equals("txt")) { parser = DataParserFactory.getDataParser(FileType.TEXT); } else if (type.equals("csv")) { parser = DataParserFactory.getDataParser(FileType.CSV); } else { model.addAttribute("errorMsg", "Unknown file type."); return "upload"; } final String ticket = Utils.getExecutionId(); String tempDataFilePath = logDir + Utils.FILE_SEPARATOR + ticket + Utils.FILE_SEPARATOR + ticket + ".dat"; File tempDataFile = new File(tempDataFilePath); try { if (!tempDataFile.getParentFile().isDirectory()) { tempDataFile.getParentFile().mkdirs(); } List<Object[]> data = parser.parse(file.getInputStream()); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(tempDataFile)); for (Object[] row : data) { os.writeObject(row); } os.close(); model.addAttribute("data", mapper.writeValueAsString(data)); } catch (Exception e) { logger.debug("Failed to write to temporary datafile {}", tempDataFilePath); model.addAttribute("errorMsg", "Failed to parse and save your data."); return "upload"; } try { List<DatasetColumn> schema = parser.parseSchema(file.getInputStream()); model.addAttribute("schema", mapper.writeValueAsString(schema)); } catch(Exception e) { logger.debug("Exception occured when parsing data schema", e); model.addAttribute("errorMsg", "Failed to parse schema."); return "upload"; } model.addAttribute("ticket", ticket); return "schema"; }
public String getSchemaPage(@RequestParam(value="file", required=false) MultipartFile file, @RequestParam(value="fileUrl", required=false) String fileUrl, @RequestParam(value="firstRowAsHeader", required=false) String firstRowAsHeader, @RequestParam(value="delimiter", required=false) String delimiter, ModelMap model, Principal principal) { User user = (User) ((Authentication) principal).getPrincipal(); ObjectMapper mapper = new ObjectMapper(); try { String data = mapper.writeValueAsString(new String[] { "1", fileUrl }); datastoreService.logUserAction(user.getId(), UserActionLog.ActionCode.GET_SCHEMA_PAGE, data); } catch (Exception e) { logger.debug("Failed to log action", e); } if (file == null && (fileUrl == null || StringUtils.isEmptyOrWhitespaceOnly(fileUrl))) { model.addAttribute("errorMsg", "Null input file or file address."); return "upload"; } String filename = file.getOriginalFilename(); int index = filename.lastIndexOf("."); String type = filename.substring(index + 1); filename = filename.substring(0, index); long size = file.getSize(); logger.debug("UPLOAD FILE: Received {} file. Size {}", filename, size); if (size <= 0) { model.addAttribute("errorMsg", "Cannot determine file size."); return "upload"; } DataParser parser; if (type.equals("xls") || type.equals("xlsx")) { parser = DataParserFactory.getDataParser(FileType.EXCEL); } else if (type.equals("txt")) { parser = DataParserFactory.getDataParser(FileType.TEXT); } else if (type.equals("csv")) { parser = DataParserFactory.getDataParser(FileType.CSV); } else { model.addAttribute("errorMsg", "Unknown file type."); return "upload"; } final String ticket = Utils.getExecutionId(); String tempDataFilePath = logDir + Utils.FILE_SEPARATOR + ticket + Utils.FILE_SEPARATOR + ticket + ".dat"; File tempDataFile = new File(tempDataFilePath); try { if (!tempDataFile.getParentFile().isDirectory()) { tempDataFile.getParentFile().mkdirs(); } List<Object[]> data = parser.parse(file.getInputStream()); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(tempDataFile)); for (Object[] row : data) { os.writeObject(row); } os.close(); model.addAttribute("data", mapper.writeValueAsString(data.subList(0, Math.min(100, data.size())))); } catch (Exception e) { logger.debug("Failed to write to temporary datafile {}", tempDataFilePath); model.addAttribute("errorMsg", "Failed to parse and save your data."); return "upload"; } try { List<DatasetColumn> schema = parser.parseSchema(file.getInputStream()); model.addAttribute("schema", mapper.writeValueAsString(schema)); } catch(Exception e) { logger.debug("Exception occured when parsing data schema", e); model.addAttribute("errorMsg", "Failed to parse schema."); return "upload"; } model.addAttribute("ticket", ticket); return "schema"; }
public void test() { assertThat(this.testee, is(not(nullValue()))); this.testee.finest("FINEST"); this.testee.finer("FINER"); this.testee.fine("FINE"); this.testee.config("CONFIG"); this.testee.info("INFO"); this.testee.warning("WARNING"); this.testee.severe("SEVERE"); }
public void test() { assertThat(testee, is(not(nullValue()))); testee.finest("FINEST"); testee.finer("FINER"); testee.fine("FINE"); testee.config("CONFIG"); testee.info("INFO"); testee.warning("WARNING"); testee.severe("SEVERE"); }
@Override public void onModuleLoad() { Score score = ScoreRevolutionary.createScore(); RootPanel container = RootPanel.get("container"); container.add(new Label(findAClef(score, MP.atBeat(0, 1, 0, _0)))); container.add(new Label(findAClef(score, MP.atBeat(1, 1, 0, _0)))); MP mp = MP.atBeat(0, 1, 0, _0); container.add(new Label("Voice at " + mp + ": " + score.getVoice(mp))); }
@Override public void onModuleLoad() { Score score = ScoreRevolutionary.createScore(); RootPanel container = RootPanel.get("container"); container.add(new Label("If you see some text with musical data, it works:")); container.add(new Label(findAClef(score, MP.atBeat(0, 1, 0, _0)))); container.add(new Label(findAClef(score, MP.atBeat(1, 1, 0, _0)))); MP mp = MP.atBeat(0, 1, 0, _0); container.add(new Label("Voice at " + mp + ": " + score.getVoice(mp))); }
public Value eval(Context ctxt) { breakpoint.check(location, ctxt); State state = null; ClassInvariantListener listener = null; if (statedef != null) { state = statedef.getState(); state.doInvariantChecks = false; } else if (classdef != null) { listener = classdef.invlistener; listener.doInvariantChecks = false; } for (AssignmentStatement stmt: assignments) { stmt.eval(ctxt); } if (state != null) { state.doInvariantChecks = true; state.changedValue(location, null, ctxt); } else if (classdef != null) { listener.doInvariantChecks = true; listener.changedValue(location, null, ctxt); } return new VoidValue(); }
public Value eval(Context ctxt) { breakpoint.check(location, ctxt); State state = null; ClassInvariantListener listener = null; if (statedef != null) { state = statedef.getState(); state.doInvariantChecks = false; } else if (classdef != null && classdef.invlistener != null) { listener = classdef.invlistener; listener.doInvariantChecks = false; } for (AssignmentStatement stmt: assignments) { stmt.eval(ctxt); } if (state != null) { state.doInvariantChecks = true; state.changedValue(location, null, ctxt); } else if (listener != null) { listener.doInvariantChecks = true; listener.changedValue(location, null, ctxt); } return new VoidValue(); }
public static BluetoothOppReceiveFileInfo generateFileInfo(Context context, int id) { ContentResolver contentResolver = context.getContentResolver(); Uri contentUri = Uri.parse(BluetoothShare.CONTENT_URI + "/" + id); String filename = null, hint = null; long length = 0; Cursor metadataCursor = contentResolver.query(contentUri, new String[] { BluetoothShare.FILENAME_HINT, BluetoothShare.TOTAL_BYTES, BluetoothShare.MIMETYPE }, null, null, null); if (metadataCursor != null) { try { if (metadataCursor.moveToFirst()) { hint = metadataCursor.getString(0); length = metadataCursor.getInt(1); } } finally { metadataCursor.close(); } } File base = null; StatFs stat = null; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String root = Environment.getExternalStorageDirectory().getPath(); base = new File(root + Constants.DEFAULT_STORE_SUBDIR); if (!base.isDirectory() && !base.mkdir()) { if (D) Log.d(Constants.TAG, "Receive File aborted - can't create base directory " + base.getPath()); return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_FILE_ERROR); } stat = new StatFs(base.getPath()); } else { if (D) Log.d(Constants.TAG, "Receive File aborted - no external storage"); return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_ERROR_NO_SDCARD); } if (stat.getBlockSize() * ((long)stat.getAvailableBlocks() - 4) < length) { if (D) Log.d(Constants.TAG, "Receive File aborted - not enough free space"); return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_ERROR_SDCARD_FULL); } filename = choosefilename(hint); String extension = null; int dotIndex = filename.indexOf('.'); if (dotIndex < 0) { return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_FILE_ERROR); } else { extension = filename.substring(dotIndex); filename = filename.substring(0, dotIndex); } filename = base.getPath() + File.separator + filename; String fullfilename = chooseUniquefilename(filename, extension); if (V) Log.v(Constants.TAG, "Generated received filename " + fullfilename); if (fullfilename != null) { try { new FileOutputStream(fullfilename).close(); int index = fullfilename.lastIndexOf('/') + 1; if (index > 0) { String displayName = fullfilename.substring(index); if (V) Log.v(Constants.TAG, "New display name " + displayName); ContentValues updateValues = new ContentValues(); updateValues.put(BluetoothShare.FILENAME_HINT, displayName); context.getContentResolver().update(contentUri, updateValues, null, null); } return new BluetoothOppReceiveFileInfo(fullfilename, length, new FileOutputStream( fullfilename), 0); } catch (IOException e) { if (D) Log.e(Constants.TAG, "Error when creating file " + fullfilename); return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_FILE_ERROR); } } else { return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_FILE_ERROR); } }
public static BluetoothOppReceiveFileInfo generateFileInfo(Context context, int id) { ContentResolver contentResolver = context.getContentResolver(); Uri contentUri = Uri.parse(BluetoothShare.CONTENT_URI + "/" + id); String filename = null, hint = null; long length = 0; Cursor metadataCursor = contentResolver.query(contentUri, new String[] { BluetoothShare.FILENAME_HINT, BluetoothShare.TOTAL_BYTES, BluetoothShare.MIMETYPE }, null, null, null); if (metadataCursor != null) { try { if (metadataCursor.moveToFirst()) { hint = metadataCursor.getString(0); length = metadataCursor.getInt(1); } } finally { metadataCursor.close(); } } File base = null; StatFs stat = null; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String root = Environment.getExternalStorageDirectory().getPath(); base = new File(root + Constants.DEFAULT_STORE_SUBDIR); if (!base.isDirectory() && !base.mkdir()) { if (D) Log.d(Constants.TAG, "Receive File aborted - can't create base directory " + base.getPath()); return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_FILE_ERROR); } stat = new StatFs(base.getPath()); } else { if (D) Log.d(Constants.TAG, "Receive File aborted - no external storage"); return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_ERROR_NO_SDCARD); } if (stat.getBlockSize() * ((long)stat.getAvailableBlocks() - 4) < length) { if (D) Log.d(Constants.TAG, "Receive File aborted - not enough free space"); return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_ERROR_SDCARD_FULL); } filename = choosefilename(hint); if (filename == null) { return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_FILE_ERROR); } String extension = null; int dotIndex = filename.indexOf('.'); if (dotIndex < 0) { return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_FILE_ERROR); } else { extension = filename.substring(dotIndex); filename = filename.substring(0, dotIndex); } filename = base.getPath() + File.separator + filename; String fullfilename = chooseUniquefilename(filename, extension); if (V) Log.v(Constants.TAG, "Generated received filename " + fullfilename); if (fullfilename != null) { try { new FileOutputStream(fullfilename).close(); int index = fullfilename.lastIndexOf('/') + 1; if (index > 0) { String displayName = fullfilename.substring(index); if (V) Log.v(Constants.TAG, "New display name " + displayName); ContentValues updateValues = new ContentValues(); updateValues.put(BluetoothShare.FILENAME_HINT, displayName); context.getContentResolver().update(contentUri, updateValues, null, null); } return new BluetoothOppReceiveFileInfo(fullfilename, length, new FileOutputStream( fullfilename), 0); } catch (IOException e) { if (D) Log.e(Constants.TAG, "Error when creating file " + fullfilename); return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_FILE_ERROR); } } else { return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_FILE_ERROR); } }
public void export(int type) { if(type != 1 || type !=2) { return; } File file = new File(plugin.getDataFolder(), "export-type1.txt"); try { PrintWriter pw = new PrintWriter(new FileWriter(file)); Set<String> keys = config.getConfigurationSection("emails").getKeys(false); for(String key : keys) { String line = ""; if(type == 1) { line = key+","+config.getString(root+key); } else if(type == 2) { line = config.getString(root+key); } pw.println(line); } pw.close(); plugin.getLogger().info("Export file created at "+file.getPath()); } catch (Exception e) { plugin.getLogger().severe("Could not export emails"); e.printStackTrace(); return; } }
public void export(int type) { if(!(type == 1 || type == 2)) { plugin.getLogger().info("Incorrect export type"); return; } File file = new File(plugin.getDataFolder(), "export-type1.txt"); try { PrintWriter pw = new PrintWriter(new FileWriter(file)); Set<String> keys = config.getConfigurationSection("emails").getKeys(false); for(String key : keys) { String line = ""; if(type == 1) { line = key+","+config.getString(root+key); } else if(type == 2) { line = config.getString(root+key); } pw.println(line); } pw.close(); plugin.getLogger().info("Export file created at "+file.getPath()); } catch (Exception e) { plugin.getLogger().severe("Could not export emails"); e.printStackTrace(); return; } }
private static void setUpLogging() { try { FileHandler handler = new FileHandler("logs/log-grabber.log", 100000, 5, true); handler.setFormatter(new SimpleFormatter()); Logger logger = Logger.getLogger("com.dnb.loggrabber"); logger.addHandler(handler); logger.setUseParentHandlers(false); logger.setLevel(Level.ALL); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to initialize logger handler.", e); } }
private static void setUpLogging() { try { FileHandler handler = new FileHandler("logs/log-grabber.log", 100000, 5, true); handler.setFormatter(new SimpleFormatter()); Logger logger = Logger.getLogger("com.clusterclient"); logger.addHandler(handler); logger.setUseParentHandlers(false); logger.setLevel(Level.ALL); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to initialize logger handler.", e); } }
public void tradeMarketOrder(Order o) { createOrder(o, false); if (startingPeriod) { cancelOrder(o); return; } long price = 0; long aggressorID = o.getCreatorID(); int totalVolumeTraded = 0; int quantityToRid = o.getCurrentQuant(); if (o.isBuyOrder()) { ArrayList<Order> topSells = topSellOrders(); while (!topSells.isEmpty()) { price = topSells.get(0).getPrice(); int currentVolumeTraded = trade(o, topSells.get(0)); totalVolumeTraded += currentVolumeTraded; agentMap.get(topSells.get(0).getCreatorID()).setLastOrderTraded(true, currentVolumeTraded); if (totalVolumeTraded < quantityToRid) { topSells.remove(0); } else { break; } } agentMap.get(aggressorID).setLastOrderTraded(true, totalVolumeTraded); lastAgVolumeBuySide += totalVolumeTraded; } else { ArrayList<Order> topBuys = topBuyOrders(); while (!topBuys.isEmpty()) { price = topBuys.get(0).getPrice(); int currentVolumeTraded = trade(o, topBuys.get(0)); totalVolumeTraded += currentVolumeTraded; agentMap.get(topBuys.get(0).getCreatorID()).setLastOrderTraded(true, currentVolumeTraded); if (totalVolumeTraded < quantityToRid) { topBuys.remove(0); } else { break; } } agentMap.get(aggressorID).setLastOrderTraded(true, totalVolumeTraded); lastAgVolumeSellSide += totalVolumeTraded; } System.out.print("Market ORDER "); logTrade(o, price, totalVolumeTraded); }
public void tradeMarketOrder(Order o) { createOrder(o, true); if (startingPeriod) { cancelOrder(o); return; } long price = 0; long aggressorID = o.getCreatorID(); int totalVolumeTraded = 0; int quantityToRid = o.getCurrentQuant(); if (o.isBuyOrder()) { ArrayList<Order> topSells = topSellOrders(); if (topSells.isEmpty()) { cancelOrder(o); return; } while (!topSells.isEmpty()) { price = topSells.get(0).getPrice(); int currentVolumeTraded = trade(o, topSells.get(0)); totalVolumeTraded += currentVolumeTraded; agentMap.get(topSells.get(0).getCreatorID()).setLastOrderTraded(true, currentVolumeTraded); if (totalVolumeTraded < quantityToRid) { topSells.remove(0); } else { break; } } agentMap.get(aggressorID).setLastOrderTraded(true, totalVolumeTraded); lastAgVolumeBuySide += totalVolumeTraded; } else { ArrayList<Order> topBuys = topBuyOrders(); if (topBuys.isEmpty()) { cancelOrder(o); return; } while (!topBuys.isEmpty()) { price = topBuys.get(0).getPrice(); int currentVolumeTraded = trade(o, topBuys.get(0)); totalVolumeTraded += currentVolumeTraded; agentMap.get(topBuys.get(0).getCreatorID()).setLastOrderTraded(true, currentVolumeTraded); if (totalVolumeTraded < quantityToRid) { topBuys.remove(0); } else { break; } } agentMap.get(aggressorID).setLastOrderTraded(true, totalVolumeTraded); lastAgVolumeSellSide += totalVolumeTraded; } System.out.print("Market ORDER "); logTrade(o, price, totalVolumeTraded); }
public void doMoveToWaitInitialRole(MockStorageSourceConfig cfg) throws Exception { moveToWaitDescriptionStatReply(); resetChannel(); replay(channel); OFStatisticsReply sr = (OFStatisticsReply)BasicFactory.getInstance() .getMessage(OFType.STATS_REPLY); sr.setStatisticType(OFStatisticsType.DESC); OFDescriptionStatistics desc = new OFDescriptionStatistics(); desc.setDatapathDescription("Datapath Description"); desc.setHardwareDescription("Hardware Description"); desc.setManufacturerDescription("Manufacturer Description"); desc.setSerialNumber("Serial Number"); desc.setSoftwareDescription("Software Description"); sr.setStatistics(Collections.singletonList(desc)); setupMessageEvent(Collections.<OFMessage>singletonList(sr)); setupMockStorageSource(cfg); reset(sw); sw.setChannel(channel); expectLastCall().once(); sw.setFloodlightProvider(controller); expectLastCall().once(); sw.setThreadPoolService(threadPool); expectLastCall().once(); sw.setDebugCounterService(debugCounterService); expectLastCall().once(); sw.setFeaturesReply(featuresReply); expectLastCall().once(); sw.setConnected(true); expectLastCall().once(); sw.getStringId(); expectLastCall().andReturn(cfg.dpid).atLeastOnce(); sw.isWriteThrottleEnabled(); expectLastCall().andReturn(false).anyTimes(); sw.setAccessFlowPriority(ACCESS_PRIORITY); expectLastCall().once(); sw.setCoreFlowPriority(CORE_PRIORITY); expectLastCall().once(); if (cfg.isPresent) sw.setAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH, cfg.isCoreSwitch); replay(sw); reset(controller); expect(controller.getDebugCounter()).andReturn(debugCounterService) .once(); controller.flushAll(); expectLastCall().once(); expect(controller.getThreadPoolService()) .andReturn(threadPool).once(); expect(controller.getOFSwitchInstance(eq(desc))) .andReturn(sw).once(); expect(controller.getCoreFlowPriority()) .andReturn(CORE_PRIORITY).once(); expect(controller.getAccessFlowPriority()) .andReturn(ACCESS_PRIORITY).once(); controller.addSwitchChannelAndSendInitialRole(handler); expectLastCall().once(); expect(controller.getStorageSourceService()) .andReturn(storageSource).atLeastOnce(); replay(controller); handler.messageReceived(ctx, messageEvent); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); verifyStorageSource(); }
public void doMoveToWaitInitialRole(MockStorageSourceConfig cfg) throws Exception { moveToWaitDescriptionStatReply(); resetChannel(); replay(channel); OFStatisticsReply sr = (OFStatisticsReply)BasicFactory.getInstance() .getMessage(OFType.STATS_REPLY); sr.setStatisticType(OFStatisticsType.DESC); OFDescriptionStatistics desc = new OFDescriptionStatistics(); desc.setDatapathDescription("Datapath Description"); desc.setHardwareDescription("Hardware Description"); desc.setManufacturerDescription("Manufacturer Description"); desc.setSerialNumber("Serial Number"); desc.setSoftwareDescription("Software Description"); sr.setStatistics(Collections.singletonList(desc)); setupMessageEvent(Collections.<OFMessage>singletonList(sr)); setupMockStorageSource(cfg); reset(sw); sw.setChannel(channel); expectLastCall().once(); sw.setFloodlightProvider(controller); expectLastCall().once(); sw.setThreadPoolService(threadPool); expectLastCall().once(); sw.setDebugCounterService(debugCounterService); expectLastCall().once(); sw.setFeaturesReply(featuresReply); expectLastCall().once(); sw.setConnected(true); expectLastCall().once(); sw.getStringId(); expectLastCall().andReturn(cfg.dpid).atLeastOnce(); sw.isWriteThrottleEnabled(); expectLastCall().andReturn(false).anyTimes(); sw.setAccessFlowPriority(ACCESS_PRIORITY); expectLastCall().once(); sw.setCoreFlowPriority(CORE_PRIORITY); expectLastCall().once(); sw.startDriverHandshake(); expectLastCall().once(); sw.isDriverHandshakeComplete(); expectLastCall().andReturn(true).once(); if (cfg.isPresent) sw.setAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH, cfg.isCoreSwitch); replay(sw); reset(controller); expect(controller.getDebugCounter()).andReturn(debugCounterService) .once(); controller.flushAll(); expectLastCall().once(); expect(controller.getThreadPoolService()) .andReturn(threadPool).once(); expect(controller.getOFSwitchInstance(eq(desc))) .andReturn(sw).once(); expect(controller.getCoreFlowPriority()) .andReturn(CORE_PRIORITY).once(); expect(controller.getAccessFlowPriority()) .andReturn(ACCESS_PRIORITY).once(); controller.addSwitchChannelAndSendInitialRole(handler); expectLastCall().once(); expect(controller.getStorageSourceService()) .andReturn(storageSource).atLeastOnce(); replay(controller); handler.messageReceived(ctx, messageEvent); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); verifyStorageSource(); }
public String getName(int lineA, int lineB, int lineC) { if (lineA <= 0 || lineB <= 0 || lineC <= 0) { throw new IllegalArgumentException(); } if (lineA == lineB && lineB == lineC) { return "���O�p�`"; } else if (lineA == lineB || lineB == lineC || lineC == lineA) { return "�񓙕ӎO�p�`"; } else { return "�s���ӎO�p�`"; } }
public String getName(int lineA, int lineB, int lineC) { if (lineA <= 0 || lineB <= 0 || lineC <= 0) { throw new IllegalArgumentException(); } if (lineA == lineB && lineB == lineC) { return ""; } else if (lineA == lineB || lineB == lineC || lineC == lineA) { return ""; } else { return ""; } }
private static void getTSKData(String standardPath, List<String> img) { String tsk_loc; if (System.getProperty("os.name").contains("Windows")) { tsk_loc = "\\Users\\" + System.getProperty("user.name") + "\\Documents\\GitHub\\sleuthkit\\win32\\Release\\tsk_gettimes"; } else { return; } String[] cmd = {tsk_loc, img.get(0)}; try { Process p = Runtime.getRuntime().exec(cmd); Scanner read = new Scanner(p.getInputStream()); Scanner error1 = new Scanner(p.getErrorStream()); FileWriter out = new FileWriter(standardPath); while (read.hasNextLine()) { String line = read.nextLine(); line = line.replace(" (deleted)", ""); line = line.replace("(null)", ""); String[] linecontents = line.split("\\|"); String metaaddrcon = linecontents[2]; String mtad = metaaddrcon.split("\\-")[0]; line = line.replace(metaaddrcon, mtad); out.append(line); out.flush(); out.append("\n"); } runSort(standardPath); } catch (Exception ex) { logg.log(Level.SEVERE, "Failed to run CPP program", ex); } java.io.File xfile = new java.io.File(standardPath.replace(".txt", DataModelTestSuite.EX + ".txt")); try { xfile.createNewFile(); } catch (IOException ex) { logg.log(Level.SEVERE, "Failed to create exceptions file", ex); } }
private static void getTSKData(String standardPath, List<String> img) { String tsk_loc; java.io.File up = new java.io.File(System.getProperty("user.dir")); up = up.getParentFile(); up = up.getParentFile(); if (System.getProperty("os.name").contains("Windows")) { tsk_loc = up.getAbsolutePath() + "\\win32\\Release\\tsk_gettimes"; } else { return; } String[] cmd = {tsk_loc, img.get(0)}; try { Process p = Runtime.getRuntime().exec(cmd); Scanner read = new Scanner(p.getInputStream()); Scanner error1 = new Scanner(p.getErrorStream()); FileWriter out = new FileWriter(standardPath); while (read.hasNextLine()) { String line = read.nextLine(); line = line.replace(" (deleted)", ""); line = line.replace("(null)", ""); String[] linecontents = line.split("\\|"); String metaaddrcon = linecontents[2]; String mtad = metaaddrcon.split("\\-")[0]; line = line.replace(metaaddrcon, mtad); out.append(line); out.flush(); out.append("\n"); } runSort(standardPath); } catch (Exception ex) { logg.log(Level.SEVERE, "Failed to run CPP program", ex); } java.io.File xfile = new java.io.File(standardPath.replace(".txt", DataModelTestSuite.EX + ".txt")); try { xfile.createNewFile(); } catch (IOException ex) { logg.log(Level.SEVERE, "Failed to create exceptions file", ex); } }
public static void draw(GuiISOCraft gui, TileEntityISOCraftMachine tile, Minecraft mc, int xpos, int ypos, int xcur, int ycur) { mc.getTextureManager().bindTexture(Reference.Gui_Utils_loc); double e = ((double) tile.getEnergyStored(null) / tile.getMaxEnergyStored(null)); int energyPos = (int) Math.floor(e * 58); gui.drawTexturedModalRect(xpos, ypos - energyPos, 0, (57 - energyPos), 5, energyPos); String tooltip = tile.getEnergyStored(null) + "/12000 rf"; gui.drawTooltip(Arrays.asList(new String[] { tooltip }), 164, 13, xcur, ycur, 5, 58); }
public static void draw(GuiISOCraft gui, TileEntityISOCraftMachine tile, Minecraft mc, int xpos, int ypos, int xcur, int ycur) { mc.getTextureManager().bindTexture(Reference.Gui_Utils_loc); double e = ((double) tile.getEnergyStored(null) / tile.getMaxEnergyStored(null)); int energyPos = (int) Math.floor(e * 58); gui.drawTexturedModalRect(xpos, ypos - energyPos, 0, (58 - energyPos), 5, energyPos); String tooltip = tile.getEnergyStored(null) + "/" + tile.getMaxEnergyStored(null) + "rf"; gui.drawTooltip(Arrays.asList(new String[] { tooltip }), 164, 13, xcur, ycur, 5, 58); }
public void testFactoryFeedforward() { String architecture = "?:B->TANH->3->LINEAR->?:B"; MLMethodFactory factory = new MLMethodFactory(); BasicNetwork network = (BasicNetwork)factory.create(MLMethodFactory.TYPE_FEEDFORWARD, architecture, 1, 4); Assert.assertTrue(network.isLayerBiased(0)); Assert.assertFalse(network.isLayerBiased(1)); Assert.assertTrue(network.isLayerBiased(2)); Assert.assertEquals(3, network.getLayerCount()); Assert.assertTrue(network.getActivation(0) instanceof ActivationTANH ); Assert.assertTrue(network.getActivation(1) instanceof ActivationLinear ); Assert.assertTrue(network.getActivation(2) instanceof ActivationLinear ); Assert.assertEquals(18,network.encodedArrayLength()); Assert.assertEquals(1,network.getLayerNeuronCount(0)); Assert.assertEquals(3,network.getLayerNeuronCount(1)); Assert.assertEquals(4,network.getLayerNeuronCount(2)); }
public void testFactoryFeedforward() { String architecture = "?:B->TANH->3->LINEAR->?:B"; MLMethodFactory factory = new MLMethodFactory(); BasicNetwork network = (BasicNetwork)factory.create(MLMethodFactory.TYPE_FEEDFORWARD, architecture, 1, 4); Assert.assertTrue(network.isLayerBiased(0)); Assert.assertFalse(network.isLayerBiased(1)); Assert.assertTrue(network.isLayerBiased(2)); Assert.assertEquals(3, network.getLayerCount()); Assert.assertTrue(network.getActivation(0) instanceof ActivationLinear ); Assert.assertTrue(network.getActivation(1) instanceof ActivationTANH ); Assert.assertTrue(network.getActivation(2) instanceof ActivationLinear ); Assert.assertEquals(18,network.encodedArrayLength()); Assert.assertEquals(1,network.getLayerNeuronCount(0)); Assert.assertEquals(3,network.getLayerNeuronCount(1)); Assert.assertEquals(4,network.getLayerNeuronCount(2)); }
public Boolean run(CommandSender sender, String[] args) { if (args.length < 1) { Util.Message("Usage: /jail [Name] (t:time) (j:Jail name) (c:Cell name) (r:Reason) (m)", sender); return true; } if (Jail.zones.size() < 1) { Util.Message(InputOutput.global.getString(Setting.MessageNoJail.getString()), sender); return true; } String playerName = args[0].toLowerCase(); int time = InputOutput.global.getInt(Setting.DefaultJailTime.getString()); String jailname = ""; String cellname = ""; String reason = ""; Boolean muted = InputOutput.global.getBoolean(Setting.AutomaticMute.getString()); for (int i = 1; i < args.length; i++) { String line = args[i]; if (Util.isInteger(line)) time = Integer.parseInt(line); else if (line.startsWith("j:")) jailname = line.substring(2); else if (line.startsWith("c:")) cellname = line.substring(2); else if (line.equals("m")) muted = !muted; else if (line.startsWith("r:")) { if (line.startsWith("r:\"")) { reason = line.substring(3); while (!line.endsWith("\"")) { i++; if (i >= args.length) { Util.Message("Usage: /jail [Name] (t:time) (j:Jail name) (c:Cell name) (r:Reason) (m)", sender); return true; } line = args[i]; if (line.endsWith("\"")) reason += " " + line.substring(0, line.length() - 1); else reason += " " + line; } } else reason = line.substring(2); int maxReason = InputOutput.global.getInt(Setting.MaximumReasonLength.getString()); if (maxReason > 250) maxReason = 250; if (reason.length() > maxReason) { Util.Message(InputOutput.global.getString(Setting.MessageTooLongReason.getString()), sender); return true; } } } Player player = Util.getPlayer(playerName, true); if (player == null && !Util.playerExists(playerName)) { Util.Message(InputOutput.global.getString(Setting.MessageNoJail.getString()).replace("<Player>", playerName), sender); return true; } else if (player != null) playerName = player.getName().toLowerCase(); JailPrisoner prisoner = new JailPrisoner(playerName, time * 6, jailname, cellname, false, "", reason, muted, "", sender instanceof Player ? ((Player) sender).getName() : "console", ""); PrisonerManager.PrepareJail(prisoner, player); String message; if (player == null) message = InputOutput.global.getString(Setting.MessagePrisonerOffline.getString()); else message = InputOutput.global.getString(Setting.MessagePrisonerJailed.getString()); message = prisoner.parseTags(message); Util.Message(message, sender); return true; }
public Boolean run(CommandSender sender, String[] args) { if (args.length < 1) { Util.Message("Usage: /jail [Name] (time) (j:Jail name) (c:Cell name) (r:Reason) (m)", sender); return true; } if (Jail.zones.size() < 1) { Util.Message(InputOutput.global.getString(Setting.MessageNoJail.getString()), sender); return true; } String playerName = args[0].toLowerCase(); int time = InputOutput.global.getInt(Setting.DefaultJailTime.getString()); String jailname = ""; String cellname = ""; String reason = ""; Boolean muted = InputOutput.global.getBoolean(Setting.AutomaticMute.getString()); for (int i = 1; i < args.length; i++) { String line = args[i]; if (Util.isInteger(line)) time = Integer.parseInt(line); else if (line.startsWith("j:")) jailname = line.substring(2); else if (line.startsWith("c:")) cellname = line.substring(2); else if (line.equals("m")) muted = !muted; else if (line.startsWith("r:")) { if (line.startsWith("r:\"")) { reason = line.substring(3); while (!line.endsWith("\"")) { i++; if (i >= args.length) { Util.Message("Usage: /jail [Name] (t:time) (j:Jail name) (c:Cell name) (r:Reason) (m)", sender); return true; } line = args[i]; if (line.endsWith("\"")) reason += " " + line.substring(0, line.length() - 1); else reason += " " + line; } } else reason = line.substring(2); int maxReason = InputOutput.global.getInt(Setting.MaximumReasonLength.getString()); if (maxReason > 250) maxReason = 250; if (reason.length() > maxReason) { Util.Message(InputOutput.global.getString(Setting.MessageTooLongReason.getString()), sender); return true; } } } Player player = Util.getPlayer(playerName, true); if (player == null && !Util.playerExists(playerName)) { Util.Message(InputOutput.global.getString(Setting.MessageNoJail.getString()).replace("<Player>", playerName), sender); return true; } else if (player != null) playerName = player.getName().toLowerCase(); JailPrisoner prisoner = new JailPrisoner(playerName, time * 6, jailname, cellname, false, "", reason, muted, "", sender instanceof Player ? ((Player) sender).getName() : "console", ""); PrisonerManager.PrepareJail(prisoner, player); String message; if (player == null) message = InputOutput.global.getString(Setting.MessagePrisonerOffline.getString()); else message = InputOutput.global.getString(Setting.MessagePrisonerJailed.getString()); message = prisoner.parseTags(message); Util.Message(message, sender); return true; }
public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive "+intent.getAction()); if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) { Log.d(TAG, "stop service"); Intent xmppServiceIntent = new Intent(context, XMPPService.class); xmppServiceIntent.setAction("de.hdmstuttgart.yaxim.XMPPSERVICE"); context.stopService(xmppServiceIntent); } else if (intent.getAction().equals(android.net.ConnectivityManager.CONNECTIVITY_ACTION)) { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); Log.d(TAG, "ACTIVE NetworkInfo: "+(networkInfo != null ? networkInfo.toString() : "NONE")); if (((networkInfo == null) && (networkType != -1)) || ((networkInfo != null) && (networkInfo.isConnected() == false) && (networkInfo.getType() == networkType))) { Log.d(TAG, "we got disconnected"); networkType = -1; Intent xmppServiceIntent = new Intent(context, XMPPService.class); xmppServiceIntent.setAction("de.hdmstuttgart.yaxim.XMPPSERVICE"); xmppServiceIntent.putExtra("disconnect", true); context.startService(xmppServiceIntent); } if ((networkInfo != null) && (networkInfo.isConnected() == true) && (networkInfo.getType() != networkType)) { Log.d(TAG, "we got connected"); networkType = networkInfo.getType(); Intent xmppServiceIntent = new Intent(context, XMPPService.class); xmppServiceIntent.setAction("de.hdmstuttgart.yaxim.XMPPSERVICE"); xmppServiceIntent.putExtra("reconnect", true); context.startService(xmppServiceIntent); } else if ((networkInfo != null) && (networkInfo.isConnected() == true) && (networkInfo.getType() == networkType)) { Log.d(TAG, "we stay connected, sending a ping"); Intent xmppServiceIntent = new Intent(context, XMPPService.class); xmppServiceIntent.setAction("de.hdmstuttgart.yaxim.XMPPSERVICE"); xmppServiceIntent.putExtra("ping", true); context.startService(xmppServiceIntent); } } }
public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive "+intent.getAction()); if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) { Log.d(TAG, "stop service"); Intent xmppServiceIntent = new Intent(context, XMPPService.class); xmppServiceIntent.setAction("de.hdmstuttgart.yaxim.XMPPSERVICE"); context.stopService(xmppServiceIntent); } else if (intent.getAction().equals(android.net.ConnectivityManager.CONNECTIVITY_ACTION)) { org.xbill.DNS.ResolverConfig.refresh(); ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); Log.d(TAG, "ACTIVE NetworkInfo: "+(networkInfo != null ? networkInfo.toString() : "NONE")); if (((networkInfo == null) && (networkType != -1)) || ((networkInfo != null) && (networkInfo.isConnected() == false) && (networkInfo.getType() == networkType))) { Log.d(TAG, "we got disconnected"); networkType = -1; Intent xmppServiceIntent = new Intent(context, XMPPService.class); xmppServiceIntent.setAction("de.hdmstuttgart.yaxim.XMPPSERVICE"); xmppServiceIntent.putExtra("disconnect", true); context.startService(xmppServiceIntent); } if ((networkInfo != null) && (networkInfo.isConnected() == true) && (networkInfo.getType() != networkType)) { Log.d(TAG, "we got connected"); networkType = networkInfo.getType(); Intent xmppServiceIntent = new Intent(context, XMPPService.class); xmppServiceIntent.setAction("de.hdmstuttgart.yaxim.XMPPSERVICE"); xmppServiceIntent.putExtra("reconnect", true); context.startService(xmppServiceIntent); } else if ((networkInfo != null) && (networkInfo.isConnected() == true) && (networkInfo.getType() == networkType)) { Log.d(TAG, "we stay connected, sending a ping"); Intent xmppServiceIntent = new Intent(context, XMPPService.class); xmppServiceIntent.setAction("de.hdmstuttgart.yaxim.XMPPSERVICE"); xmppServiceIntent.putExtra("ping", true); context.startService(xmppServiceIntent); } } }
public void start() throws Exception { modProps = new ArrayList(); camera = new Camera(); try { CharDeviceUtils.openDeviceWithRetry(camera, CAMERA_DEVICE_NODE, 2); } catch (IOException e) { String errormsg = "Unable to open camera device node: " + CAMERA_DEVICE_NODE + "\n trying again..."; logService.log(LogService.LOG_ERROR, errormsg); throw e; } cc = new CameraControl(); try { CharDeviceUtils.openDeviceWithRetry(cc, CAMERA_CONTROL_DEVICE_NODE, 2); } catch (IOException e){ String errormsg = "Unable to open camera device node: " + CAMERA_CONTROL_DEVICE_NODE + "\n trying again..."; logService.log(LogService.LOG_ERROR, errormsg); throw e; } cameraControl = new CameraModuleControl(cc); cameraControlRef = context.registerService(ICameraModuleControl.class.getName(), cameraControl, createRemotableProperties(null)); moduleControl = context.registerService(IModuleControl.class.getName(), this, createRemotableProperties(null)); cameraService = context.registerService(ICameraDevice.class.getName(), this, createRemotableProperties(null)); ledRef = context.registerService(IModuleLEDController.class.getName(), cameraControl, createRemotableProperties(null)); bep = new CameraInputEventProvider(DEVNODE_INPUT_DEVICE, logService); bep.start(); bepReg = context.registerService(ICameraButtonEventProvider.class.getName(), bep, createRemotableProperties(getButtonServiceProperties())); regionKey = StatusBarUtils.displayImage(context, icon, this.getModuleName()); List wsProviders = new ArrayList(); wsProviders.add(this); wsTracker = PublicWSAdminTracker.createTracker(context, wsProviders); }
public void start() throws Exception { modProps = new ArrayList(); camera = new Camera(); try { CharDeviceUtils.openDeviceWithRetry(camera, CAMERA_DEVICE_NODE, 2); } catch (IOException e) { String errormsg = "Unable to open camera device node: " + CAMERA_DEVICE_NODE + "\n trying again..."; logService.log(LogService.LOG_ERROR, errormsg); throw e; } cc = new CameraControl(); try { CharDeviceUtils.openDeviceWithRetry(cc, CAMERA_CONTROL_DEVICE_NODE, 2); } catch (IOException e){ String errormsg = "Unable to open camera device node: " + CAMERA_CONTROL_DEVICE_NODE + "\n trying again..."; logService.log(LogService.LOG_ERROR, errormsg); throw e; } cameraControl = new CameraModuleControl(cc); cameraControlRef = context.registerService(ICameraModuleControl.class.getName(), cameraControl, createRemotableProperties(null)); moduleControl = context.registerService(IModuleControl.class.getName(), this, null); cameraService = context.registerService(ICameraDevice.class.getName(), this, createRemotableProperties(null)); ledRef = context.registerService(IModuleLEDController.class.getName(), cameraControl, createRemotableProperties(null)); bep = new CameraInputEventProvider(DEVNODE_INPUT_DEVICE, logService); bep.start(); bepReg = context.registerService(ICameraButtonEventProvider.class.getName(), bep, createRemotableProperties(getButtonServiceProperties())); regionKey = StatusBarUtils.displayImage(context, icon, this.getModuleName()); List wsProviders = new ArrayList(); wsProviders.add(this); wsTracker = PublicWSAdminTracker.createTracker(context, wsProviders); }
public void apply(Request request, Response response) { try { if (name != null) { setContentTypeIfNotSet(response, MimeTypes.getContentType(name)); } if (!response.headers.containsKey("Content-Disposition")) { if (inline) { if (name == null) { response.setHeader("Content-Disposition", "inline"); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + name + "\""); } } else if (name == null) { response.setHeader("Content-Disposition", "attachment"); } else { response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\""); } } if (file != null) { if (!file.exists()) { throw new UnexpectedException("Your file buffer does not exists"); } if (!file.canRead()) { throw new UnexpectedException("Can't read your file buffer"); } if (!file.isFile()) { throw new UnexpectedException("Your file buffer is not a file"); } response.direct = file; } else { byte[] buffer = new byte[8092]; int count = 0; while ((count = is.read(buffer)) > 0) { response.out.write(buffer, 0, count); } is.close(); } } catch (Exception e) { throw new UnexpectedException(e); } }
public void apply(Request request, Response response) { try { if (name != null) { setContentTypeIfNotSet(response, MimeTypes.getContentType(name)); } if (!response.headers.containsKey("Content-Disposition")) { if (inline) { if (name == null) { response.setHeader("Content-Disposition", "inline"); } else { response.setHeader("Content-Disposition", "inline; filename*=utf-8''" + encoder.encode(name, "utf-8") + "; filename=\"" + encoder.encode(name, "utf-8") + "\""); } } else if (name == null) { response.setHeader("Content-Disposition", "attachment"); } else { response.setHeader("Content-Disposition", "attachment; filename*=utf-8''" + encoder.encode(name, "utf-8") + "; filename=\"" + encoder.encode(name, "utf-8") + "\""); } } if (file != null) { if (!file.exists()) { throw new UnexpectedException("Your file buffer does not exists"); } if (!file.canRead()) { throw new UnexpectedException("Can't read your file buffer"); } if (!file.isFile()) { throw new UnexpectedException("Your file buffer is not a file"); } response.direct = file; } else { byte[] buffer = new byte[8092]; int count = 0; while ((count = is.read(buffer)) > 0) { response.out.write(buffer, 0, count); } is.close(); } } catch (Exception e) { throw new UnexpectedException(e); } }
public void worldReset(MVAResetFinishedEvent event) { World world = Bukkit.getWorld(event.getWorld()); if (world != null && plugin.config().get(CRConfig.RESET_WORLDS).contains(world.getName())) { Logging.info("Restocking all chests for reset world.. This may take a moment"); plugin.getChestManager().restockAllChests(world, null); } }
public void worldReset(MVAResetFinishedEvent event) { World world = Bukkit.getWorld(event.getWorld()); if (world != null && plugin.config().getList(CRConfig.RESET_WORLDS).contains(world.getName())) { Logging.info("Restocking all chests for reset world.. This may take a moment"); plugin.getChestManager().restockAllChests(world, null); } }
public EventImpl(byte[] s, long timestamp, Priority pri, long nanoTime, String host, Map<String, byte[]> fields) { super(fields); Preconditions.checkNotNull(s, "Failed when attempting to create event with null body"); Preconditions.checkArgument(s.length <= MAX_BODY_SIZE, "Failed when " + "attempting to create event with body with length (" + s.length + ") > max body size (" + MAX_BODY_SIZE + "). You may want to " + "increase flume.event.max.size.bytes in your flume-site.xml file"); Preconditions.checkNotNull(pri, "Failed when atttempt to " + "create event with null priority"); this.body = s; this.timestamp = timestamp; this.pri = pri; this.nanos = nanoTime; this.host = host; }
public EventImpl(byte[] s, long timestamp, Priority pri, long nanoTime, String host, Map<String, byte[]> fields) { super(fields); Preconditions.checkNotNull(s, "Failed when attempting to create event with null body"); Preconditions.checkArgument(s.length <= MAX_BODY_SIZE, "Failed when " + "attempting to create event with body with length (" + s.length + ") > max body size (" + MAX_BODY_SIZE + "). You may want to " + "increase flume.event.max.size.bytes in your flume-site.xml file"); Preconditions.checkNotNull(pri, "Failed when atttempting to " + "create event with null priority"); this.body = s; this.timestamp = timestamp; this.pri = pri; this.nanos = nanoTime; this.host = host; }
public boolean preHandle(HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception { String clientID=null; String sessionID=null; Cookie[] cookies = request.getCookies(); if (cookies!=null){ for (Cookie cookie : cookies) { if(cookie.getName().equalsIgnoreCase("enwida.de")){ clientID=cookieSecurityService.decryptJsonString(cookie.getValue(), Constants.ENCRYPTION_KEY); } if(cookie.getName().equalsIgnoreCase("JSESSION")){ sessionID=cookie.getValue(); } } } if (clientID==null){ if (sessionID==null){ SecureRandom random = new SecureRandom(); sessionID= new BigInteger(130, random).toString(32); } clientID=sessionID; Cookie cookie=new Cookie("enwida.de",cookieSecurityService.encryptJsonString(clientID, Constants.ENCRYPTION_KEY)); sessionID=cookie.getValue(); response.addCookie(cookie); } request.setAttribute("clientId", clientID); return super.preHandle(request, response, handler); }
public boolean preHandle(HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception { String clientID=null; String sessionID=null; Cookie[] cookies = request.getCookies(); if (cookies!=null){ for (Cookie cookie : cookies) { if(cookie.getName().equalsIgnoreCase("enwida.de")){ clientID=cookieSecurityService.decryptJsonString(cookie.getValue(), Constants.ENCRYPTION_KEY); } if(cookie.getName().equalsIgnoreCase("JSESSION")){ sessionID=cookie.getValue(); } } } if (clientID==null){ if (sessionID==null){ SecureRandom random = new SecureRandom(); sessionID= new BigInteger(130, random).toString(32); } clientID=sessionID; Cookie cookie=new Cookie("enwida.de",cookieSecurityService.encryptJsonString(clientID, Constants.ENCRYPTION_KEY)); cookie.setPath("/"); cookie.setMaxAge(Integer.MAX_VALUE); sessionID=cookie.getValue(); response.addCookie(cookie); } request.setAttribute("clientId", clientID); return super.preHandle(request, response, handler); }
public void mapLineSnp() { String line = "1 565286 rs1578391 C T . flt NS=1;DP=5;AF=1.000;ANNOT=INT;GI=LOC100131754 GT:DP:EC:CONFS 1/1:5:5:5.300,5.300,1.000,1.000,1.000,1.000,1.000"; VariantLineMapper mapper = new VcfVariantLineMapper(COL_NAMES, Collections.<Annotation> emptyList(), Collections.<String, String> emptyMap(), this); GeneticVariant variant = mapper.mapLine(line); assertNotNull(variant); assertEquals(variant.getSequenceName(), "1"); assertEquals(variant.getStartPos(), 565286); assertEquals(variant.getPrimaryVariantId(), "rs1578391"); List<String> ids = variant.getAllIds(); assertNotNull(ids); assertEquals(ids.size(), 1); assertEquals(ids.get(0), "rs1578391"); assertEquals(variant.getRefAllele().getAlleleAsString(), "C"); List<String> alleles = variant.getVariantAlleles().getAllelesAsString(); assertNotNull(alleles); assertEquals(alleles.size(), 2); assertEquals(alleles.get(0), "C"); assertEquals(alleles.get(1), "T"); assertEquals(variant.getRefAllele().getAlleleAsString(), "C"); List<String> snpAlleles = variant.getVariantAlleles().getAllelesAsString(); assertNotNull(snpAlleles); assertEquals(snpAlleles.size(), 2); assertEquals(snpAlleles.get(0), "C"); assertEquals(snpAlleles.get(1), "T"); }
public void mapLineSnp() { String line = "1 565286 rs1578391 C T . flt NS=1;DP=5;AF=1.000;ANNOT=INT;GI=LOC100131754 GT:DP:EC:CONFS 1/1:5:5:5.300,5.300,1.000,1.000,1.000,1.000,1.000"; VariantLineMapper mapper = new VcfVariantLineMapper(COL_NAMES, Collections.<Annotation> emptyList(), Collections.<String, String> emptyMap(), this); GeneticVariant variant = mapper.mapLine(line); assertNotNull(variant); assertEquals(variant.isSnp(), true); assertEquals(variant.getSequenceName(), "1"); assertEquals(variant.getStartPos(), 565286); assertEquals(variant.getPrimaryVariantId(), "rs1578391"); List<String> ids = variant.getAllIds(); assertNotNull(ids); assertEquals(ids.size(), 1); assertEquals(ids.get(0), "rs1578391"); assertEquals(variant.getRefAllele().getAlleleAsString(), "C"); List<String> alleles = variant.getVariantAlleles().getAllelesAsString(); assertNotNull(alleles); assertEquals(alleles.size(), 2); assertEquals(alleles.get(0), "C"); assertEquals(alleles.get(1), "T"); assertEquals(variant.getRefAllele().getAlleleAsString(), "C"); List<String> snpAlleles = variant.getVariantAlleles().getAllelesAsString(); assertNotNull(snpAlleles); assertEquals(snpAlleles.size(), 2); assertEquals(snpAlleles.get(0), "C"); assertEquals(snpAlleles.get(1), "T"); }
public void execute() throws MojoExecutionException { if (clearOutput) { deleteDirectory(output); } HashMap<String, AspectClass> cacheAspects = new HashMap<String, AspectClass>(); List<NewMetaClassCreation> newMetaClass = new ArrayList<NewMetaClassCreation>(); List<File> sourceKotlinFileList = new ArrayList<File>(); if (sourceFile.isDirectory() && sourceFile.exists()) { collectFiles(sourceFile, sourceKotlinFileList, ".kt"); } Pattern metaAspect = Pattern.compile(".*metaclass[(]\"([a-zA-Z_]*)\"[)]\\s*trait\\s*([a-zA-Z_]*)(\\s*:\\s*[.a-zA-Z_]*)?.*"); Pattern p = Pattern.compile(".*aspect\\s*trait\\s*([a-zA-Z_]*)\\s*:\\s*([.a-zA-Z_]*).*"); Pattern pfun = Pattern.compile(".*fun\\s*([a-zA-Z_]*)\\s*[(](.*)[)](\\s*:\\s*[.a-zA-Z_]*)?.*"); Pattern packagePattern = Pattern.compile(".*package ([.a-zA-Z_]*).*"); CommentCleaner cleaner = new CommentCleaner(); for (File kotlinFile : sourceKotlinFileList) { BufferedReader br; String packageName = null; try { br = new BufferedReader(new StringReader(cleaner.cleanComment(kotlinFile))); String line; AspectClass currentAspect = null; while ((line = br.readLine()) != null) { Matcher funMatch = pfun.matcher(line); if (funMatch.matches() && !line.contains(" private ")) { if (currentAspect != null) { AspectMethod method = new AspectMethod(); method.name = funMatch.group(1).trim(); if (funMatch.groupCount() == 3) { method.returnType = funMatch.group(3); if (method.returnType != null) { method.returnType = method.returnType.replace(":", "").trim(); } } String params = funMatch.group(2); String[] paramsArray = params.split(","); for (int i = 0; i < paramsArray.length; i++) { String[] paramType = paramsArray[i].split(":"); if (paramType.length == 2) { AspectParam param = new AspectParam(); param.name = paramType[0].trim(); param.type = paramType[1].trim(); method.params.add(param); } } currentAspect.methods.add(method); } } Matcher newMeta = metaAspect.matcher(line); Matcher m = p.matcher(line); if (m.matches() || newMeta.matches()) { if (currentAspect != null) { cacheAspects.put(packageName + "." + currentAspect.name, currentAspect); } if (newMeta.matches()) { NewMetaClassCreation newMetaObject = new NewMetaClassCreation(); newMetaObject.originFile = kotlinFile; newMetaObject.name = newMeta.group(1).trim(); newMetaObject.packageName = packageName.trim(); if (newMeta.groupCount() == 3) { newMetaObject.parentName = newMeta.group(3); if (newMetaObject.parentName != null) { newMetaObject.parentName = newMetaObject.parentName.replace(":", "").trim(); } } newMetaClass.add(newMetaObject); currentAspect = new AspectClass(); currentAspect.name = newMeta.group(2); currentAspect.aspectedClass = newMetaObject.name; currentAspect.packageName = packageName.trim(); } else { currentAspect = new AspectClass(); currentAspect.name = m.group(1).trim(); currentAspect.aspectedClass = m.group(2).trim(); currentAspect.packageName = packageName.trim(); } } else { if (line.contains(" trait ") || line.contains(" class ")) { if (currentAspect != null) { cacheAspects.put(packageName + "." + currentAspect.name, currentAspect); } currentAspect = null; } } Matcher packageP = packagePattern.matcher(line); if (packageP.matches()) { packageName = packageP.group(1); } } if (currentAspect != null) { cacheAspects.put(packageName + "." + currentAspect.name, currentAspect); } } catch (Exception e) { e.printStackTrace(); } if (js) { if (!outputUtil.exists()) { outputUtil.mkdirs(); } URI relativeURI = sourceFile.toURI().relativize(kotlinFile.toURI()); File newFileTarget = new File(outputUtil + File.separator + relativeURI); newFileTarget.getParentFile().mkdirs(); try { if (cacheAspects == null) { Files.copy(kotlinFile, newFileTarget); } else { BufferedWriter writer = new BufferedWriter(new FileWriter(newFileTarget)); br = new BufferedReader(new FileReader(kotlinFile)); String line; while ((line = br.readLine()) != null) { writer.write(line .replaceAll("(metaclass.*trait)", "trait") .replace("aspect trait", "trait") .replace("import org.kevoree.modeling.api.aspect;", "") .replace("import org.kevoree.modeling.api.aspect", "") .replace("import org.kevoree.modeling.api.metaclass;", "") .replace("import org.kevoree.modeling.api.metaclass", "")); writer.write("\n"); } writer.close(); } } catch (Exception e) { e.printStackTrace(); } } } System.out.println("Collected Aspects : "); for (AspectClass aspect : cacheAspects.values()) { System.out.println(aspect.toString()); } GenerationContext ctx = new GenerationContext(); ctx.setRootSrcDirectory(sourceFile); ctx.aspects_$eq(cacheAspects); ctx.newMetaClasses_$eq(newMetaClass); try { for (String path : project.getCompileClasspathElements()) { if (path.contains("org.kevoree.modeling.microframework")) { ctx.microframework_$eq(true); } } } catch (DependencyResolutionRequiredException e) { e.printStackTrace(); } ctx.setPackagePrefix(scala.Option.apply(packagePrefix)); ctx.setRootGenerationDirectory(output); ctx.setRootUserDirectory(sourceFile); ctx.genSelector_$eq(selector); ctx.setJS(js); ctx.setGenerateEvents(events); ctx.flyweightFactory_$eq(flyweightFactory); ctx.ecma5_$eq(ecma5); Generator gen = new Generator(ctx, ecore); gen.generateModel(project.getVersion()); gen.generateLoader(); gen.generateSerializer(); gen.generateJSONSerializer(); gen.generateJsonLoader(); if (!ctx.getJS()) { javax.tools.JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); try { outputClasses.mkdirs(); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(outputClasses)); try { ArrayList<File> classPaths = new ArrayList<File>(); for (String path : project.getCompileClasspathElements()) { classPaths.add(new File(path)); } fileManager.setLocation(StandardLocation.CLASS_PATH, classPaths); } catch (DependencyResolutionRequiredException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } List<File> sourceFileList = new ArrayList<File>(); collectFiles(ctx.getRootGenerationDirectory(), sourceFileList, ".java"); try { File localFileDir = new File(outputUtil + File.separator + "org" + File.separator + "jetbrains" + File.separator + "annotations"); localFileDir.mkdirs(); File localFile = new File(localFileDir, "NotNull.java"); PrintWriter pr = new PrintWriter(localFile, "utf-8"); VelocityEngine ve = new VelocityEngine(); ve.setProperty("file.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); Template template = ve.getTemplate("NotNull.vm"); VelocityContext ctxV = new VelocityContext(); template.merge(ctxV, pr); pr.flush(); pr.close(); sourceFileList.add(localFile); } catch (Exception e) { e.printStackTrace(); } File microfxlpath = new File(ctx.getRootGenerationDirectory().getAbsolutePath() + File.separator + "org" + File.separator + "kevoree" + File.separator + "modeling" + File.separator + "api"); if (microfxlpath.exists()) { K2JVMCompilerArguments args = new K2JVMCompilerArguments(); ArrayList<String> sources = new ArrayList<String>(); sources.add(microfxlpath.getAbsolutePath()); args.setSourceDirs(sources); args.setOutputDir(outputClasses.getPath()); args.noJdkAnnotations = true; args.noStdlib = true; args.verbose = false; ExitCode efirst = KotlinCompiler.exec(new PrintStream(System.err) { @Override public void println(String x) { if (x.startsWith("WARNING")) { } else { super.println(x); } } }, args); if (efirst.ordinal() != 0) { throw new MojoExecutionException("Embedded Kotlin compilation error !"); } else { try { FileUtils.deleteDirectory(microfxlpath); } catch (IOException e) { e.printStackTrace(); } } } List<String> optionList = new ArrayList<String>(); try { StringBuffer cpath = new StringBuffer(); boolean firstBUF = true; for (String path : project.getCompileClasspathElements()) { if (!firstBUF) { cpath.append(File.pathSeparator); } cpath.append(path); firstBUF = false; } optionList.addAll(Arrays.asList("-classpath", cpath.toString())); } catch (Exception e) { optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path"))); } optionList.add("-source"); optionList.add("1.6"); optionList.add("-target"); optionList.add("1.6"); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sourceFileList); DiagnosticListener noWarningListener = new DiagnosticListener() { @Override public void report(Diagnostic diagnostic) { if (!diagnostic.getMessage(Locale.ENGLISH).contains("bootstrap class path not set in conjunction")) { if (diagnostic.getKind().equals(Diagnostic.Kind.ERROR)) { System.err.println(diagnostic); } else { System.out.println(diagnostic); } } } }; javax.tools.JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, noWarningListener, optionList, null, compilationUnits); boolean result = task.call(); try { fileManager.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Java API compilation : " + result); } outputClasses.mkdirs(); List<String> exclusions = new ArrayList<String>(); exclusions.add("KMFContainer.kt"); exclusions.add("Lexer.kt"); exclusions.add("TraceSequence.kt"); exclusions.add("XMIModelLoader.kt"); exclusions.add("XMIModelSerializer.kt"); try { StringBuffer cpath = new StringBuffer(); boolean firstBUF = true; for (String path : project.getCompileClasspathElements()) { boolean JSLIB = false; File file = new File(path); if (file.exists()) { if (file.isFile() && ctx.js()) { JarFile jarFile = new JarFile(file); if (jarFile.getJarEntry("META-INF/services/org.jetbrains.kotlin.js.librarySource") != null) { JSLIB = true; Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); boolean filtered = false; for (String filter : exclusions) { if (entry.getName().contains(filter)) { filtered = true; } } if ((entry.getName().endsWith(".kt") && !filtered) || entry.getName().endsWith(".kt.jslib")) { String fileName = entry.getName(); if (fileName.endsWith(".jslib")) { fileName = fileName.replace(".jslib", ""); } File destFile = new File(output, fileName.replace("/", File.separator + "")); File parent = destFile.getParentFile(); if (!parent.exists() && !parent.mkdirs()) { throw new IllegalStateException("Couldn't create dir: " + parent); } FileOutputStream jos = new FileOutputStream(destFile); InputStream is = jarFile.getInputStream(entry); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = is.read(buffer)) != -1) { jos.write(buffer, 0, bytesRead); } is.close(); jos.flush(); } } } } if (!JSLIB) { if (!firstBUF) { cpath.append(File.pathSeparator); } cpath.append(path); firstBUF = false; } } } ExitCode e = null; if (ctx.getJS()) { K2JSCompilerArguments args = new K2JSCompilerArguments(); ArrayList<String> sources = new ArrayList<String>(); sources.add(ctx.getRootGenerationDirectory().getAbsolutePath()); if (outputUtil.exists()) { sources.add(outputUtil.getAbsolutePath()); } args.sourceFiles = sources.toArray(new String[sources.size()]); args.outputFile = outputJS; args.verbose = false; if (ecma5) { args.target = EcmaVersion.v5.name(); } e = KotlinCompilerJS.exec(new PrintStream(System.err) { @Override public void println(String x) { if (x.startsWith("WARNING")) { } else { super.println(x); } } }, args); if (e.ordinal() != 0) { getLog().error("Can't compile generated code !"); throw new MojoExecutionException("Embedded Kotlin compilation error !"); } else { copyJsLibraryFile(KOTLIN_JS_MAPS); copyJsLibraryFile(KOTLIN_JS_LIB); copyJsLibraryFileRename("kotlin-lib-ecma3-fixed.js", KOTLIN_JS_LIB_ECMA3); copyJsLibraryFile(KOTLIN_JS_LIB_ECMA5); File outputMerged = new File(outputKotlinJSDir, project.getArtifactId() + ".merged.js"); FileOutputStream mergedStream = new FileOutputStream(outputMerged); if (ecma5) { IOUtils.copy(MetaInfServices.loadClasspathResource(KOTLIN_JS_LIB_ECMA5), mergedStream); } else { IOUtils.copy(MetaInfServices.loadClasspathResource("kotlin-lib-ecma3-fixed.js"), mergedStream); } IOUtils.copy(MetaInfServices.loadClasspathResource(KOTLIN_JS_LIB), mergedStream); IOUtils.copy(MetaInfServices.loadClasspathResource(KOTLIN_JS_MAPS), mergedStream); Files.copy(new File(outputKotlinJSDir, project.getArtifactId() + ".js"), mergedStream); mergedStream.write(("if(typeof(module)!='undefined'){module.exports = Kotlin.modules['" + project.getArtifactId() + "'];}").getBytes()); mergedStream.write("\n".getBytes()); mergedStream.flush(); mergedStream.close(); File ecm5merged = null; if(ecma5){ ecm5merged = new File(outputKotlinJSDir, project.getArtifactId() + ".merged2.js"); FileOutputStream mergedStream2 = new FileOutputStream(ecm5merged); BufferedReader buffered = new BufferedReader(new FileReader(outputMerged)); String line; while ((line = buffered.readLine()) != null) { mergedStream2.write(line.replace("\"use strict\";","").replace("'use strict';","").getBytes()); mergedStream2.write("\n".getBytes()); } buffered.close(); mergedStream2.close(); } com.google.javascript.jscomp.Compiler.setLoggingLevel(Level.WARNING); com.google.javascript.jscomp.Compiler compiler = new com.google.javascript.jscomp.Compiler(); CompilerOptions options = new CompilerOptions(); WarningLevel.QUIET.setOptionsForWarningLevel(options); CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options); options.setCheckUnreachableCode(CheckLevel.OFF); if(ecma5){ compiler.compile(Collections.<JSSourceFile>emptyList(), Collections.singletonList(JSSourceFile.fromFile(ecm5merged)), options); } else { compiler.compile(Collections.<JSSourceFile>emptyList(), Collections.singletonList(JSSourceFile.fromFile(outputMerged)), options); } File outputMin = new File(outputKotlinJSDir, project.getArtifactId() + ".min.js"); FileWriter outputFile = new FileWriter(outputMin); outputFile.write(compiler.toSource()); outputFile.close(); if (outputUtil.exists()) { FileUtils.deleteDirectory(outputUtil); } } } else { K2JVMCompilerArguments args = new K2JVMCompilerArguments(); args.setClasspath(cpath.toString()); ArrayList<String> sources = new ArrayList<String>(); sources.add(ctx.getRootGenerationDirectory().getAbsolutePath()); if (sourceFile.exists()) { getLog().info("Add directory : " + sourceFile.getAbsolutePath()); sources.add(sourceFile.getAbsolutePath()); } args.setSourceDirs(sources); args.setOutputDir(outputClasses.getPath()); args.noJdkAnnotations = true; args.noStdlib = true; args.verbose = false; e = KotlinCompiler.exec(new PrintStream(System.err) { @Override public void println(String x) { if (x.startsWith("WARNING")) { } else { super.println(x); } } }, args); } if (e.ordinal() != 0) { throw new MojoExecutionException("Embedded Kotlin compilation error !"); } } catch (MojoExecutionException e) { getLog().error(e); throw e; } catch (Exception e) { getLog().error(e); } }
public void execute() throws MojoExecutionException { if (clearOutput) { deleteDirectory(output); } HashMap<String, AspectClass> cacheAspects = new HashMap<String, AspectClass>(); List<NewMetaClassCreation> newMetaClass = new ArrayList<NewMetaClassCreation>(); List<File> sourceKotlinFileList = new ArrayList<File>(); if (sourceFile.isDirectory() && sourceFile.exists()) { collectFiles(sourceFile, sourceKotlinFileList, ".kt"); } Pattern metaAspect = Pattern.compile(".*metaclass[(]\"([a-zA-Z_]*)\"[)]\\s*trait\\s*([a-zA-Z_]*)(\\s*:\\s*[.a-zA-Z_]*)?.*"); Pattern p = Pattern.compile(".*aspect\\s*trait\\s*([a-zA-Z_]*)\\s*:\\s*([.a-zA-Z_]*).*"); Pattern pfun = Pattern.compile(".*fun\\s*([a-zA-Z_]*)\\s*[(](.*)[)](\\s*:\\s*[.a-zA-Z_]*)?.*"); Pattern packagePattern = Pattern.compile(".*package ([.a-zA-Z_]*).*"); CommentCleaner cleaner = new CommentCleaner(); for (File kotlinFile : sourceKotlinFileList) { BufferedReader br; String packageName = null; try { br = new BufferedReader(new StringReader(cleaner.cleanComment(kotlinFile))); String line; AspectClass currentAspect = null; while ((line = br.readLine()) != null) { Matcher funMatch = pfun.matcher(line); if (funMatch.matches() && !line.contains(" private ")) { if (currentAspect != null) { AspectMethod method = new AspectMethod(); method.name = funMatch.group(1).trim(); if (funMatch.groupCount() == 3) { method.returnType = funMatch.group(3); if (method.returnType != null) { method.returnType = method.returnType.replace(":", "").trim(); } } String params = funMatch.group(2); String[] paramsArray = params.split(","); for (int i = 0; i < paramsArray.length; i++) { String[] paramType = paramsArray[i].split(":"); if (paramType.length == 2) { AspectParam param = new AspectParam(); param.name = paramType[0].trim(); param.type = paramType[1].trim(); method.params.add(param); } } currentAspect.methods.add(method); } } Matcher newMeta = metaAspect.matcher(line); Matcher m = p.matcher(line); if (m.matches() || newMeta.matches()) { if (currentAspect != null) { cacheAspects.put(packageName + "." + currentAspect.name, currentAspect); } if (newMeta.matches()) { NewMetaClassCreation newMetaObject = new NewMetaClassCreation(); newMetaObject.originFile = kotlinFile; newMetaObject.name = newMeta.group(1).trim(); newMetaObject.packageName = packageName.trim(); if (newMeta.groupCount() == 3) { newMetaObject.parentName = newMeta.group(3); if (newMetaObject.parentName != null) { newMetaObject.parentName = newMetaObject.parentName.replace(":", "").trim(); } } newMetaClass.add(newMetaObject); currentAspect = new AspectClass(); currentAspect.name = newMeta.group(2); currentAspect.aspectedClass = newMetaObject.name; currentAspect.packageName = packageName.trim(); } else { currentAspect = new AspectClass(); currentAspect.name = m.group(1).trim(); currentAspect.aspectedClass = m.group(2).trim(); currentAspect.packageName = packageName.trim(); } } else { if (line.contains(" trait ") || line.contains(" class ")) { if (currentAspect != null) { cacheAspects.put(packageName + "." + currentAspect.name, currentAspect); } currentAspect = null; } } Matcher packageP = packagePattern.matcher(line); if (packageP.matches()) { packageName = packageP.group(1); } } if (currentAspect != null) { cacheAspects.put(packageName + "." + currentAspect.name, currentAspect); } } catch (Exception e) { e.printStackTrace(); } if (js) { if (!outputUtil.exists()) { outputUtil.mkdirs(); } URI relativeURI = sourceFile.toURI().relativize(kotlinFile.toURI()); File newFileTarget = new File(outputUtil + File.separator + relativeURI); newFileTarget.getParentFile().mkdirs(); try { if (cacheAspects == null) { Files.copy(kotlinFile, newFileTarget); } else { BufferedWriter writer = new BufferedWriter(new FileWriter(newFileTarget)); br = new BufferedReader(new FileReader(kotlinFile)); String line; while ((line = br.readLine()) != null) { writer.write(line .replaceAll("(metaclass.*trait)", "trait") .replace("aspect trait", "trait") .replace("import org.kevoree.modeling.api.aspect;", "") .replace("import org.kevoree.modeling.api.aspect", "") .replace("import org.kevoree.modeling.api.metaclass;", "") .replace("import org.kevoree.modeling.api.metaclass", "")); writer.write("\n"); } writer.close(); } } catch (Exception e) { e.printStackTrace(); } } } System.out.println("Collected Aspects : "); for (AspectClass aspect : cacheAspects.values()) { System.out.println(aspect.toString()); } GenerationContext ctx = new GenerationContext(); ctx.setRootSrcDirectory(sourceFile); ctx.aspects_$eq(cacheAspects); ctx.newMetaClasses_$eq(newMetaClass); try { for (String path : project.getCompileClasspathElements()) { if (path.contains("org.kevoree.modeling.microframework")) { ctx.microframework_$eq(true); } } } catch (DependencyResolutionRequiredException e) { e.printStackTrace(); } ctx.setPackagePrefix(scala.Option.apply(packagePrefix)); ctx.setRootGenerationDirectory(output); ctx.setRootUserDirectory(sourceFile); ctx.genSelector_$eq(selector); ctx.setJS(js); ctx.setGenerateEvents(events); ctx.flyweightFactory_$eq(flyweightFactory); ctx.ecma5_$eq(ecma5); Generator gen = new Generator(ctx, ecore); gen.generateModel(project.getVersion()); gen.generateLoader(); gen.generateSerializer(); gen.generateJSONSerializer(); gen.generateJsonLoader(); if (!ctx.getJS()) { javax.tools.JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); try { outputClasses.mkdirs(); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(outputClasses)); try { ArrayList<File> classPaths = new ArrayList<File>(); for (String path : project.getCompileClasspathElements()) { classPaths.add(new File(path)); } fileManager.setLocation(StandardLocation.CLASS_PATH, classPaths); } catch (DependencyResolutionRequiredException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } List<File> sourceFileList = new ArrayList<File>(); collectFiles(ctx.getRootGenerationDirectory(), sourceFileList, ".java"); try { File localFileDir = new File(outputUtil + File.separator + "org" + File.separator + "jetbrains" + File.separator + "annotations"); localFileDir.mkdirs(); File localFile = new File(localFileDir, "NotNull.java"); PrintWriter pr = new PrintWriter(localFile, "utf-8"); VelocityEngine ve = new VelocityEngine(); ve.setProperty("file.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); Template template = ve.getTemplate("NotNull.vm"); VelocityContext ctxV = new VelocityContext(); template.merge(ctxV, pr); pr.flush(); pr.close(); sourceFileList.add(localFile); } catch (Exception e) { e.printStackTrace(); } File microfxlpath = new File(ctx.getRootGenerationDirectory().getAbsolutePath() + File.separator + "org" + File.separator + "kevoree" + File.separator + "modeling" + File.separator + "api"); if (microfxlpath.exists()) { K2JVMCompilerArguments args = new K2JVMCompilerArguments(); ArrayList<String> sources = new ArrayList<String>(); sources.add(microfxlpath.getAbsolutePath()); args.setSourceDirs(sources); args.setOutputDir(outputClasses.getPath()); args.noJdkAnnotations = true; args.noStdlib = true; args.verbose = false; ExitCode efirst = KotlinCompiler.exec(new PrintStream(System.err) { @Override public void println(String x) { if (x.startsWith("WARNING")) { } else { super.println(x); } } }, args); if (efirst.ordinal() != 0) { throw new MojoExecutionException("Embedded Kotlin compilation error !"); } else { try { FileUtils.deleteDirectory(microfxlpath); } catch (IOException e) { e.printStackTrace(); } } } List<String> optionList = new ArrayList<String>(); try { StringBuffer cpath = new StringBuffer(); boolean firstBUF = true; for (String path : project.getCompileClasspathElements()) { if (!firstBUF) { cpath.append(File.pathSeparator); } cpath.append(path); firstBUF = false; } optionList.addAll(Arrays.asList("-classpath", cpath.toString())); } catch (Exception e) { optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path"))); } optionList.add("-source"); optionList.add("1.6"); optionList.add("-target"); optionList.add("1.6"); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sourceFileList); DiagnosticListener noWarningListener = new DiagnosticListener() { @Override public void report(Diagnostic diagnostic) { if (!diagnostic.getMessage(Locale.ENGLISH).contains("bootstrap class path not set in conjunction")) { if (diagnostic.getKind().equals(Diagnostic.Kind.ERROR)) { System.err.println(diagnostic); } else { System.out.println(diagnostic); } } } }; javax.tools.JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, noWarningListener, optionList, null, compilationUnits); boolean result = task.call(); try { fileManager.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Java API compilation : " + result); } outputClasses.mkdirs(); List<String> exclusions = new ArrayList<String>(); exclusions.add("KMFContainer.kt"); exclusions.add("JSONModelLoader.kt"); exclusions.add("Lexer.kt"); exclusions.add("TraceSequence.kt"); exclusions.add("XMIModelLoader.kt"); exclusions.add("XMIModelSerializer.kt"); try { StringBuffer cpath = new StringBuffer(); boolean firstBUF = true; for (String path : project.getCompileClasspathElements()) { boolean JSLIB = false; File file = new File(path); if (file.exists()) { if (file.isFile() && ctx.js()) { JarFile jarFile = new JarFile(file); if (jarFile.getJarEntry("META-INF/services/org.jetbrains.kotlin.js.librarySource") != null) { JSLIB = true; Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); boolean filtered = false; for (String filter : exclusions) { if (entry.getName().contains(filter)) { filtered = true; } } if ((entry.getName().endsWith(".kt") && !filtered) || entry.getName().endsWith(".kt.jslib")) { String fileName = entry.getName(); if (fileName.endsWith(".jslib")) { fileName = fileName.replace(".jslib", ""); } File destFile = new File(output, fileName.replace("/", File.separator + "")); File parent = destFile.getParentFile(); if (!parent.exists() && !parent.mkdirs()) { throw new IllegalStateException("Couldn't create dir: " + parent); } FileOutputStream jos = new FileOutputStream(destFile); InputStream is = jarFile.getInputStream(entry); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = is.read(buffer)) != -1) { jos.write(buffer, 0, bytesRead); } is.close(); jos.flush(); } } } } if (!JSLIB) { if (!firstBUF) { cpath.append(File.pathSeparator); } cpath.append(path); firstBUF = false; } } } ExitCode e = null; if (ctx.getJS()) { K2JSCompilerArguments args = new K2JSCompilerArguments(); ArrayList<String> sources = new ArrayList<String>(); sources.add(ctx.getRootGenerationDirectory().getAbsolutePath()); if (outputUtil.exists()) { sources.add(outputUtil.getAbsolutePath()); } args.sourceFiles = sources.toArray(new String[sources.size()]); args.outputFile = outputJS; args.verbose = false; if (ecma5) { args.target = EcmaVersion.v5.name(); } e = KotlinCompilerJS.exec(new PrintStream(System.err) { @Override public void println(String x) { if (x.startsWith("WARNING")) { } else { super.println(x); } } }, args); if (e.ordinal() != 0) { getLog().error("Can't compile generated code !"); throw new MojoExecutionException("Embedded Kotlin compilation error !"); } else { copyJsLibraryFile(KOTLIN_JS_MAPS); copyJsLibraryFile(KOTLIN_JS_LIB); copyJsLibraryFileRename("kotlin-lib-ecma3-fixed.js", KOTLIN_JS_LIB_ECMA3); copyJsLibraryFile(KOTLIN_JS_LIB_ECMA5); File outputMerged = new File(outputKotlinJSDir, project.getArtifactId() + ".merged.js"); FileOutputStream mergedStream = new FileOutputStream(outputMerged); if (ecma5) { IOUtils.copy(MetaInfServices.loadClasspathResource(KOTLIN_JS_LIB_ECMA5), mergedStream); } else { IOUtils.copy(MetaInfServices.loadClasspathResource("kotlin-lib-ecma3-fixed.js"), mergedStream); } IOUtils.copy(MetaInfServices.loadClasspathResource(KOTLIN_JS_LIB), mergedStream); IOUtils.copy(MetaInfServices.loadClasspathResource(KOTLIN_JS_MAPS), mergedStream); Files.copy(new File(outputKotlinJSDir, project.getArtifactId() + ".js"), mergedStream); mergedStream.write(("if(typeof(module)!='undefined'){module.exports = Kotlin.modules['" + project.getArtifactId() + "'];}").getBytes()); mergedStream.write("\n".getBytes()); mergedStream.flush(); mergedStream.close(); File ecm5merged = null; if(ecma5){ ecm5merged = new File(outputKotlinJSDir, project.getArtifactId() + ".merged2.js"); FileOutputStream mergedStream2 = new FileOutputStream(ecm5merged); BufferedReader buffered = new BufferedReader(new FileReader(outputMerged)); String line; while ((line = buffered.readLine()) != null) { mergedStream2.write(line.replace("\"use strict\";","").replace("'use strict';","").getBytes()); mergedStream2.write("\n".getBytes()); } buffered.close(); mergedStream2.close(); } com.google.javascript.jscomp.Compiler.setLoggingLevel(Level.WARNING); com.google.javascript.jscomp.Compiler compiler = new com.google.javascript.jscomp.Compiler(); CompilerOptions options = new CompilerOptions(); WarningLevel.QUIET.setOptionsForWarningLevel(options); CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options); options.setCheckUnreachableCode(CheckLevel.OFF); if(ecma5){ compiler.compile(Collections.<JSSourceFile>emptyList(), Collections.singletonList(JSSourceFile.fromFile(ecm5merged)), options); } else { compiler.compile(Collections.<JSSourceFile>emptyList(), Collections.singletonList(JSSourceFile.fromFile(outputMerged)), options); } File outputMin = new File(outputKotlinJSDir, project.getArtifactId() + ".min.js"); FileWriter outputFile = new FileWriter(outputMin); outputFile.write(compiler.toSource()); outputFile.close(); if (outputUtil.exists()) { FileUtils.deleteDirectory(outputUtil); } } } else { K2JVMCompilerArguments args = new K2JVMCompilerArguments(); args.setClasspath(cpath.toString()); ArrayList<String> sources = new ArrayList<String>(); sources.add(ctx.getRootGenerationDirectory().getAbsolutePath()); if (sourceFile.exists()) { getLog().info("Add directory : " + sourceFile.getAbsolutePath()); sources.add(sourceFile.getAbsolutePath()); } args.setSourceDirs(sources); args.setOutputDir(outputClasses.getPath()); args.noJdkAnnotations = true; args.noStdlib = true; args.verbose = false; e = KotlinCompiler.exec(new PrintStream(System.err) { @Override public void println(String x) { if (x.startsWith("WARNING")) { } else { super.println(x); } } }, args); } if (e.ordinal() != 0) { throw new MojoExecutionException("Embedded Kotlin compilation error !"); } } catch (MojoExecutionException e) { getLog().error(e); throw e; } catch (Exception e) { getLog().error(e); } }
public DirectedSparseMultigraph<ClassicalBMachine, RefType> initialize( Start mainast, RecursiveMachineLoader rml) throws ProBException { DirectedSparseMultigraph<ClassicalBMachine, RefType> graph = new DirectedSparseMultigraph<ClassicalBMachine, RefType>(); mainMachine = new ClassicalBMachine(null); DomBuilder d = new DomBuilder(mainMachine); d.build(mainast); String name = mainMachine.name(); graph.addVertex(mainMachine); boolean fpReached; do { fpReached = true; Collection<ClassicalBMachine> vertices = graph.getVertices(); for (ClassicalBMachine machine : vertices) { Start ast = rml.getParsedMachines().get(machine.name()); if (!done.contains(machine)) { ast.apply(new DependencyWalker(machine, graph, rml .getParsedMachines())); done.add(machine); fpReached = false; } } } while (!fpReached); this.graph = graph; return graph; }
public DirectedSparseMultigraph<ClassicalBMachine, RefType> initialize( Start mainast, RecursiveMachineLoader rml) throws ProBException { DirectedSparseMultigraph<ClassicalBMachine, RefType> graph = new DirectedSparseMultigraph<ClassicalBMachine, RefType>(); mainMachine = new ClassicalBMachine(null); DomBuilder d = new DomBuilder(mainMachine); d.build(mainast); graph.addVertex(mainMachine); boolean fpReached; do { fpReached = true; Collection<ClassicalBMachine> vertices = graph.getVertices(); for (ClassicalBMachine machine : vertices) { Start ast = rml.getParsedMachines().get(machine.name()); if (!done.contains(machine)) { ast.apply(new DependencyWalker(machine, graph, rml .getParsedMachines())); done.add(machine); fpReached = false; } } } while (!fpReached); this.graph = graph; return graph; }
public ObjectiveProperties load() { final String title = toTitle(_resourcePath); final JavaPropertiesReader reader = new JavaPropertiesReader(title, new JavaPropertiesStreamProvider() { public InputStream provideStream() throws IOException { return toStream(_resourcePath); } }); prepareExtendsProperties(reader); _javaPropertiesResult = reader.read(); return this; }
public ObjectiveProperties load() { final String title = toTitle(_resourcePath); final JavaPropertiesReader reader = new JavaPropertiesReader(title, new JavaPropertiesStreamProvider() { public InputStream provideStream() throws IOException { return toStream(_resourcePath); } }); prepareExtendsProperties(reader); if (_checkImplicitOverride) { reader.checkImplicitOverride(); } _javaPropertiesResult = reader.read(); return this; }
public void init(IStructuredSelection selection) { super.init(selection); if (selection != null && !selection.isEmpty()) { Object o = selection.iterator().next(); IType type = null; if (o instanceof IType) { type = (IType) o; } else if (o instanceof ICompilationUnit) { ICompilationUnit cu = (ICompilationUnit) o; try { IType[] ts = cu.getTypes(); if (ts != null && ts.length > 0) type = ts[0]; } catch (JavaModelException e) { CDICorePlugin.getDefault().logError(e); } } boolean isInterface = false; try { isInterface = type != null && type.isInterface(); } catch (JavaModelException e) { CDICorePlugin.getDefault().logError(e); } if (isInterface) { ArrayList<String> interfacesNames = new ArrayList<String>(); String name = ""; try { name = type.getFullyQualifiedParameterizedName(); } catch (JavaModelException e) { name = type.getFullyQualifiedName(); } interfacesNames.add(name); setSuperInterfaces(interfacesNames, true); superInterfacesChanged(); setDefaultTypeName(name); } } setModifiers(getModifiers() | Flags.AccAbstract, true); doStatusUpdate(); }
public void init(IStructuredSelection selection) { super.init(selection); if (selection != null && !selection.isEmpty()) { Object o = selection.iterator().next(); IType type = null; if (o instanceof IType) { type = (IType) o; } else if (o instanceof ICompilationUnit) { ICompilationUnit cu = (ICompilationUnit) o; try { IType[] ts = cu.getTypes(); if (ts != null && ts.length > 0) type = ts[0]; } catch (JavaModelException e) { CDICorePlugin.getDefault().logError(e); } } boolean isInterface = false; try { isInterface = type != null && type.isInterface(); } catch (JavaModelException e) { CDICorePlugin.getDefault().logError(e); } ArrayList<String> interfacesNames = new ArrayList<String>(); if (isInterface) { String name = ""; try { name = type.getFullyQualifiedParameterizedName(); } catch (JavaModelException e) { name = type.getFullyQualifiedName(); } interfacesNames.add(name); setDefaultTypeName(name); } interfacesNames.add("java.io.Serializable"); setSuperInterfaces(interfacesNames, true); superInterfacesChanged(); } doStatusUpdate(); }
public void run(Result result, SchedulerEvent event) { try { FXDParserResult fxdResult = (FXDParserResult) result; List<FXDSyntaxErrorException> syntaxErrors = fxdResult.getSyntaxErrors(); Document document = result.getSnapshot().getSource().getDocument(false); List<ErrorDescription> errors = new ArrayList<ErrorDescription>(); for (FXDSyntaxErrorException syntaxError : syntaxErrors) { TokenSequence<?> ts = result.getSnapshot().getTokenHierarchy().tokenSequence(); ts.move(syntaxError.getOffset()); if (ts.moveNext()) { Token token = ts.token(); int start = ts.offset(); int end = start + token.length(); ErrorDescription errorDescription = ErrorDescriptionFactory.createErrorDescription( Severity.ERROR, syntaxError.getMessage(), document, document.createPosition(start), document.createPosition(end)); errors.add(errorDescription); } } HintsController.setErrors(document, "simple-java", errors); } catch (BadLocationException ex1) { Exceptions.printStackTrace(ex1); } catch (org.netbeans.modules.parsing.spi.ParseException ex1) { Exceptions.printStackTrace (ex1); } }
public void run(Result result, SchedulerEvent event) { try { FXDParserResult fxdResult = (FXDParserResult) result; List<FXDSyntaxErrorException> syntaxErrors = fxdResult.getSyntaxErrors(); Document document = result.getSnapshot().getSource().getDocument(false); List<ErrorDescription> errors = new ArrayList<ErrorDescription>(); for (FXDSyntaxErrorException syntaxError : syntaxErrors) { TokenSequence<?> ts = result.getSnapshot().getTokenHierarchy().tokenSequence(); ts.move(syntaxError.getOffset()); if (ts.moveNext()) { Token token = ts.token(); int start = ts.offset(); int end = start + token.length(); ErrorDescription errorDescription = ErrorDescriptionFactory.createErrorDescription( Severity.ERROR, syntaxError.getMessage(), document, document.createPosition(start), document.createPosition(end)); errors.add(errorDescription); } } if(document != null){ HintsController.setErrors(document, "simple-java", errors); } } catch (BadLocationException ex1) { Exceptions.printStackTrace(ex1); } catch (org.netbeans.modules.parsing.spi.ParseException ex1) { Exceptions.printStackTrace (ex1); } }
protected InputStream postProcess(ProxyRequest request, InputStream responseStream) throws IOException { ProxyHtmlUtil.headerProcess( request ); request.putResponseHeader("Pragma", "no-cache"); request.putResponseHeader("Cache-Control", "no-cache"); String contentType = request.getResponseHeader("Content-Type"); if(contentType != null && !(contentType.indexOf("text/html") == 0 || contentType.indexOf("application/xhtml+xml") == 0) ){ request.putResponseHeader("Content-Type", "text/html; charset=\"UTF-8\""); byte[] errorMsg = createErrorMessage("Error: Part select function can be only used for HTML.", "UTF-8"); request.putResponseHeader("Content-Length", String.valueOf( errorMsg.length ) ); return new ByteArrayInputStream( errorMsg ) ; } String encoding = request.getFilterEncoding(); String outputEncoding = encoding != null && encoding.length() > 0 ? encoding : "UTF-8"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try{ String requestURL = request.getRedirectURL(); if( requestURL == null ) requestURL = request.getEscapedOriginalURL(); ProxyHtmlUtil.getInstance().nekoProcess( responseStream, encoding,new XMLDocumentFilter[]{ new ProxyHtmlUtil.AttachBaseTagFilter( requestURL ), new Writer(baos, outputEncoding) }); }catch(MalformedInputException e){ String message = "Invalid page is specifeid to the page.[" + encoding + "]\n UTF-8 is applied as default if any encoding is not specified."; log.error(message, e); byte[] errorMsg = createErrorMessage(message, "UTF-8"); request.putResponseHeader("Content-Type", "text/html; charset=\"UTF-8\""); request.putResponseHeader("Content-Length", String.valueOf( errorMsg.length ) ); return new ByteArrayInputStream(errorMsg); } byte[] responseBody = baos.toByteArray(); request.putResponseHeader("Content-Type", "text/html; charset=" + outputEncoding); request.putResponseHeader("Content-Length",String.valueOf( responseBody.length )); return new ByteArrayInputStream( responseBody ); }
protected InputStream postProcess(ProxyRequest request, InputStream responseStream) throws IOException { ProxyHtmlUtil.headerProcess( request ); request.putResponseHeader("Pragma", "no-cache"); request.putResponseHeader("Cache-Control", "no-cache"); String contentType = request.getResponseHeader("Content-Type"); if(contentType != null && !(contentType.toLowerCase().indexOf("text/html") == 0 || contentType.toLowerCase().indexOf("application/xhtml+xml") == 0) ){ request.putResponseHeader("Content-Type", "text/html; charset=\"UTF-8\""); byte[] errorMsg = createErrorMessage("Error: Part select function can be only used for HTML.", "UTF-8"); request.putResponseHeader("Content-Length", String.valueOf( errorMsg.length ) ); return new ByteArrayInputStream( errorMsg ) ; } String encoding = request.getFilterEncoding(); String outputEncoding = encoding != null && encoding.length() > 0 ? encoding : "UTF-8"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try{ String requestURL = request.getRedirectURL(); if( requestURL == null ) requestURL = request.getEscapedOriginalURL(); ProxyHtmlUtil.getInstance().nekoProcess( responseStream, encoding,new XMLDocumentFilter[]{ new ProxyHtmlUtil.AttachBaseTagFilter( requestURL ), new Writer(baos, outputEncoding) }); }catch(MalformedInputException e){ String message = "Invalid page is specifeid to the page.[" + encoding + "]\n UTF-8 is applied as default if any encoding is not specified."; log.error(message, e); byte[] errorMsg = createErrorMessage(message, "UTF-8"); request.putResponseHeader("Content-Type", "text/html; charset=\"UTF-8\""); request.putResponseHeader("Content-Length", String.valueOf( errorMsg.length ) ); return new ByteArrayInputStream(errorMsg); } byte[] responseBody = baos.toByteArray(); request.putResponseHeader("Content-Type", "text/html; charset=" + outputEncoding); request.putResponseHeader("Content-Length",String.valueOf( responseBody.length )); return new ByteArrayInputStream( responseBody ); }
public GameMenuPopup(Stage stage) { noop = new Runnable(){ @Override public void run() { } }; setWidth(stage.getWidth()); setHeight(stage.getHeight()/(6.8f-GnuBackgammon.ss)); setX(0); setY(-getHeight()); background = GnuBackgammon.skin.getDrawable("popup-region"); setBackground(background); a = new Actor(); a.addListener(new InputListener(){ @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { hide(noop); return true; } }); t1 = new Table(); t1.setFillParent(true); TextButtonStyle tl = GnuBackgammon.skin.get("button", TextButtonStyle.class); undo = new TextButton("Undo Move", tl); undo.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { hide(new Runnable(){ @Override public void run() { if (undo.isDisabled()) return; GnuBackgammon.Instance.board.undoMove(); }}); } }); resign = new TextButton("Resign Game", tl); resign.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { hide(new Runnable(){ @Override public void run() { if (resign.isDisabled()) return; GnuBackgammon.fsm.state(States.DIALOG_HANDLER); GnuBackgammon.fsm.processEvent(Events.ACCEPT_RESIGN, 0); }}); } }); abandon = new TextButton("Abandon Match", tl); abandon.addListener(new ClickListener(){@Override public void clicked(InputEvent event, float x, float y) { hide(new Runnable(){ @Override public void run() { if (abandon.isDisabled()) return; GnuBackgammon.fsm.state(States.DIALOG_HANDLER); UIDialog.getYesNoDialog( Events.ABANDON_MATCH, "Really exit this match?", 0.82f, GnuBackgammon.Instance.board.getStage()); }}); }}); options = new TextButton("Options", tl); options.addListener(new ClickListener(){@Override public void clicked(InputEvent event, float x, float y) { hide(new Runnable(){ @Override public void run() { UIDialog.getOptionsDialog(0.82f, GnuBackgammon.Instance.board.getStage()); }}); }}); float pad = getHeight()/15; float w = getWidth()/3.3f - pad; add(undo).fill().expand().pad(pad).width(w); add(resign).fill().expand().pad(pad).width(w); add(abandon).fill().expand().pad(pad).width(w); add(options).fill().expand().pad(pad).width(w); visible = false; addActor(t1); }
public GameMenuPopup(Stage stage) { noop = new Runnable(){ @Override public void run() { } }; setWidth(stage.getWidth()); setHeight(stage.getHeight()/(6.8f-GnuBackgammon.ss)); setX(0); setY(-getHeight()); background = GnuBackgammon.skin.getDrawable("popup-region"); setBackground(background); a = new Actor(); a.addListener(new InputListener(){ @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { hide(noop); return true; } }); t1 = new Table(); t1.setFillParent(true); TextButtonStyle tl = GnuBackgammon.skin.get("button", TextButtonStyle.class); undo = new TextButton("Undo Move", tl); undo.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { hide(new Runnable(){ @Override public void run() { if (undo.isDisabled()) return; GnuBackgammon.Instance.board.undoMove(); }}); } }); resign = new TextButton("Resign Game", tl); resign.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { hide(new Runnable(){ @Override public void run() { if (resign.isDisabled()) return; GnuBackgammon.fsm.state(States.DIALOG_HANDLER); GnuBackgammon.fsm.processEvent(Events.ACCEPT_RESIGN, 0); }}); } }); abandon = new TextButton("Abandon Match", tl); abandon.addListener(new ClickListener(){@Override public void clicked(InputEvent event, float x, float y) { hide(new Runnable(){ @Override public void run() { if (abandon.isDisabled()) return; GnuBackgammon.fsm.state(States.DIALOG_HANDLER); UIDialog.getYesNoDialog( Events.ABANDON_MATCH, "Really exit this match?", 0.82f, GnuBackgammon.Instance.board.getStage()); }}); }}); options = new TextButton("Options", tl); options.addListener(new ClickListener(){@Override public void clicked(InputEvent event, float x, float y) { hide(new Runnable(){ @Override public void run() { UIDialog.getOptionsDialog(0.95f, GnuBackgammon.Instance.board.getStage()); }}); }}); float pad = getHeight()/15; float w = getWidth()/3.3f - pad; add(undo).fill().expand().pad(pad).width(w); add(resign).fill().expand().pad(pad).width(w); add(abandon).fill().expand().pad(pad).width(w); add(options).fill().expand().pad(pad).width(w); visible = false; addActor(t1); }
public void fromHostAndPorstWithCorrectDataShouldSucceed() { final List<HostAndPort> hostAndPorts = ImmutableList.of( HostAndPort.fromParts("example.net", 1234), HostAndPort.fromParts("example.com", 5678), HostAndPort.fromString("example.org") ); final TransportAddress[] result = TransportAddressHelper.fromHostAndPorts(hostAndPorts); assertEquals(3, result.length); for (int i = 0; i < result.length; i++) { final InetSocketTransportAddress transportAddress = (InetSocketTransportAddress) result[i]; assertEquals(hostAndPorts.get(i).getHostText(), transportAddress.address().getHostName()); assertEquals(hostAndPorts.get(i).getPortOrDefault(ES_DEFAULT_PORT), transportAddress.address().getPort()); } }
public void fromHostAndPostWithCorrectDataShouldSucceed() { final List<HostAndPort> hostAndPorts = ImmutableList.of( HostAndPort.fromParts("example.net", 1234), HostAndPort.fromParts("example.com", 5678), HostAndPort.fromString("example.org") ); final TransportAddress[] result = TransportAddressHelper.fromHostAndPorts(hostAndPorts); assertEquals(3, result.length); for (int i = 0; i < result.length; i++) { final InetSocketTransportAddress transportAddress = (InetSocketTransportAddress) result[i]; assertEquals(hostAndPorts.get(i).getHostText(), transportAddress.address().getHostName()); assertEquals(hostAndPorts.get(i).getPortOrDefault(ES_DEFAULT_PORT), transportAddress.address().getPort()); } }
protected void repairTreeAfterDeletion(RedBlackTree<K, V>.TreePath path) { boolean setColor = false; Entry toDelete = path.getLast(); while (path.size() > 1 && colorOf(path.getLast()) == Color.BLACK) { if (path.getLast() == leftOf(path.getLast(1))) { Entry sib = rightOf(path.getLast(1)); if (colorOf(sib) == Color.RED) { setColor(sib, Color.BLACK); setColor(path.getLast(1), Color.RED); Entry p = path.removeLast(); path.rotateLeft(); path.addLast(p); sib = rightOf(path.getLast(1)); } if (colorOf(leftOf(sib)) == Color.BLACK && colorOf(rightOf(sib)) == Color.BLACK) { setColor(sib, Color.RED); path.removeLast(); setColor = true; } else { if (colorOf(rightOf(sib)) == Color.BLACK) { setColor(leftOf(sib), Color.BLACK); setColor(sib, Color.RED); Entry p = path.removeLast(); path.addLast(sib); path.rotateRight(); path.removeLast(); path.removeLast(); path.addLast(p); sib = rightOf(path.getLast(1)); } setColor(sib, colorOf(path.getLast(1))); setColor(path.getLast(1), Color.BLACK); setColor(rightOf(sib), Color.BLACK); path.removeLast(); path.rotateLeft(); setColor(root, Color.BLACK); setColor = false; break; } } else { Entry sib = leftOf(path.getLast(1)); if (colorOf(sib) == Color.RED) { setColor(sib, Color.BLACK); setColor(path.getLast(1), Color.RED); Entry p = path.removeLast(); path.rotateRight(); path.addLast(p); sib = leftOf(path.getLast(1)); } if (colorOf(rightOf(sib)) == Color.BLACK && colorOf(leftOf(sib)) == Color.BLACK) { setColor(sib, Color.RED); path.removeLast(); setColor = true; } else { if (colorOf(leftOf(sib)) == Color.BLACK) { setColor(rightOf(sib), Color.BLACK); setColor(sib, Color.RED); Entry p = path.removeLast(); path.addLast(sib); path.rotateLeft(); path.removeLast(); path.removeLast(); path.addLast(p); sib = leftOf(path.getLast(1)); } setColor(sib, colorOf(path.getLast(1))); setColor(path.getLast(1), Color.BLACK); setColor(leftOf(sib), Color.BLACK); path.removeLast(); path.rotateRight(); setColor(root, Color.BLACK); setColor = false; break; } } } if (setColor) setColor(path.getLast(), Color.BLACK); boolean goHigher = comparator.compare(toDelete.getKey(), path.getLast().getKey()) >= 0; while (!path.endsWithKey(toDelete.getKey())) { if (goHigher) path.moveToSuccesor(); else path.moveToPredecessor(); } }
protected void repairTreeAfterDeletion(RedBlackTree<K, V>.TreePath path) { boolean setColor = false; Entry toDelete = path.getLast(); while (path.size() > 1 && colorOf(path.getLast()) == Color.BLACK) { if (path.getLast() == leftOf(path.getLast(1))) { Entry sib = rightOf(path.getLast(1)); if (colorOf(sib) == Color.RED) { setColor(sib, Color.BLACK); setColor(path.getLast(1), Color.RED); Entry p = path.removeLast(); path.rotateLeft(); path.addLast(p); sib = rightOf(path.getLast(1)); } if (colorOf(leftOf(sib)) == Color.BLACK && colorOf(rightOf(sib)) == Color.BLACK) { setColor(sib, Color.RED); path.removeLast(); setColor = true; } else { if (colorOf(rightOf(sib)) == Color.BLACK) { setColor(leftOf(sib), Color.BLACK); setColor(sib, Color.RED); Entry p = path.removeLast(); path.addLast(sib); path.rotateRight(); path.removeLast(); path.removeLast(); path.addLast(p); sib = rightOf(path.getLast(1)); } setColor(sib, colorOf(path.getLast(1))); setColor(path.getLast(1), Color.BLACK); setColor(rightOf(sib), Color.BLACK); path.removeLast(); path.rotateLeft(); setColor(root, Color.BLACK); setColor = false; break; } } else { Entry sib = leftOf(path.getLast(1)); if (colorOf(sib) == Color.RED) { setColor(sib, Color.BLACK); setColor(path.getLast(1), Color.RED); Entry p = path.removeLast(); path.rotateRight(); path.addLast(p); sib = leftOf(path.getLast(1)); } if (colorOf(rightOf(sib)) == Color.BLACK && colorOf(leftOf(sib)) == Color.BLACK) { setColor(sib, Color.RED); path.removeLast(); setColor = true; } else { if (colorOf(leftOf(sib)) == Color.BLACK) { setColor(rightOf(sib), Color.BLACK); setColor(sib, Color.RED); Entry p = path.removeLast(); path.addLast(sib); path.rotateLeft(); path.removeLast(); path.removeLast(); path.addLast(p); sib = leftOf(path.getLast(1)); } setColor(sib, colorOf(path.getLast(1))); setColor(path.getLast(1), Color.BLACK); setColor(leftOf(sib), Color.BLACK); path.removeLast(); path.rotateRight(); setColor(root, Color.BLACK); setColor = false; break; } } } if (setColor) setColor(path.getLast(), Color.BLACK); boolean goHigher = comparator.compare(toDelete.getKey(), path.getLast().getKey()) >= 0; while (path.size() > 0 && !path.endsWithKey(toDelete.getKey())) { if (goHigher) path.moveToSuccesor(); else path.moveToPredecessor(); } }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("tardis")) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { sender.sendMessage(Constants.COMMANDS.split("\n")); return true; } if (!args[0].equalsIgnoreCase("save") && !args[0].equalsIgnoreCase("list") && !args[0].equalsIgnoreCase("admin") && !args[0].equalsIgnoreCase("help") && !args[0].equalsIgnoreCase("find") && !args[0].equalsIgnoreCase("reload") && !args[0].equalsIgnoreCase("add") && !args[0].equalsIgnoreCase("remove") && !args[0].equalsIgnoreCase("update")) { sender.sendMessage("Do you want to list destinations, save a destination, update the TARDIS, add/remove companions, do some admin stuff or find the TARDIS?"); return false; } if (args[0].equalsIgnoreCase("reload")) { plugin.loadConfig(); sender.sendMessage("TARDIS config reloaded."); } if (args[0].equalsIgnoreCase("admin")) { if (args.length == 1) { sender.sendMessage(Constants.COMMAND_ADMIN.split("\n")); return true; } if (args[1].equalsIgnoreCase("update")) { Set<String> timelords = plugin.timelords.getKeys(false); for (String p : timelords) { if (!p.equals("dummy_user")) { String c = plugin.timelords.getString(p + ".chunk"); String d = plugin.timelords.getString(p + ".direction"); String h = plugin.timelords.getString(p + ".home"); String s = plugin.timelords.getString(p + ".save"); String cur = plugin.timelords.getString(p + ".current"); String r = plugin.timelords.getString(p + ".replaced"); String chest = plugin.timelords.getString(p + ".chest"); String b = plugin.timelords.getString(p + ".button"); String r0 = plugin.timelords.getString(p + ".repeater0"); String r1 = plugin.timelords.getString(p + ".repeater1"); String r2 = plugin.timelords.getString(p + ".repeater2"); String r3 = plugin.timelords.getString(p + ".repeater3"); String s1 = plugin.timelords.getString(p + ".save1"); String s2 = plugin.timelords.getString(p + ".save2"); String s3 = plugin.timelords.getString(p + ".save3"); String t = plugin.timelords.getString(p + ".travelling"); try { service.getConnection(); service.insertTimelords(p, c, d, h, s, cur, r, chest, b, r0, r1, r2, r3, s1, s2, s3, t); } catch (Exception e) { System.err.println(Constants.MY_PLUGIN_NAME + " Timelords to DB Error: " + e); } } } BufferedReader br = null; List<World> worldList = plugin.getServer().getWorlds(); for (World w : worldList) { String strWorldName = w.getName(); File chunkFile = new File(plugin.getDataFolder() + File.separator + "chunks" + File.separator + strWorldName + ".chunks"); if (chunkFile.exists() && w.getEnvironment() == World.Environment.NORMAL) { try { br = new BufferedReader(new FileReader(chunkFile)); String str; int cx = 0, cz = 0; while ((str = br.readLine()) != null) { String[] chunkData = str.split(":"); try { cx = Integer.parseInt(chunkData[1]); cz = Integer.parseInt(chunkData[2]); } catch (NumberFormatException nfe) { System.err.println(Constants.MY_PLUGIN_NAME + " Could not convert to number!"); } try { service.getConnection(); service.insertChunks(chunkData[0], cx, cz); } catch (Exception e) { System.err.println(Constants.MY_PLUGIN_NAME + " Chunk File to DB Error: " + e); } } } catch (IOException io) { System.err.println(Constants.MY_PLUGIN_NAME + " could not create [" + strWorldName + "] world chunk file!"); } } } sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " The config files were successfully inserted into the database."); return true; } if (args.length < 3) { sender.sendMessage("Too few command arguments!"); return false; } else { if (!args[1].equalsIgnoreCase("bonus") && !args[1].equalsIgnoreCase("protect") && !args[1].equalsIgnoreCase("max_rad") && !args[1].equalsIgnoreCase("spout") && !args[1].equalsIgnoreCase("default") && !args[1].equalsIgnoreCase("name") && !args[1].equalsIgnoreCase("include") && !args[1].equalsIgnoreCase("key") && !args[1].equalsIgnoreCase("update") && !args[1].equalsIgnoreCase("exclude") && !args[1].equalsIgnoreCase("platform")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " TARDIS does not recognise that command argument!"); return false; } if (args[1].equalsIgnoreCase("key")) { String setMaterial = args[2].toUpperCase(); if (!Arrays.asList(Materials.MATERIAL_LIST).contains(setMaterial)) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "That is not a valid Material! Try checking http://jd.bukkit.org/apidocs/org/bukkit/Material.html"); return false; } else { plugin.config.set("key", setMaterial); Constants.TARDIS_KEY = setMaterial; } } if (args[1].equalsIgnoreCase("bonus")) { String tf = args[2].toLowerCase(); if (!tf.equals("true") && !tf.equals("false")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "The last argument must be true or false!"); return false; } plugin.config.set("bonus_chest", Boolean.valueOf(tf)); } if (args[1].equalsIgnoreCase("protect")) { String tf = args[2].toLowerCase(); if (!tf.equals("true") && !tf.equals("false")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "The last argument must be true or false!"); return false; } plugin.config.set("protect_blocks", Boolean.valueOf(tf)); } if (args[1].equalsIgnoreCase("platform")) { String tf = args[2].toLowerCase(); if (!tf.equals("true") && !tf.equals("false")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "The last argument must be true or false!"); return false; } plugin.config.set("platform", Boolean.valueOf(tf)); } if (args[1].equalsIgnoreCase("max_rad")) { String a = args[2]; int val; try { val = Integer.parseInt(a); } catch (NumberFormatException nfe) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + " The last argument must be a number!"); return false; } plugin.config.set("tp_radius", val); } if (args[1].equalsIgnoreCase("spout")) { String tf = args[2].toLowerCase(); if (!tf.equals("true") && !tf.equals("false")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "The last argument must be true or false!"); return false; } plugin.config.set("require_spout", Boolean.valueOf(tf)); } if (args[1].equalsIgnoreCase("default")) { String tf = args[2].toLowerCase(); if (!tf.equals("true") && !tf.equals("false")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "The last argument must be true or false!"); return false; } plugin.config.set("default_world", Boolean.valueOf(tf)); } if (args[1].equalsIgnoreCase("name")) { int count = args.length; StringBuilder buf = new StringBuilder(); for (int i = 2; i < count; i++) { buf.append(args[i]).append(" "); } String tmp = buf.toString(); String t = tmp.substring(0, tmp.length() - 1); String nodots = StringUtils.replace(t, ".", "_"); plugin.config.set("default_world_name", nodots); } if (args[1].equalsIgnoreCase("include")) { String tf = args[2].toLowerCase(); if (!tf.equals("true") && !tf.equals("false")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "The last argument must be true or false!"); return false; } plugin.config.set("include_default_world", Boolean.valueOf(tf)); } if (args[1].equalsIgnoreCase("exclude")) { int count = args.length; StringBuilder buf = new StringBuilder(); for (int i = 2; i < count; i++) { buf.append(args[i]).append(" "); } String tmp = buf.toString(); String t = tmp.substring(0, tmp.length() - 1); String nodots = StringUtils.replace(t, ".", "_"); plugin.config.set("worlds." + nodots, false); } try { plugin.config.save(plugin.myconfigfile); sender.sendMessage(Constants.MY_PLUGIN_NAME + " The config was updated!"); } catch (IOException e) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " There was a problem saving the config file!"); } } return true; } if (player == null) { sender.sendMessage("This command can only be run by a player"); return false; } else { if (args[0].equalsIgnoreCase("update")) { if (player.hasPermission("TARDIS.update")) { String[] validBlockNames = {"door", "button", "save-repeater", "x-repeater", "z-repeater", "y-repeater"}; if (args.length < 2) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " Too few command arguments!"); return false; } if (!Arrays.asList(validBlockNames).contains(args[1].toLowerCase())) { player.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " That is not a valid TARDIS block name! Try one of : door|button|save-repeater|x-repeater|z-repeater|y-repeater"); return false; } try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String queryInTARDIS = "SELECT tardis.owner, travellers.player FROM tardis, travellers WHERE travellers.player = '" + player.getName() + "' AND traveller.tardis_id = tardis.tardis_id AND travellers.player = tardis.owner"; ResultSet rs = statement.executeQuery(queryInTARDIS); if (rs == null || !rs.next()) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " Either you are not the Timelord, or you are not inside your TARDIS. You need to be both to run this command!"); return false; } rs.close(); statement.close(); } catch (SQLException e) { System.err.println(Constants.MY_PLUGIN_NAME + " List Saves Error: " + e); } plugin.trackPlayers.put(player.getName(), args[1].toLowerCase()); player.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " Click the TARDIS " + args[1].toLowerCase() + " with to update its position."); return true; } else { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + Constants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("list")) { if (player.hasPermission("TARDIS.list")) { try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String queryList = "SELECT owner FROM tardis WHERE owner = '" + player.getName() + "'"; ResultSet rs = statement.executeQuery(queryList); if (rs == null || !rs.next()) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You have not created a TARDIS yet!"); return false; } Constants.list(player); rs.close(); statement.close(); return true; } catch (SQLException e) { System.err.println(Constants.MY_PLUGIN_NAME + " List Saves Error: " + e); } } else { sender.sendMessage(Constants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("find")) { if (player.hasPermission("TARDIS.find")) { try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String queryList = "SELECT save FROM tardis WHERE owner = '" + player.getName() + "'"; ResultSet rs = statement.executeQuery(queryList); if (rs == null || !rs.next()) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You have not created a TARDIS yet!"); return false; } String loc = rs.getString("save"); String[] findData = loc.split(":"); sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You you left your TARDIS in " + findData[0] + " at x:" + findData[1] + " y:" + findData[2] + " z:" + findData[3]); rs.close(); statement.close(); return true; } catch (SQLException e) { System.err.println(Constants.MY_PLUGIN_NAME + " Find TARDIS Error: " + e); } } else { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + Constants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("add")) { if (player.hasPermission("TARDIS.add")) { try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String queryList = "SELECT tardis_id, companions FROM tardis WHERE owner = '" + player.getName() + "'"; ResultSet rs = statement.executeQuery(queryList); String comps; int id; if (rs == null || !rs.next()) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You have not created a TARDIS yet!"); return false; } else { comps = rs.getString("companions"); id = rs.getInt("tardis_id"); rs.close(); } if (args.length < 2) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " Too few command arguments!"); return false; } else { String queryCompanions; if (comps != null && !comps.equals("") && !comps.equals("[Null]")) { String newList = comps + ":" + args[1]; queryCompanions = "UPDATE tardis SET companions = '" + newList + "' WHERE tardis_id = " + id; } else { queryCompanions = "UPDATE tardis SET companions = '" + args[1] + "' WHERE tardis_id = " + id; } statement.executeUpdate(queryCompanions); player.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You added " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); statement.close(); return true; } } catch (SQLException e) { System.err.println(Constants.MY_PLUGIN_NAME + " Companion Save Error: " + e); } } else { sender.sendMessage(Constants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("remove")) { if (player.hasPermission("TARDIS.add")) { try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String queryList = "SELECT tardis_id, companions FROM tardis WHERE owner = '" + player.getName() + "'"; ResultSet rs = statement.executeQuery(queryList); String comps; int id; if (rs == null || !rs.next()) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You have not created a TARDIS yet!"); return false; } else { id = rs.getInt("tardis_id"); comps = rs.getString("companions"); rs.close(); } if (comps.equals("") || comps.equals("[Null]") || comps == null) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You have not added any TARDIS companions yet!"); return false; } if (args.length < 2) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " Too few command arguments!"); return false; } else { String[] split = comps.split(":"); String newList = ""; for (String c : split) { if (!c.equals(args[1])) { newList += c + ":"; } } newList = newList.substring(0, newList.length() - 1); String queryCompanions = "UPDATE tardis SET companions = '" + newList + "' WHERE tardis_id = " + id; statement.executeUpdate(queryCompanions); player.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You removed " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); statement.close(); return true; } } catch (SQLException e) { System.err.println(Constants.MY_PLUGIN_NAME + " Companion Save Error: " + e); } } else { sender.sendMessage(Constants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("save")) { if (player.hasPermission("TARDIS.save")) { try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String queryList = "SELECT * FROM tardis WHERE owner = '" + player.getName() + "'"; ResultSet rs = statement.executeQuery(queryList); if (rs == null || !rs.next()) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You have not created a TARDIS yet!"); return false; } if (args.length < 3) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " Too few command arguments!"); return false; } else { String cur = rs.getString("current"); String sav = rs.getString("save"); int id = rs.getInt("tardis_id"); int count = args.length; StringBuilder buf = new StringBuilder(); for (int i = 2; i < count; i++) { buf.append(args[i]).append(" "); } String tmp = buf.toString(); String t = tmp.substring(0, tmp.length() - 1); String nodots = StringUtils.replace(t, ".", "_"); String curDest; String queryTraveller = "SELECT * FROM travellers WHERE player = '" + player.getName() + "'"; ResultSet rsTraveller = statement.executeQuery(queryTraveller); if (rsTraveller != null && rsTraveller.next()) { curDest = nodots + ":" + cur; } else { curDest = nodots + "~" + sav; } String querySave = "UPDATE tardis SET save" + args[1] + " = '" + curDest + "' WHERE tardis_id = " + id; statement.executeUpdate(querySave); rs.close(); rsTraveller.close(); statement.close(); return true; } } catch (SQLException e) { System.err.println(Constants.MY_PLUGIN_NAME + " Companion Save Error: " + e); } } else { sender.sendMessage(Constants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("help")) { if (args.length == 1) { sender.sendMessage(Constants.COMMANDS.split("\n")); return true; } if (args.length == 2) { switch (Constants.fromString(args[1])) { case CREATE: sender.sendMessage(Constants.COMMAND_CREATE.split("\n")); break; case DELETE: sender.sendMessage(Constants.COMMAND_DELETE.split("\n")); break; case TIMETRAVEL: sender.sendMessage(Constants.COMMAND_TIMETRAVEL.split("\n")); break; case LIST: sender.sendMessage(Constants.COMMAND_LIST.split("\n")); break; case FIND: sender.sendMessage(Constants.COMMAND_FIND.split("\n")); break; case SAVE: sender.sendMessage(Constants.COMMAND_SAVE.split("\n")); break; case ADD: sender.sendMessage(Constants.COMMAND_ADD.split("\n")); break; case ADMIN: sender.sendMessage(Constants.COMMAND_ADMIN.split("\n")); break; default: sender.sendMessage(Constants.COMMANDS.split("\n")); } } return true; } } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("tardis")) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { sender.sendMessage(Constants.COMMANDS.split("\n")); return true; } if (!args[0].equalsIgnoreCase("save") && !args[0].equalsIgnoreCase("list") && !args[0].equalsIgnoreCase("admin") && !args[0].equalsIgnoreCase("help") && !args[0].equalsIgnoreCase("find") && !args[0].equalsIgnoreCase("reload") && !args[0].equalsIgnoreCase("add") && !args[0].equalsIgnoreCase("remove") && !args[0].equalsIgnoreCase("update")) { sender.sendMessage("Do you want to list destinations, save a destination, update the TARDIS, add/remove companions, do some admin stuff or find the TARDIS?"); return false; } if (args[0].equalsIgnoreCase("reload")) { plugin.loadConfig(); sender.sendMessage("TARDIS config reloaded."); } if (args[0].equalsIgnoreCase("admin")) { if (args.length == 1) { sender.sendMessage(Constants.COMMAND_ADMIN.split("\n")); return true; } if (args[1].equalsIgnoreCase("update")) { Set<String> timelords = plugin.timelords.getKeys(false); for (String p : timelords) { if (!p.equals("dummy_user")) { String c = plugin.timelords.getString(p + ".chunk"); String d = plugin.timelords.getString(p + ".direction"); String h = plugin.timelords.getString(p + ".home"); String s = plugin.timelords.getString(p + ".save"); String cur = plugin.timelords.getString(p + ".current"); String r = plugin.timelords.getString(p + ".replaced"); String chest = plugin.timelords.getString(p + ".chest"); String b = plugin.timelords.getString(p + ".button"); String r0 = plugin.timelords.getString(p + ".repeater0"); String r1 = plugin.timelords.getString(p + ".repeater1"); String r2 = plugin.timelords.getString(p + ".repeater2"); String r3 = plugin.timelords.getString(p + ".repeater3"); String s1 = plugin.timelords.getString(p + ".save1"); String s2 = plugin.timelords.getString(p + ".save2"); String s3 = plugin.timelords.getString(p + ".save3"); String t = plugin.timelords.getString(p + ".travelling"); try { service.getConnection(); service.insertTimelords(p, c, d, h, s, cur, r, chest, b, r0, r1, r2, r3, s1, s2, s3, t); } catch (Exception e) { System.err.println(Constants.MY_PLUGIN_NAME + " Timelords to DB Error: " + e); } } } BufferedReader br = null; List<World> worldList = plugin.getServer().getWorlds(); for (World w : worldList) { String strWorldName = w.getName(); File chunkFile = new File(plugin.getDataFolder() + File.separator + "chunks" + File.separator + strWorldName + ".chunks"); if (chunkFile.exists() && w.getEnvironment() == World.Environment.NORMAL) { try { br = new BufferedReader(new FileReader(chunkFile)); String str; int cx = 0, cz = 0; while ((str = br.readLine()) != null) { String[] chunkData = str.split(":"); try { cx = Integer.parseInt(chunkData[1]); cz = Integer.parseInt(chunkData[2]); } catch (NumberFormatException nfe) { System.err.println(Constants.MY_PLUGIN_NAME + " Could not convert to number!"); } try { service.getConnection(); service.insertChunks(chunkData[0], cx, cz); } catch (Exception e) { System.err.println(Constants.MY_PLUGIN_NAME + " Chunk File to DB Error: " + e); } } } catch (IOException io) { System.err.println(Constants.MY_PLUGIN_NAME + " could not create [" + strWorldName + "] world chunk file!"); } } } sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " The config files were successfully inserted into the database."); return true; } if (args.length < 3) { sender.sendMessage("Too few command arguments!"); return false; } else { if (!args[1].equalsIgnoreCase("bonus") && !args[1].equalsIgnoreCase("protect") && !args[1].equalsIgnoreCase("max_rad") && !args[1].equalsIgnoreCase("spout") && !args[1].equalsIgnoreCase("default") && !args[1].equalsIgnoreCase("name") && !args[1].equalsIgnoreCase("include") && !args[1].equalsIgnoreCase("key") && !args[1].equalsIgnoreCase("update") && !args[1].equalsIgnoreCase("exclude") && !args[1].equalsIgnoreCase("platform")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " TARDIS does not recognise that command argument!"); return false; } if (args[1].equalsIgnoreCase("key")) { String setMaterial = args[2].toUpperCase(); if (!Arrays.asList(Materials.MATERIAL_LIST).contains(setMaterial)) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "That is not a valid Material! Try checking http://jd.bukkit.org/apidocs/org/bukkit/Material.html"); return false; } else { plugin.config.set("key", setMaterial); Constants.TARDIS_KEY = setMaterial; } } if (args[1].equalsIgnoreCase("bonus")) { String tf = args[2].toLowerCase(); if (!tf.equals("true") && !tf.equals("false")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "The last argument must be true or false!"); return false; } plugin.config.set("bonus_chest", Boolean.valueOf(tf)); } if (args[1].equalsIgnoreCase("protect")) { String tf = args[2].toLowerCase(); if (!tf.equals("true") && !tf.equals("false")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "The last argument must be true or false!"); return false; } plugin.config.set("protect_blocks", Boolean.valueOf(tf)); } if (args[1].equalsIgnoreCase("platform")) { String tf = args[2].toLowerCase(); if (!tf.equals("true") && !tf.equals("false")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "The last argument must be true or false!"); return false; } plugin.config.set("platform", Boolean.valueOf(tf)); } if (args[1].equalsIgnoreCase("max_rad")) { String a = args[2]; int val; try { val = Integer.parseInt(a); } catch (NumberFormatException nfe) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + " The last argument must be a number!"); return false; } plugin.config.set("tp_radius", val); } if (args[1].equalsIgnoreCase("spout")) { String tf = args[2].toLowerCase(); if (!tf.equals("true") && !tf.equals("false")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "The last argument must be true or false!"); return false; } plugin.config.set("require_spout", Boolean.valueOf(tf)); } if (args[1].equalsIgnoreCase("default")) { String tf = args[2].toLowerCase(); if (!tf.equals("true") && !tf.equals("false")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "The last argument must be true or false!"); return false; } plugin.config.set("default_world", Boolean.valueOf(tf)); } if (args[1].equalsIgnoreCase("name")) { int count = args.length; StringBuilder buf = new StringBuilder(); for (int i = 2; i < count; i++) { buf.append(args[i]).append(" "); } String tmp = buf.toString(); String t = tmp.substring(0, tmp.length() - 1); String nodots = StringUtils.replace(t, ".", "_"); plugin.config.set("default_world_name", nodots); } if (args[1].equalsIgnoreCase("include")) { String tf = args[2].toLowerCase(); if (!tf.equals("true") && !tf.equals("false")) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RED + "The last argument must be true or false!"); return false; } plugin.config.set("include_default_world", Boolean.valueOf(tf)); } if (args[1].equalsIgnoreCase("exclude")) { int count = args.length; StringBuilder buf = new StringBuilder(); for (int i = 2; i < count; i++) { buf.append(args[i]).append(" "); } String tmp = buf.toString(); String t = tmp.substring(0, tmp.length() - 1); String nodots = StringUtils.replace(t, ".", "_"); plugin.config.set("worlds." + nodots, false); } try { plugin.config.save(plugin.myconfigfile); sender.sendMessage(Constants.MY_PLUGIN_NAME + " The config was updated!"); } catch (IOException e) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " There was a problem saving the config file!"); } } return true; } if (player == null) { sender.sendMessage("This command can only be run by a player"); return false; } else { if (args[0].equalsIgnoreCase("update")) { if (player.hasPermission("TARDIS.update")) { String[] validBlockNames = {"door", "button", "save-repeater", "x-repeater", "z-repeater", "y-repeater"}; if (args.length < 2) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " Too few command arguments!"); return false; } if (!Arrays.asList(validBlockNames).contains(args[1].toLowerCase())) { player.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " That is not a valid TARDIS block name! Try one of : door|button|save-repeater|x-repeater|z-repeater|y-repeater"); return false; } try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String queryInTARDIS = "SELECT tardis.owner, travellers.player FROM tardis, travellers WHERE travellers.player = '" + player.getName() + "' AND travellers.tardis_id = tardis.tardis_id AND travellers.player = tardis.owner"; ResultSet rs = statement.executeQuery(queryInTARDIS); if (rs == null || !rs.next()) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " Either you are not the Timelord, or you are not inside your TARDIS. You need to be both to run this command!"); return false; } rs.close(); statement.close(); } catch (SQLException e) { System.err.println(Constants.MY_PLUGIN_NAME + " List Saves Error: " + e); } plugin.trackPlayers.put(player.getName(), args[1].toLowerCase()); player.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " Click the TARDIS " + args[1].toLowerCase() + " with to update its position."); return true; } else { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + Constants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("list")) { if (player.hasPermission("TARDIS.list")) { try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String queryList = "SELECT owner FROM tardis WHERE owner = '" + player.getName() + "'"; ResultSet rs = statement.executeQuery(queryList); if (rs == null || !rs.next()) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You have not created a TARDIS yet!"); return false; } Constants.list(player); rs.close(); statement.close(); return true; } catch (SQLException e) { System.err.println(Constants.MY_PLUGIN_NAME + " List Saves Error: " + e); } } else { sender.sendMessage(Constants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("find")) { if (player.hasPermission("TARDIS.find")) { try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String queryList = "SELECT save FROM tardis WHERE owner = '" + player.getName() + "'"; ResultSet rs = statement.executeQuery(queryList); if (rs == null || !rs.next()) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You have not created a TARDIS yet!"); return false; } String loc = rs.getString("save"); String[] findData = loc.split(":"); sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You you left your TARDIS in " + findData[0] + " at x:" + findData[1] + " y:" + findData[2] + " z:" + findData[3]); rs.close(); statement.close(); return true; } catch (SQLException e) { System.err.println(Constants.MY_PLUGIN_NAME + " Find TARDIS Error: " + e); } } else { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + Constants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("add")) { if (player.hasPermission("TARDIS.add")) { try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String queryList = "SELECT tardis_id, companions FROM tardis WHERE owner = '" + player.getName() + "'"; ResultSet rs = statement.executeQuery(queryList); String comps; int id; if (rs == null || !rs.next()) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You have not created a TARDIS yet!"); return false; } else { comps = rs.getString("companions"); id = rs.getInt("tardis_id"); rs.close(); } if (args.length < 2) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " Too few command arguments!"); return false; } else { String queryCompanions; if (comps != null && !comps.equals("") && !comps.equals("[Null]")) { String newList = comps + ":" + args[1]; queryCompanions = "UPDATE tardis SET companions = '" + newList + "' WHERE tardis_id = " + id; } else { queryCompanions = "UPDATE tardis SET companions = '" + args[1] + "' WHERE tardis_id = " + id; } statement.executeUpdate(queryCompanions); player.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You added " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); statement.close(); return true; } } catch (SQLException e) { System.err.println(Constants.MY_PLUGIN_NAME + " Companion Save Error: " + e); } } else { sender.sendMessage(Constants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("remove")) { if (player.hasPermission("TARDIS.add")) { try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String queryList = "SELECT tardis_id, companions FROM tardis WHERE owner = '" + player.getName() + "'"; ResultSet rs = statement.executeQuery(queryList); String comps; int id; if (rs == null || !rs.next()) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You have not created a TARDIS yet!"); return false; } else { id = rs.getInt("tardis_id"); comps = rs.getString("companions"); rs.close(); } if (comps.equals("") || comps.equals("[Null]") || comps == null) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You have not added any TARDIS companions yet!"); return false; } if (args.length < 2) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " Too few command arguments!"); return false; } else { String[] split = comps.split(":"); String newList = ""; for (String c : split) { if (!c.equals(args[1])) { newList += c + ":"; } } newList = newList.substring(0, newList.length() - 1); String queryCompanions = "UPDATE tardis SET companions = '" + newList + "' WHERE tardis_id = " + id; statement.executeUpdate(queryCompanions); player.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You removed " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); statement.close(); return true; } } catch (SQLException e) { System.err.println(Constants.MY_PLUGIN_NAME + " Companion Save Error: " + e); } } else { sender.sendMessage(Constants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("save")) { if (player.hasPermission("TARDIS.save")) { try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String queryList = "SELECT * FROM tardis WHERE owner = '" + player.getName() + "'"; ResultSet rs = statement.executeQuery(queryList); if (rs == null || !rs.next()) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " You have not created a TARDIS yet!"); return false; } if (args.length < 3) { sender.sendMessage(ChatColor.GRAY + Constants.MY_PLUGIN_NAME + ChatColor.RESET + " Too few command arguments!"); return false; } else { String cur = rs.getString("current"); String sav = rs.getString("save"); int id = rs.getInt("tardis_id"); int count = args.length; StringBuilder buf = new StringBuilder(); for (int i = 2; i < count; i++) { buf.append(args[i]).append(" "); } String tmp = buf.toString(); String t = tmp.substring(0, tmp.length() - 1); String nodots = StringUtils.replace(t, ".", "_"); String curDest; String queryTraveller = "SELECT * FROM travellers WHERE player = '" + player.getName() + "'"; ResultSet rsTraveller = statement.executeQuery(queryTraveller); if (rsTraveller != null && rsTraveller.next()) { curDest = nodots + ":" + cur; } else { curDest = nodots + "~" + sav; } String querySave = "UPDATE tardis SET save" + args[1] + " = '" + curDest + "' WHERE tardis_id = " + id; statement.executeUpdate(querySave); rs.close(); rsTraveller.close(); statement.close(); return true; } } catch (SQLException e) { System.err.println(Constants.MY_PLUGIN_NAME + " Companion Save Error: " + e); } } else { sender.sendMessage(Constants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("help")) { if (args.length == 1) { sender.sendMessage(Constants.COMMANDS.split("\n")); return true; } if (args.length == 2) { switch (Constants.fromString(args[1])) { case CREATE: sender.sendMessage(Constants.COMMAND_CREATE.split("\n")); break; case DELETE: sender.sendMessage(Constants.COMMAND_DELETE.split("\n")); break; case TIMETRAVEL: sender.sendMessage(Constants.COMMAND_TIMETRAVEL.split("\n")); break; case LIST: sender.sendMessage(Constants.COMMAND_LIST.split("\n")); break; case FIND: sender.sendMessage(Constants.COMMAND_FIND.split("\n")); break; case SAVE: sender.sendMessage(Constants.COMMAND_SAVE.split("\n")); break; case ADD: sender.sendMessage(Constants.COMMAND_ADD.split("\n")); break; case ADMIN: sender.sendMessage(Constants.COMMAND_ADMIN.split("\n")); break; default: sender.sendMessage(Constants.COMMANDS.split("\n")); } } return true; } } } return false; }
protected void initLayout() { setHeaderVisible(true); setLayout(new BorderLayout()); setCollapsible(false); setBodyBorder(false); setFrame(false); setHeaderVisible(false); setBodyStyle("backgroundColor: white;"); setHeight(920); getHeader().addTool(new ToolButton("x-tool-gear")); getHeader().addTool(new ToolButton("x-tool-close")); BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST, 760); westData.setMinSize(50); westData.setMaxSize(1000); westData.setMargins(new Margins(5)); westData.setSplit(true); westData.setCollapsible(true); BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER); ; centerData.setMargins(new Margins(5, 0, 5, 0)); final ContentPanel controlsContainer = new ContentPanel(); controlsContainer.setFrame(true); controlsContainer.setBorders(true); controlsContainer.setHeading("Controls"); controlsContainer.setScrollMode(Scroll.AUTO); calendarControl = new CalendarControl(this); calendarControl.setCollapsible(true); controlsContainer.add(calendarControl); scheduleControl = new ScheduleControl(this); scheduleControl.setCollapsible(true); controlsContainer.add(scheduleControl); scheduleExplorer = new ScheduleCalendar(startCalendarDay, numCalendarDays); scheduleExplorer.addButtonsListener(this); scheduleExplorer.setDefaultDate(startCalendarDay); scheduleExplorer.setCollapsible(true); scheduleExplorer.setAutoHeight(true); controlsContainer.add(scheduleExplorer); vacancyControl = new VacancyControl(this); vacancyControl.setCollapsible(true); vacancyControl.collapse(); controlsContainer.add(vacancyControl); nomineePanel = new NomineePanel(this); nomineePanel.setCollapsible(true); nomineePanel.collapse(); controlsContainer.add(nomineePanel); reservations = new Reservations(startCalendarDay, numCalendarDays); reservations.setCollapsible(true); reservations.collapse(); controlsContainer.add(reservations); calendar = new ContentPanel(); calendar.setHeading("Calendar"); calendar.setScrollMode(Scroll.AUTOX); calendar.setStyleAttribute("bgcolor", "black"); FormPanel fp = new FormPanel(); fp.setHeaderVisible(false); fp.setBorders(false); fp.setLayout(new RowLayout(Orientation.HORIZONTAL)); fp.setHeight(40); fp.setWidth("100%"); fp.setStyleAttribute("background", "#E9EEF6"); LabelField pending = new LabelField("Legend"); pending.setStyleAttribute("color", "#F2A640"); pending.setValue("Pending"); fp.add(pending, new RowData(-1, -1, new Margins(0, 10, 0, 10))); LabelField fixed = new LabelField("Legend"); fixed.setStyleAttribute("color", "#D96666"); fixed.setValue("Fixed"); fp.add(fixed, new RowData(-1, -1, new Margins(0, 10, 0, 10))); LabelField open = new LabelField("Legend"); open.setStyleAttribute("color", "#668CD9"); open.setValue("Open"); fp.add(open, new RowData(-1, -1, new Margins(0, 10, 0, 10))); LabelField dwindow = new LabelField("Legend"); dwindow.setStyleAttribute("color", "#4CB052"); dwindow.setValue("Default Windowed"); dwindow.setWidth(120); fp.add(dwindow, new RowData(-1, -1, new Margins(0, 10, 0, 10))); LabelField ndwindow = new LabelField("Legend"); ndwindow.setStyleAttribute("color", "#BFBF4D"); ndwindow.setValue("Non-Default Windowed"); ndwindow.setWidth(150); fp.add(ndwindow, new RowData(-1, -1, new Margins(0, 10, 0, 10))); LabelField elwindow = new LabelField("Legend"); elwindow.setStyleAttribute("color", "#8C66D9"); elwindow.setValue("Elective"); fp.add(elwindow, new RowData(-1, -1, new Margins(0, 10, 0, 10))); calendar.add(fp); dayView = new DayView(); dayView.setDate(startCalendarDay); dayView.setDays((int) numCalendarDays); dayView.setWidth("100%"); dayView.setHeight("97%"); dayView.setTitle("Schedule Calendar"); CalendarSettings settings = new CalendarSettings(); settings.setOffsetHourLabels(false); settings.setIntervalsPerHour(4); settings.setEnableDragDrop(true); settings.setPixelsPerInterval(12); dayView.setSettings(settings); getSessionOptions(); dayView.addValueChangeHandler(new ValueChangeHandler<Appointment>(){ public void onValueChange(ValueChangeEvent<Appointment> event) { String periodUrl = "/periods/UTC/" + event.getValue().getEventId(); JSONRequest.get(periodUrl, new JSONCallbackAdapter() { @Override public void onSuccess(JSONObject json) { Period period = Period.parseJSON(json.get("period").isObject()); PeriodSummaryDlg dlg = new PeriodSummaryDlg(period, sess_handles, (Schedule) controlsContainer.getParent()); } }); } }); calendar.add(dayView); add(controlsContainer, westData); add(calendar, centerData); updateCalendar(); }
protected void initLayout() { setHeaderVisible(true); setLayout(new BorderLayout()); setCollapsible(false); setBodyBorder(false); setFrame(false); setHeaderVisible(false); setBodyStyle("backgroundColor: white;"); setHeight(920); getHeader().addTool(new ToolButton("x-tool-gear")); getHeader().addTool(new ToolButton("x-tool-close")); BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST, 760); westData.setMinSize(50); westData.setMaxSize(1000); westData.setMargins(new Margins(5)); westData.setSplit(true); westData.setCollapsible(true); BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER); ; centerData.setMargins(new Margins(5, 0, 5, 0)); final ContentPanel controlsContainer = new ContentPanel(); controlsContainer.setFrame(true); controlsContainer.setBorders(true); controlsContainer.setHeading("Controls"); controlsContainer.setScrollMode(Scroll.AUTO); calendarControl = new CalendarControl(this); calendarControl.setCollapsible(true); controlsContainer.add(calendarControl); scheduleControl = new ScheduleControl(this); scheduleControl.setCollapsible(true); controlsContainer.add(scheduleControl); scheduleExplorer = new ScheduleCalendar(startCalendarDay, numCalendarDays); scheduleExplorer.addButtonsListener(this); scheduleExplorer.setDefaultDate(startCalendarDay); scheduleExplorer.setCollapsible(true); scheduleExplorer.setAutoHeight(true); controlsContainer.add(scheduleExplorer); vacancyControl = new VacancyControl(this); vacancyControl.setCollapsible(true); vacancyControl.collapse(); controlsContainer.add(vacancyControl); nomineePanel = new NomineePanel(this); nomineePanel.setCollapsible(true); nomineePanel.collapse(); controlsContainer.add(nomineePanel); reservations = new Reservations(startCalendarDay, numCalendarDays); reservations.setCollapsible(true); reservations.collapse(); controlsContainer.add(reservations); calendar = new ContentPanel(); calendar.setHeading("Calendar"); calendar.setScrollMode(Scroll.AUTOX); calendar.setStyleAttribute("bgcolor", "black"); FormPanel fp = new FormPanel(); fp.setHeaderVisible(false); fp.setBorders(false); fp.setLayout(new RowLayout(Orientation.HORIZONTAL)); fp.setHeight(40); fp.setWidth("100%"); fp.setStyleAttribute("background", "#E9EEF6"); LabelField pending = new LabelField("Legend"); pending.setStyleAttribute("color", "#F2A640"); pending.setValue("Pending"); fp.add(pending, new RowData(-1, -1, new Margins(0, 10, 0, 10))); LabelField fixed = new LabelField("Legend"); fixed.setStyleAttribute("color", "#D96666"); fixed.setValue("Fixed"); fp.add(fixed, new RowData(-1, -1, new Margins(0, 10, 0, 10))); LabelField open = new LabelField("Legend"); open.setStyleAttribute("color", "#668CD9"); open.setValue("Open"); fp.add(open, new RowData(-1, -1, new Margins(0, 10, 0, 10))); LabelField dwindow = new LabelField("Legend"); dwindow.setStyleAttribute("color", "#4CB052"); dwindow.setValue("Default Windowed"); dwindow.setWidth(120); fp.add(dwindow, new RowData(-1, -1, new Margins(0, 10, 0, 10))); LabelField ndwindow = new LabelField("Legend"); ndwindow.setStyleAttribute("color", "#BFBF4D"); ndwindow.setValue("Non-Default Windowed"); ndwindow.setWidth(150); fp.add(ndwindow, new RowData(-1, -1, new Margins(0, 10, 0, 10))); LabelField elwindow = new LabelField("Legend"); elwindow.setStyleAttribute("color", "#8C66D9"); elwindow.setValue("Elective"); fp.add(elwindow, new RowData(-1, -1, new Margins(0, 10, 0, 10))); calendar.add(fp); calendar.setScrollMode(Scroll.NONE); dayView = new DayView(); dayView.setDate(startCalendarDay); dayView.setDays((int) numCalendarDays); dayView.setWidth("100%"); dayView.setHeight("96%"); dayView.setTitle("Schedule Calendar"); CalendarSettings settings = new CalendarSettings(); settings.setOffsetHourLabels(false); settings.setIntervalsPerHour(4); settings.setEnableDragDrop(true); settings.setPixelsPerInterval(12); dayView.setSettings(settings); getSessionOptions(); dayView.addValueChangeHandler(new ValueChangeHandler<Appointment>(){ public void onValueChange(ValueChangeEvent<Appointment> event) { String periodUrl = "/periods/UTC/" + event.getValue().getEventId(); JSONRequest.get(periodUrl, new JSONCallbackAdapter() { @Override public void onSuccess(JSONObject json) { Period period = Period.parseJSON(json.get("period").isObject()); PeriodSummaryDlg dlg = new PeriodSummaryDlg(period, sess_handles, (Schedule) controlsContainer.getParent()); } }); } }); calendar.add(dayView); add(controlsContainer, westData); add(calendar, centerData); updateCalendar(); }
public static void main(String[] args) { String configFileArg = null; String lookAndFeelArg = null; boolean devMode = false; for (int i = 0; i < args.length; i++) { if (LOOK_AND_FEEL_FLAG.equals(args[i])) { if (args.length == (i + 1)) { exitOnErrorMessage("No look & feel parameter specified."); } else { i++; lookAndFeelArg = args[i]; } } else if (DEVELOPMENT_FLAG.equals(args[i])) { devMode = true; } else { configFileArg = args[i]; } } try { if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") == -1) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } else { if (lookAndFeelArg != null) { if ("native".equals(lookAndFeelArg)) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } else if ("plastic".equals(lookAndFeelArg)) { PlasticLookAndFeel.setMyCurrentTheme(new SkyBlue()); UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } else { UIManager.setLookAndFeel(lookAndFeelArg); } } else { PlasticLookAndFeel.setMyCurrentTheme(new SkyBlue()); UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } } } catch (Exception e) { log.error(e,e); } splash.hideOnClick(); splash.addAutoProgressBarIndeterminate(); splash.setProgressBarString("loading..."); splash.showSplash(); initProperties(); if (!devMode) { log.info("Scanning plugins..."); String componentsDir = System.getProperty(COMPONENTS_DIR_PROPERTY); if (componentsDir == null) { componentsDir = DEFAULT_COMPONENTS_DIR; } ComponentRegistry.getRegistry().initializeComponentResources(componentsDir); ComponentRegistry.getRegistry().initializeGearResources(DEFAULT_GEAR_DIR); log.info("... scan complete."); } else { log.info("Development mode-- skipping plugin scan."); } configure(); org.geworkbench.util.Debug.debugStatus = false; String configFileName = null; if (configFileArg != null) { configFileName = configFileArg; } else { configFileName = System.getProperty(CONFIG_FILE_NAME); if (configFileName == null) exitOnErrorMessage("Invalid or absent configuration file."); } try { InputStream is = Class.forName(UILauncher.class.getName()).getResourceAsStream("/" + configFileName); if (is == null) { exitOnErrorMessage("Invalid or absent configuration file."); } log.debug("Digester Test Program"); log.debug("Opening input stream ..."); log.debug("Creating new digester ..."); log.debug("Parsing input stream ..."); uiLauncher.parse(is); log.debug("Closing input stream ..."); is.close(); } catch (Exception e) { log.error(e,e); } PluginRegistry.debugPrint(); splash.hideSplash(); }
public static void main(String[] args) { String configFileArg = null; String lookAndFeelArg = null; boolean devMode = false; for (int i = 0; i < args.length; i++) { if (LOOK_AND_FEEL_FLAG.equals(args[i])) { if (args.length == (i + 1)) { exitOnErrorMessage("No look & feel parameter specified."); } else { i++; lookAndFeelArg = args[i]; } } else if (DEVELOPMENT_FLAG.equals(args[i])) { devMode = true; } else { configFileArg = args[i]; } } try { if (System.getProperty("os.name").toUpperCase().indexOf("MAC OS X") > -1) { PlasticLookAndFeel.setMyCurrentTheme(new SkyBlue()); UIManager .setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } else if (System.getProperty("os.name").toUpperCase().indexOf( "Solaris") > -1) { PlasticLookAndFeel.setMyCurrentTheme(new SkyBlue()); UIManager .setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } else if (System.getProperty("os.name").toUpperCase().indexOf( "WINDOWS") == -1) { UIManager.setLookAndFeel(UIManager .getSystemLookAndFeelClassName()); } else { if (lookAndFeelArg != null) { if ("native".equals(lookAndFeelArg)) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } else if ("plastic".equals(lookAndFeelArg)) { PlasticLookAndFeel.setMyCurrentTheme(new SkyBlue()); UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } else { UIManager.setLookAndFeel(lookAndFeelArg); } } else { PlasticLookAndFeel.setMyCurrentTheme(new SkyBlue()); UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } } } catch (Exception e) { log.error(e,e); } splash.hideOnClick(); splash.addAutoProgressBarIndeterminate(); splash.setProgressBarString("loading..."); splash.showSplash(); initProperties(); if (!devMode) { log.info("Scanning plugins..."); String componentsDir = System.getProperty(COMPONENTS_DIR_PROPERTY); if (componentsDir == null) { componentsDir = DEFAULT_COMPONENTS_DIR; } ComponentRegistry.getRegistry().initializeComponentResources(componentsDir); ComponentRegistry.getRegistry().initializeGearResources(DEFAULT_GEAR_DIR); log.info("... scan complete."); } else { log.info("Development mode-- skipping plugin scan."); } configure(); org.geworkbench.util.Debug.debugStatus = false; String configFileName = null; if (configFileArg != null) { configFileName = configFileArg; } else { configFileName = System.getProperty(CONFIG_FILE_NAME); if (configFileName == null) exitOnErrorMessage("Invalid or absent configuration file."); } try { InputStream is = Class.forName(UILauncher.class.getName()).getResourceAsStream("/" + configFileName); if (is == null) { exitOnErrorMessage("Invalid or absent configuration file."); } log.debug("Digester Test Program"); log.debug("Opening input stream ..."); log.debug("Creating new digester ..."); log.debug("Parsing input stream ..."); uiLauncher.parse(is); log.debug("Closing input stream ..."); is.close(); } catch (Exception e) { log.error(e,e); } PluginRegistry.debugPrint(); splash.hideSplash(); }
public ValueData getValue() throws RegistryParseException, UnsupportedEncodingException { RegistryValueType t = this.getValueType(); long length = this.getRawDataLength(); int offset = (int)this.getDataOffset(); if (length > LARGE_DATA_SIZE + DB_DATA_SIZE) { throw new RegistryParseException("Value size too large: " + length); } switch(t) { case REG_BIN: case REG_NONE: case REG_SZ: case REG_EXPAND_SZ: case REG_MULTI_SZ: case REG_LINK: case REG_RESOURCE_LIST: case REG_FULL_RESOURCE_DESCRIPTOR: case REG_RESOURCE_REQUIREMENTS_LIST: { ByteBuffer data; if (length >= LARGE_DATA_SIZE) { int bufSize = (int)(length - LARGE_DATA_SIZE); data = ByteBuffer.allocate(bufSize); data.position(0x0); data.limit(bufSize); for (int i = 0; i < bufSize; i++) { data.put(this.getByte(DATA_OFFSET_OFFSET + i)); } } else if (DB_DATA_SIZE < length && length < LARGE_DATA_SIZE) { Cell c = new Cell(this._buf, offset); try { DBRecord db = c.getDBRecord(); data = db.getData((int)length); } catch (RegistryParseException e) { data = c.getData(); data.limit((int)length); } } else { Cell c = new Cell(this._buf, offset); data = c.getData(); data.limit((int)length); } return new ValueData(data, t); } case REG_DWORD: case REG_BIG_ENDIAN: { ByteBuffer data; int bufSize = 0x4; data = ByteBuffer.allocate(bufSize); data.position(0x0); data.limit(bufSize); for (int i = 0; i < bufSize; i++) { data.put(this.getByte(DATA_OFFSET_OFFSET + i)); } return new ValueData(data, t); } case REG_QWORD: { ByteBuffer data; int bufSize = 0x8; data = ByteBuffer.allocate(bufSize); data.position(0x0); data.limit(bufSize); for (int i = 0; i < bufSize; i++) { data.put(this.getByte(DATA_OFFSET_OFFSET + i)); } return new ValueData(data, t); } default: { throw new NotImplementedException(); } } }
public ValueData getValue() throws RegistryParseException, UnsupportedEncodingException { RegistryValueType t = this.getValueType(); long length = this.getRawDataLength(); int offset = (int)this.getDataOffset(); if (length > LARGE_DATA_SIZE + DB_DATA_SIZE) { throw new RegistryParseException("Value size too large: " + length); } switch(t) { case REG_BIN: case REG_NONE: case REG_SZ: case REG_EXPAND_SZ: case REG_MULTI_SZ: case REG_LINK: case REG_RESOURCE_LIST: case REG_FULL_RESOURCE_DESCRIPTOR: case REG_RESOURCE_REQUIREMENTS_LIST: { ByteBuffer data; if (length >= LARGE_DATA_SIZE) { int bufSize = (int)(length - LARGE_DATA_SIZE); data = ByteBuffer.allocate(bufSize); data.position(0x0); data.limit(bufSize); for (int i = 0; i < bufSize; i++) { data.put(this.getByte(DATA_OFFSET_OFFSET + i)); } } else if (DB_DATA_SIZE < length && length < LARGE_DATA_SIZE) { Cell c = new Cell(this._buf, offset); try { DBRecord db = c.getDBRecord(); data = db.getData((int)length); } catch (RegistryParseException e) { data = c.getData(); data.limit((int)length); } } else { Cell c = new Cell(this._buf, offset); data = c.getData(); data.limit((int)length); } data.position(0x0); return new ValueData(data, t); } case REG_DWORD: case REG_BIG_ENDIAN: { ByteBuffer data; int bufSize = 0x4; data = ByteBuffer.allocate(bufSize); data.position(0x0); data.limit(bufSize); for (int i = 0; i < bufSize; i++) { data.put(this.getByte(DATA_OFFSET_OFFSET + i)); } data.position(0x0); return new ValueData(data, t); } case REG_QWORD: { ByteBuffer data; int bufSize = 0x8; data = ByteBuffer.allocate(bufSize); data.position(0x0); data.limit(bufSize); for (int i = 0; i < bufSize; i++) { data.put(this.getByte(DATA_OFFSET_OFFSET + i)); } data.position(0x0); return new ValueData(data, t); } default: { throw new NotImplementedException(); } } }
public Vertex getClosestVertex(final Coordinate coordinate, String name, RoutingRequest options, List<Edge> extraEdges) { _log.debug("Looking for/making a vertex near {}", coordinate); StreetVertex intersection = getIntersectionAt(coordinate, MAX_CORNER_DISTANCE); if (intersection != null) { if (name == null) { Set<String> uniqueNameSet = new HashSet<String>(); for (Edge e : intersection.getOutgoing()) { if (e instanceof StreetEdge) { uniqueNameSet.add(e.getName()); } } List<String> uniqueNames = new ArrayList<String>(uniqueNameSet); Locale locale; if (options == null) { locale = new Locale("en"); } else { locale = options.getLocale(); } ResourceBundle resources = ResourceBundle.getBundle("internals", locale); String fmt = resources.getString("corner"); if (uniqueNames.size() > 1) { name = String.format(fmt, uniqueNames.get(0), uniqueNames.get(1)); } else if (uniqueNames.size() == 1) { name = uniqueNames.get(0); } else { name = resources.getString("unnamedStreet"); } } StreetLocation closest = new StreetLocation(graph, "corner " + Math.random(), coordinate, name); FreeEdge e = new FreeEdge(closest, intersection); closest.getExtra().add(e); e = new FreeEdge(intersection, closest); closest.getExtra().add(e); return closest; } double closest_stop_distance = Double.POSITIVE_INFINITY; Vertex closest_stop = null; if (options != null && options.getModes().isTransit()) { for (Vertex v : getLocalTransitStops(coordinate, 1000)) { double d = distanceLibrary.distance(v.getCoordinate(), coordinate); if (d < closest_stop_distance) { closest_stop_distance = d; closest_stop = v; } } } _log.debug(" best stop: {} distance: {}", closest_stop, closest_stop_distance); StreetLocation closestStreet = null; CandidateEdgeBundle bundle = getClosestEdges(coordinate, options, extraEdges, null, false); CandidateEdge candidate = bundle.best; double closestStreetDistance = Double.POSITIVE_INFINITY; if (candidate != null) { StreetEdge bestStreet = candidate.edge; Coordinate nearestPoint = candidate.nearestPointOnEdge; closestStreetDistance = candidate.getDistance(); _log.debug("best street: {} dist: {}", bestStreet.toString(), closestStreetDistance); if (name == null) { name = bestStreet.getName(); } String closestName = String .format("%s_%s", bestStreet.getName(), coordinate.toString()); closestStreet = StreetLocation.createStreetLocation( graph, closestName, name, bundle.toEdgeList(), nearestPoint, coordinate); } if (closestStreet == null) { _log.debug("returning only transit stop (no street found)"); return closest_stop; } else { if (closest_stop != null) { double relativeStopDistance = closest_stop_distance / closestStreetDistance; if (relativeStopDistance < 1.5) { _log.debug("linking transit stop to street (distances are comparable)"); closestStreet.addExtraEdgeTo(closest_stop); } } _log.debug("returning split street"); return closestStreet; } }
public Vertex getClosestVertex(final Coordinate coordinate, String name, RoutingRequest options, List<Edge> extraEdges) { _log.debug("Looking for/making a vertex near {}", coordinate); StreetVertex intersection = getIntersectionAt(coordinate, MAX_CORNER_DISTANCE); if (intersection != null) { if (name == null) { Set<String> uniqueNameSet = new HashSet<String>(); for (Edge e : intersection.getOutgoing()) { if (e instanceof StreetEdge) { uniqueNameSet.add(e.getName()); } } List<String> uniqueNames = new ArrayList<String>(uniqueNameSet); Locale locale; if (options == null) { locale = new Locale("en"); } else { locale = options.getLocale(); } ResourceBundle resources = ResourceBundle.getBundle("internals", locale); String fmt = resources.getString("corner"); if (uniqueNames.size() > 1) { name = String.format(fmt, uniqueNames.get(0), uniqueNames.get(1)); } else if (uniqueNames.size() == 1) { name = uniqueNames.get(0); } else { name = resources.getString("unnamedStreet"); } } StreetLocation closest = new StreetLocation(graph, "corner " + Math.random(), coordinate, name); FreeEdge e = new FreeEdge(closest, intersection); closest.getExtra().add(e); e = new FreeEdge(intersection, closest); closest.getExtra().add(e); return closest; } double closestStopDistance = Double.POSITIVE_INFINITY; Vertex closestStop = null; if (options != null && options.getModes().isTransit()) { for (Vertex v : getLocalTransitStops(coordinate, 1000)) { double d = distanceLibrary.distance(v.getCoordinate(), coordinate); if (d < closestStopDistance) { closestStopDistance = d; closestStop = v; } } } _log.debug(" best stop: {} distance: {}", closestStop, closestStopDistance); StreetLocation closestStreet = null; CandidateEdgeBundle bundle = getClosestEdges(coordinate, options, extraEdges, null, false); CandidateEdge candidate = bundle.best; double closestStreetDistance = Double.POSITIVE_INFINITY; if (candidate != null) { StreetEdge bestStreet = candidate.edge; Coordinate nearestPoint = candidate.nearestPointOnEdge; closestStreetDistance = distanceLibrary.distance(coordinate, nearestPoint); _log.debug("best street: {} dist: {}", bestStreet.toString(), closestStreetDistance); if (name == null) { name = bestStreet.getName(); } String closestName = String .format("%s_%s", bestStreet.getName(), coordinate.toString()); closestStreet = StreetLocation.createStreetLocation( graph, closestName, name, bundle.toEdgeList(), nearestPoint, coordinate); } if (closestStreet == null) { _log.debug("returning only transit stop (no street found)"); return closestStop; } else { if (closestStop != null) { double relativeStopDistance = closestStopDistance / closestStreetDistance; if (relativeStopDistance < 1.5) { _log.debug("linking transit stop to street (distances are comparable)"); closestStreet.addExtraEdgeTo(closestStop); } } _log.debug("returning split street"); return closestStreet; } }
private void processResultGenes(QueryResponse response, AtlasStructuredQueryResult result, QueryState qstate, AtlasStructuredQuery query) throws SolrServerException { SolrDocumentList docs = response.getResults(); result.setTotal(docs.getNumFound()); EfvTree<Integer> resultEfvs = new EfvTree<Integer>(); EfoTree<Integer> resultEfos = qstate.getEfos(); Iterable<EfvTree.EfEfv<Integer>> efvList = qstate.getEfvs().getValueSortedList(); Iterable<EfoTree.EfoItem<Integer>> efoList = qstate.getEfos().getValueOrderedList(); boolean hasQueryEfvs = qstate.hasQueryEfoEfvs(); EfoEfvPayloadCreator<Integer> numberer = new EfoEfvPayloadCreator<Integer>() { private int num = 0; public Integer make() { return num++; } }; Iterable<String> autoFactors = query.isFullHeatmap() ? efvService.getAllFactors() : efvService.getAnyConditionFactors(); for(SolrDocument doc : docs) { Integer id = (Integer)doc.getFieldValue("id"); if(id == null) continue; AtlasGene gene = new AtlasGene(atlasProperties, doc); if(response.getHighlighting() != null) gene.setGeneHighlights(response.getHighlighting().get(id.toString())); List<UpdownCounter> counters = new ArrayList<UpdownCounter>() { @Override public UpdownCounter get(int index) { if(index < size()) return super.get(index); else return new UpdownCounter(0, 0, 0, 0); } }; if(!hasQueryEfvs && query.getViewType() != ViewType.LIST) { Collection<Object> values; for(String ef : autoFactors) { values = doc.getFieldValues("efvs_up_" + EscapeUtil.encode(ef)); if(values != null) for(Object efv : values) { resultEfvs.getOrCreate(ef, (String)efv, numberer); } values = doc.getFieldValues("efvs_dn_" + EscapeUtil.encode(ef)); if(values != null) for(Object efv : values) { resultEfvs.getOrCreate(ef, (String)efv, numberer); } } int threshold = 0; if(!query.isFullHeatmap()) { if(resultEfos.getNumExplicitEfos() > 0) threshold = 1; else if(resultEfos.getNumExplicitEfos() > 20) threshold = 3; } values = doc.getFieldValues("efos_up"); if(values != null) for(Object efoo : values) { String efo = (String)efoo; if(EscapeUtil.nullzero((Short)doc.getFieldValue("cnt_efo_" + EscapeUtil.encode(efo) + "_s_up")) > threshold) resultEfos.add(efo, numberer, false); } values = doc.getFieldValues("efos_dn"); if(values != null) for(Object efoo : values) { String efo = (String)efoo; if(EscapeUtil.nullzero((Short)doc.getFieldValue("cnt_efo_" + EscapeUtil.encode(efo) + "_s_dn")) > threshold) resultEfos.add(efo, numberer, false); } efvList = resultEfvs.getValueSortedList(); efoList = resultEfos.getValueOrderedList(); } Iterator<EfvTree.EfEfv<Integer>> itEfv = efvList.iterator(); Iterator<EfoTree.EfoItem<Integer>> itEfo = efoList.iterator(); EfvTree.EfEfv<Integer> efv = null; EfoTree.EfoItem<Integer> efo = null; while(itEfv.hasNext() || itEfo.hasNext()) { if(itEfv.hasNext() && efv == null) efv = itEfv.next(); if(itEfo.hasNext() && efo == null) efo = itEfo.next(); String cellId; boolean usingEfv = efo == null || (efv != null && efv.getPayload().compareTo(efo.getPayload()) < 0); if(usingEfv) { cellId = efv.getEfEfvId(); } else { cellId = EscapeUtil.encode("efo", efo.getId()); } UpdownCounter counter = new UpdownCounter( EscapeUtil.nullzero((Short)doc.getFieldValue("cnt_" + cellId + "_up")), EscapeUtil.nullzero((Short)doc.getFieldValue("cnt_" + cellId + "_dn")), EscapeUtil.nullzero((Float)doc.getFieldValue("minpval_" + cellId + "_up")), EscapeUtil.nullzero((Float)doc.getFieldValue("minpval_" + cellId + "_dn"))); counters.add(counter); boolean nonZero = (counter.getUps() + counter.getDowns() > 0); if (usingEfv) { if (hasQueryEfvs && nonZero) resultEfvs.put(efv); efv = null; } else { if (nonZero) resultEfos.mark(efo.getId()); efo = null; } } if(query.getViewType() == ViewType.LIST) { loadListExperiments(result, gene, resultEfvs, resultEfos, qstate.getExperiments()); } result.addResult(new StructuredResultRow(gene, counters)); } result.setResultEfvs(resultEfvs); result.setResultEfos(resultEfos); log.info("Retrieved query completely: " + result.getSize() + " records of " + result.getTotal() + " total starting from " + result.getStart() ); log.debug("Resulting EFVs are: " + resultEfvs); log.debug("Resulting EFOs are: " + resultEfos); }
private void processResultGenes(QueryResponse response, AtlasStructuredQueryResult result, QueryState qstate, AtlasStructuredQuery query) throws SolrServerException { SolrDocumentList docs = response.getResults(); result.setTotal(docs.getNumFound()); EfvTree<Integer> resultEfvs = new EfvTree<Integer>(); EfoTree<Integer> resultEfos = qstate.getEfos(); Iterable<EfvTree.EfEfv<Integer>> efvList = qstate.getEfvs().getValueSortedList(); Iterable<EfoTree.EfoItem<Integer>> efoList = qstate.getEfos().getValueOrderedList(); boolean hasQueryEfvs = qstate.hasQueryEfoEfvs(); EfoEfvPayloadCreator<Integer> numberer = new EfoEfvPayloadCreator<Integer>() { private int num = 0; public Integer make() { return num++; } }; Iterable<String> autoFactors = query.isFullHeatmap() ? efvService.getAllFactors() : efvService.getAnyConditionFactors(); for(SolrDocument doc : docs) { Integer id = (Integer)doc.getFieldValue("id"); if(id == null) continue; AtlasGene gene = new AtlasGene(atlasProperties, doc); if(response.getHighlighting() != null) gene.setGeneHighlights(response.getHighlighting().get(id.toString())); List<UpdownCounter> counters = new ArrayList<UpdownCounter>() { @Override public UpdownCounter get(int index) { if(index < size()) return super.get(index); else return new UpdownCounter(0, 0, 0, 0); } }; if(!hasQueryEfvs && query.getViewType() != ViewType.LIST) { Collection<Object> values; for(String ef : autoFactors) { values = doc.getFieldValues("efvs_up_" + EscapeUtil.encode(ef)); if(values != null) for(Object efv : values) { resultEfvs.getOrCreate(ef, (String)efv, numberer); } values = doc.getFieldValues("efvs_dn_" + EscapeUtil.encode(ef)); if(values != null) for(Object efv : values) { resultEfvs.getOrCreate(ef, (String)efv, numberer); } } int threshold = 0; if(!query.isFullHeatmap()) { if(resultEfos.getNumExplicitEfos() > 0) threshold = 1; else if(resultEfos.getNumExplicitEfos() > 20) threshold = 3; } values = doc.getFieldValues("efos_up"); if(values != null) for(Object efoo : values) { String efo = (String)efoo; if(EscapeUtil.nullzero((Short)doc.getFieldValue("cnt_efo_" + EscapeUtil.encode(efo) + "_s_up")) > threshold) resultEfos.add(efo, numberer, false); } values = doc.getFieldValues("efos_dn"); if(values != null) for(Object efoo : values) { String efo = (String)efoo; if(EscapeUtil.nullzero((Short)doc.getFieldValue("cnt_efo_" + EscapeUtil.encode(efo) + "_s_dn")) > threshold) resultEfos.add(efo, numberer, false); } efvList = resultEfvs.getValueSortedList(); efoList = resultEfos.getValueOrderedList(); } Iterator<EfvTree.EfEfv<Integer>> itEfv = efvList.iterator(); Iterator<EfoTree.EfoItem<Integer>> itEfo = efoList.iterator(); EfvTree.EfEfv<Integer> efv = null; EfoTree.EfoItem<Integer> efo = null; while(itEfv.hasNext() || itEfo.hasNext() || efv != null || efo != null) { if(itEfv.hasNext() && efv == null) efv = itEfv.next(); if(itEfo.hasNext() && efo == null) efo = itEfo.next(); String cellId; boolean usingEfv = efo == null || (efv != null && efv.getPayload().compareTo(efo.getPayload()) < 0); if(usingEfv) { cellId = efv.getEfEfvId(); } else { cellId = EscapeUtil.encode("efo", efo.getId()); } UpdownCounter counter = new UpdownCounter( EscapeUtil.nullzero((Short)doc.getFieldValue("cnt_" + cellId + "_up")), EscapeUtil.nullzero((Short)doc.getFieldValue("cnt_" + cellId + "_dn")), EscapeUtil.nullzero((Float)doc.getFieldValue("minpval_" + cellId + "_up")), EscapeUtil.nullzero((Float)doc.getFieldValue("minpval_" + cellId + "_dn"))); counters.add(counter); boolean nonZero = (counter.getUps() + counter.getDowns() > 0); if (usingEfv) { if (hasQueryEfvs && nonZero) resultEfvs.put(efv); efv = null; } else { if (nonZero) resultEfos.mark(efo.getId()); efo = null; } } if(query.getViewType() == ViewType.LIST) { loadListExperiments(result, gene, resultEfvs, resultEfos, qstate.getExperiments()); } result.addResult(new StructuredResultRow(gene, counters)); } result.setResultEfvs(resultEfvs); result.setResultEfos(resultEfos); log.info("Retrieved query completely: " + result.getSize() + " records of " + result.getTotal() + " total starting from " + result.getStart() ); log.debug("Resulting EFVs are: " + resultEfvs); log.debug("Resulting EFOs are: " + resultEfos); }
public String toXML() { StringBuffer buffer = new StringBuffer(); String pattern = "yyyyMMdd HH:mm:ss z"; SimpleDateFormat formatter = new SimpleDateFormat( pattern ); buffer.append( "<changeset datePattern=\"" ) .append( pattern ) .append( "\"" ); if ( startDate != null ) { buffer.append( " start=\"" ) .append( formatter.format( startDate ) ) .append( "\"" ); } if ( endDate != null ) { buffer.append( " end=\"" ) .append( formatter.format( endDate ) ) .append( "\">" ); } buffer.append( "\n" ); for ( Iterator i = getChangeSets().iterator(); i.hasNext(); ) { buffer.append( ( (ChangeSet) i.next() ).toXML() ); } buffer.append( "</changeset>\n" ); return buffer.toString(); }
public String toXML() { StringBuffer buffer = new StringBuffer(); String pattern = "yyyyMMdd HH:mm:ss z"; SimpleDateFormat formatter = new SimpleDateFormat( pattern ); buffer.append( "<changeset datePattern=\"" ) .append( pattern ) .append( "\"" ); if ( startDate != null ) { buffer.append( " start=\"" ) .append( formatter.format( startDate ) ) .append( "\"" ); } if ( endDate != null ) { buffer.append( " end=\"" ) .append( formatter.format( endDate ) ) .append( "\"" ); } buffer.append( ">\n" ); for ( Iterator i = getChangeSets().iterator(); i.hasNext(); ) { buffer.append( ( (ChangeSet) i.next() ).toXML() ); } buffer.append( "</changeset>\n" ); return buffer.toString(); }
public void walk(CommonTree t, BufferedWriter out) { try { if (t != null) { switch (t.getType()) { case TanGParser.ADDSUB: if (t.getChildCount() > 1) { walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); } else { if (t.getText().equals("- ")) { out.write("("); out.write(t.getText()); walk((CommonTree) t.getChild(0), out); out.write(")"); } else { walk((CommonTree) t.getChild(0), out); } } break; case TanGParser.AND: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.ASSERT: out.write(t.getText() + " "); break; case TanGParser.ASSN: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); for (int i = 1; i < t.getChildCount(); i++) { walk((CommonTree) t.getChild(i), out); } break; case TanGParser.BITAND: walk((CommonTree) t.getChild(0), out); out.write("& "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.BITNOT: out.write("("); out.write(t.getText()); walk((CommonTree) t.getChild(0), out); out.write(")"); break; case TanGParser.BITOR: walk((CommonTree) t.getChild(0), out); out.write("| "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.BITSHIFT: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.BITXOR: walk((CommonTree) t.getChild(0), out); out.write("^ "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.BOOLAND: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.BOOLOR: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.BREAK: out.write(t.getText() + " "); break; case TanGParser.BYTE: out.write(t.getText() + " "); break; case TanGParser.COMMA: out.write(t.getText() + " "); break; case TanGParser.COMMENT: out.write(t.getText()); break; case TanGParser.COND: out.write("case "); out.newLine(); for (int j = 1; j < t.getChildCount(); j = j + 2) { if (j < t.getChildCount() - 3) { out.write("when "); walk((CommonTree) t.getChild(j), out); int k = 0; while (!(((t.getChild(j).getChild(k)).getType()) == (TanGParser.NEWLINE))) { k++; } while (k < t.getChild(j).getChildCount() - 1) { walk((CommonTree) (t.getChild(j).getChild(k)), out); k++; } } else if (j == t.getChildCount() - 3) { out.write("else "); walk((CommonTree) t.getChild(j), out); int k = 0; while (!(((t.getChild(j).getChild(k)).getType()) == (TanGParser.NEWLINE))) { k++; } while (k < t.getChild(j).getChildCount() - 1) { walk((CommonTree) (t.getChild(j).getChild(k)), out); k++; } } else { walk((CommonTree) t.getChild(j), out); } } break; case TanGParser.CONTINUE: out.write("next "); break; case TanGParser.DO: out.write(t.getText() + " "); break; case TanGParser.DOT: walk((CommonTree) t.getChild(0), out); out.write(t.getText()); walk((CommonTree) t.getChild(1), out); break; case TanGParser.ELSE: out.write(t.getText() + " "); break; case TanGParser.END: out.write(t.getText() + " "); out.newLine(); break; case TanGParser.EOF: out.write(t.getText()); break; case TanGParser.EQTEST: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.ESC_SEQ: out.write(t.getText() + " "); break; case TanGParser.EXP: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.EXPONENT: out.write("("); walk((CommonTree) t.getChild(0), out); out.write("* 10 ** "); walk((CommonTree) t.getChild(1), out); out.write(")"); break; case TanGParser.FATCOMMA: out.write(t.getText()); break; case TanGParser.FILENAME: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText().substring(0, t.getText().length() - 4) + "\" "); break; case TanGParser.FLOAT: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText() + " "); break; case TanGParser.FOR: out.write(t.getText()); break; case TanGParser.FORK: break; case TanGParser.FROM: break; case TanGParser.FUNCID: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else { out.write("td_" + t.getText() + " "); } break; case TanGParser.HEX: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText() + " "); break; case TanGParser.HEX_DIGIT: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText() + " "); break; case TanGParser.ID: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else { if ((t.getParent()).getType() == TanGParser.DOT && t.getChildIndex() != 0) { String param = ""; int w = (t.getParent().getParent()).getChildCount(); int i = 0; while (t.getParent().getParent().getChild(i) != t .getParent() && i < w) { i++; } i++; while (t.getParent().getParent().getChild(i) != null && t.getParent().getParent().getChild(i) .getType() != TanGParser.NEWLINE && i < w) { if ((t.getParent().getParent().getChild(i)) .getType() == TanGParser.ID || (t.getParent().getParent() .getChild(i).getType()) == TanGParser.FUNCID) { param = param + "td_" + t.getParent().getParent() .getChild(i).getText() + ", "; } else { param = param + t.getParent().getParent() .getChild(i).getText() + ", "; } printedAlready.add((CommonTree) t.getParent() .getParent().getChild(i)); i++; } if (param.length() > 0) { out.write(t.getText() + "(" + param.substring(0, param.length() - 2) + ")"); } else { out.write(t.getText() + "(" + param + ")"); } } else { if (t.getType() == TanGParser.ID || t.getType() == TanGParser.FUNCID) { out.write("td_" + t.getText() + " "); } else { if (t.getParent().getType() == TanGParser.DOT && t.getChildIndex() == 0) { out.write(t.getText()); } else { out.write(t.getText() + " "); } } } } break; case TanGParser.IF: out.write(t.getText() + " "); break; case TanGParser.IMPORT: out.write("require "); walk((CommonTree) t.getChild(0), out); break; case TanGParser.IN: out.write(t.getText() + " "); break; case TanGParser.INT: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText() + " "); break; case TanGParser.IS: out.write("=="); break; case TanGParser.LBRACE: out.write(t.getText()); break; case TanGParser.LBRACK: out.write(t.getText()); break; case TanGParser.LOOP: out.write("while true "); break; case TanGParser.LPAREN: out.write(t.getText()); break; case TanGParser.MAGCOMP: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.MAIN: for (int i = 0; i < t.getChildCount(); i++) walk((CommonTree) t.getChild(i), out); break; case TanGParser.MOD: walk((CommonTree) t.getChild(0), out); out.write(t.getText()); walk((CommonTree) t.getChild(1), out); break; case TanGParser.MULT: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.NEWLINE: out.write("\n"); break; case TanGParser.NODE: LinkedList<CommonTree> list = new LinkedList<CommonTree>(); if (t.getText().equals("public node")) { out.write("class "); out.write(t.getChild(0).getText()); nodes.add(t.getChild(0).getText()); } else { out.write("class "); out.write(t.getChild(0).getText()); nodes.add(t.getChild(0).getText()); out.newLine(); } out.newLine(); out.write("def main"); for (int i = 1; i < t.getChildCount(); i++) { if (t.getChild(i).getType() == TanGParser.MAIN) { for (int k = 0; k < t.getChild(i).getChildCount(); k++) { if (t.getChild(i).getChild(k).getType() == TanGParser.NODE) { list.addLast(((CommonTree) t.getChild(i) .getChild(k))); } else { walk((CommonTree) t.getChild(i).getChild(k), out); } } } else { walk((CommonTree) t.getChild(i), out); } } while (list.isEmpty() == false) { walk((CommonTree) list.getFirst(), out); list.remove(); } out.newLine(); out.write("end\n"); out.newLine(); break; case TanGParser.NODEID: doCheck(t, out); break; case TanGParser.NOT: out.write(t.getText()); walk((CommonTree) t.getChild(0), out); break; case TanGParser.NONE: out.write(t.getText() + " "); break; case TanGParser.NULL: out.write("nil "); break; case TanGParser.OR: walk((CommonTree) t.getChild(0), out); out.write(t.getText()); walk((CommonTree) t.getChild(1), out); break; case TanGParser.PIPE: String params = ""; String first = ""; LinkedList<CommonTree> list2 = new LinkedList<CommonTree>(); for (int i = 0; i < t.getChildCount(); i++) { if ((t.getChild(i).getType() == TanGParser.NODEID && i != t .getChildCount() - 1)) { list2.push((CommonTree) t.getChild(i)); } else if (t.getChild(i).getType() == TanGParser.PIPE) { list2.push((CommonTree) t.getChild(i)); } else if (t.getChild(i).getType() == TanGParser.ID) { first = list2.peek().getText(); params = params + "td_" + t.getChild(i) + ","; } else { walk((CommonTree) t.getChild(i), out); while (list2.isEmpty() == false) { out.write("("); if ((list2.peek().getText()).equals(first)) { walk((CommonTree) list2.pop(), out); out.write("("); out.write(params.substring(0, params.length() - 1)); out.write(")"); } else { walk((CommonTree) list2.pop(), out); } out.write(")"); } } } break; case TanGParser.PIPEROOT: for (int i = 0; i < t.getChildCount(); i++) walk((CommonTree) t.getChild(i), out); break; case TanGParser.PUBPRIV: break; case TanGParser.RANGE: out.write(t.getText() + " "); break; case TanGParser.RBRACE: out.write(t.getText()); break; case TanGParser.RBRACK: out.write(t.getText()); break; case TanGParser.REQUIRE: out.write(t.getText() + " " + t.getChild(0)); break; case TanGParser.RETURN: out.write(t.getText() + " "); break; case TanGParser.RPAREN: out.write(t.getText()); break; case TanGParser.ROOTNODE: for (int i = 0; i < t.getChildCount(); i++) walk((CommonTree) t.getChild(i), out); break; case TanGParser.SOME: out.write(t.getText() + " "); break; case TanGParser.STAR: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.STRING: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText() + " "); break; case TanGParser.TF: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText() + " "); break; case TanGParser.UNLESS: out.write(t.getText() + " "); break; case TanGParser.UNTIL: out.write(t.getText() + " "); break; case TanGParser.WHILE: out.write(t.getText() + " "); break; case TanGParser.WS: for (int i = 0; i < t.getChildCount(); i++) walk((CommonTree) t.getChild(i), out); break; case TanGParser.XOR: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case 0: for (int i = 0; i < t.getChildCount(); i++) walk((CommonTree) t.getChild(i), out); break; } } } catch (IOException e) { } }
public void walk(CommonTree t, BufferedWriter out) { try { if (t != null) { switch (t.getType()) { case TanGParser.ADDSUB: if (t.getChildCount() > 1) { walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); } else { if (t.getText().equals("- ")) { out.write("("); out.write(t.getText()); walk((CommonTree) t.getChild(0), out); out.write(")"); } else { walk((CommonTree) t.getChild(0), out); } } break; case TanGParser.AND: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.ASSERT: out.write(t.getText() + " "); break; case TanGParser.ASSN: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); for (int i = 1; i < t.getChildCount(); i++) { walk((CommonTree) t.getChild(i), out); } break; case TanGParser.BITAND: walk((CommonTree) t.getChild(0), out); out.write("& "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.BITNOT: out.write("("); out.write(t.getText()); walk((CommonTree) t.getChild(0), out); out.write(")"); break; case TanGParser.BITOR: walk((CommonTree) t.getChild(0), out); out.write("| "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.BITSHIFT: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.BITXOR: walk((CommonTree) t.getChild(0), out); out.write("^ "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.BOOLAND: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.BOOLOR: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.BREAK: out.write(t.getText() + " "); break; case TanGParser.BYTE: out.write(t.getText() + " "); break; case TanGParser.COMMA: out.write(t.getText() + " "); break; case TanGParser.COMMENT: out.write(t.getText()); break; case TanGParser.COND: out.write("case "); out.newLine(); for (int j = 1; j < t.getChildCount(); j = j + 2) { if (j < t.getChildCount() - 3) { out.write("when "); walk((CommonTree) t.getChild(j), out); int k = 0; while (!(((t.getChild(j).getChild(k)).getType()) == (TanGParser.NEWLINE))) { k++; } while (k < t.getChild(j).getChildCount() - 1) { walk((CommonTree) (t.getChild(j).getChild(k)), out); k++; } } else if (j == t.getChildCount() - 3) { out.write("else "); walk((CommonTree) t.getChild(j), out); int k = 0; while (!(((t.getChild(j).getChild(k)).getType()) == (TanGParser.NEWLINE))) { k++; } while (k < t.getChild(j).getChildCount() - 1) { walk((CommonTree) (t.getChild(j).getChild(k)), out); k++; } } else { walk((CommonTree) t.getChild(j), out); } } break; case TanGParser.CONTINUE: out.write("next "); break; case TanGParser.DO: out.write(t.getText() + " "); break; case TanGParser.DOT: walk((CommonTree) t.getChild(0), out); out.write(t.getText()); walk((CommonTree) t.getChild(1), out); break; case TanGParser.ELSE: out.write(t.getText() + " "); break; case TanGParser.END: out.write(t.getText() + " "); out.newLine(); break; case TanGParser.EOF: break; case TanGParser.EQTEST: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.ESC_SEQ: out.write(t.getText() + " "); break; case TanGParser.EXP: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.EXPONENT: out.write("("); walk((CommonTree) t.getChild(0), out); out.write("* 10 ** "); walk((CommonTree) t.getChild(1), out); out.write(")"); break; case TanGParser.FATCOMMA: out.write(t.getText()); break; case TanGParser.FILENAME: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText().substring(0, t.getText().length() - 4) + "\" "); break; case TanGParser.FLOAT: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText() + " "); break; case TanGParser.FOR: out.write(t.getText()); break; case TanGParser.FORK: break; case TanGParser.FROM: break; case TanGParser.FUNCID: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else { out.write("td_" + t.getText() + " "); } break; case TanGParser.HEX: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText() + " "); break; case TanGParser.HEX_DIGIT: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText() + " "); break; case TanGParser.ID: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else { if ((t.getParent()).getType() == TanGParser.DOT && t.getChildIndex() != 0) { String param = ""; int w = (t.getParent().getParent()).getChildCount(); int i = 0; while (t.getParent().getParent().getChild(i) != t .getParent() && i < w) { i++; } i++; while (t.getParent().getParent().getChild(i) != null && t.getParent().getParent().getChild(i) .getType() != TanGParser.NEWLINE && i < w) { if ((t.getParent().getParent().getChild(i)) .getType() == TanGParser.ID || (t.getParent().getParent() .getChild(i).getType()) == TanGParser.FUNCID) { param = param + "td_" + t.getParent().getParent() .getChild(i).getText() + ", "; } else { param = param + t.getParent().getParent() .getChild(i).getText() + ", "; } printedAlready.add((CommonTree) t.getParent() .getParent().getChild(i)); i++; } if (param.length() > 0) { out.write(t.getText() + "(" + param.substring(0, param.length() - 2) + ")"); } else { out.write(t.getText() + "(" + param + ")"); } } else { if (t.getType() == TanGParser.ID || t.getType() == TanGParser.FUNCID) { out.write("td_" + t.getText() + " "); } else { if (t.getParent().getType() == TanGParser.DOT && t.getChildIndex() == 0) { out.write(t.getText()); } else { out.write(t.getText() + " "); } } } } break; case TanGParser.IF: out.write(t.getText() + " "); break; case TanGParser.IMPORT: out.write("require "); walk((CommonTree) t.getChild(0), out); int d=1; while(t.getChild(d)!= null){ walk((CommonTree) t.getChild(d), out); d++; } break; case TanGParser.IN: out.write(t.getText() + " "); break; case TanGParser.INT: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText() + " "); break; case TanGParser.IS: out.write("=="); break; case TanGParser.LBRACE: out.write(t.getText()); break; case TanGParser.LBRACK: out.write(t.getText()); break; case TanGParser.LOOP: out.write("while true "); break; case TanGParser.LPAREN: out.write(t.getText()); break; case TanGParser.MAGCOMP: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.MAIN: for (int i = 0; i < t.getChildCount(); i++) walk((CommonTree) t.getChild(i), out); break; case TanGParser.MOD: walk((CommonTree) t.getChild(0), out); out.write(t.getText()); walk((CommonTree) t.getChild(1), out); break; case TanGParser.MULT: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.NEWLINE: out.write("\n"); break; case TanGParser.NODE: LinkedList<CommonTree> list = new LinkedList<CommonTree>(); if (t.getText().equals("public node")) { out.write("class "); out.write(t.getChild(0).getText()); nodes.add(t.getChild(0).getText()); } else { out.write("class "); out.write(t.getChild(0).getText()); nodes.add(t.getChild(0).getText()); out.newLine(); } out.newLine(); out.write("def main"); for (int i = 1; i < t.getChildCount(); i++) { if (t.getChild(i).getType() == TanGParser.MAIN) { for (int k = 0; k < t.getChild(i).getChildCount(); k++) { if (t.getChild(i).getChild(k).getType() == TanGParser.NODE) { list.addLast(((CommonTree) t.getChild(i) .getChild(k))); } else { walk((CommonTree) t.getChild(i).getChild(k), out); } } } else { walk((CommonTree) t.getChild(i), out); } } while (list.isEmpty() == false) { walk((CommonTree) list.getFirst(), out); list.remove(); } out.newLine(); out.write("end\n"); out.newLine(); break; case TanGParser.NODEID: doCheck(t, out); break; case TanGParser.NOT: out.write(t.getText()); walk((CommonTree) t.getChild(0), out); break; case TanGParser.NONE: out.write(t.getText() + " "); break; case TanGParser.NULL: out.write("nil "); break; case TanGParser.OR: walk((CommonTree) t.getChild(0), out); out.write(t.getText()); walk((CommonTree) t.getChild(1), out); break; case TanGParser.PIPE: String params = ""; String first = ""; LinkedList<CommonTree> list2 = new LinkedList<CommonTree>(); for (int i = 0; i < t.getChildCount(); i++) { if ((t.getChild(i).getType() == TanGParser.NODEID && i != t .getChildCount() - 1)) { list2.push((CommonTree) t.getChild(i)); } else if (t.getChild(i).getType() == TanGParser.PIPE) { list2.push((CommonTree) t.getChild(i)); } else if (t.getChild(i).getType() == TanGParser.ID) { first = list2.peek().getText(); params = params + "td_" + t.getChild(i) + ","; } else { walk((CommonTree) t.getChild(i), out); while (list2.isEmpty() == false) { out.write("("); if ((list2.peek().getText()).equals(first)) { walk((CommonTree) list2.pop(), out); out.write("("); out.write(params.substring(0, params.length() - 1)); out.write(")"); } else { walk((CommonTree) list2.pop(), out); } out.write(")"); } } } break; case TanGParser.PIPEROOT: for (int i = 0; i < t.getChildCount(); i++) walk((CommonTree) t.getChild(i), out); break; case TanGParser.PUBPRIV: break; case TanGParser.RANGE: out.write(t.getText() + " "); break; case TanGParser.RBRACE: out.write(t.getText()); break; case TanGParser.RBRACK: out.write(t.getText()); break; case TanGParser.REQUIRE: out.write(t.getText() + " " + t.getChild(0)); break; case TanGParser.RETURN: out.write(t.getText() + " "); break; case TanGParser.RPAREN: out.write(t.getText()); break; case TanGParser.ROOTNODE: for (int i = 0; i < t.getChildCount(); i++) walk((CommonTree) t.getChild(i), out); break; case TanGParser.SOME: out.write(t.getText() + " "); break; case TanGParser.STAR: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case TanGParser.STRING: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText() + " "); break; case TanGParser.TF: if (printedAlready.contains((CommonTree) t)) { printedAlready.remove(t); } else out.write(t.getText() + " "); break; case TanGParser.UNLESS: out.write(t.getText() + " "); break; case TanGParser.UNTIL: out.write(t.getText() + " "); break; case TanGParser.WHILE: out.write(t.getText() + " "); break; case TanGParser.WS: for (int i = 0; i < t.getChildCount(); i++) walk((CommonTree) t.getChild(i), out); break; case TanGParser.XOR: walk((CommonTree) t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree) t.getChild(1), out); break; case 0: for (int i = 0; i < t.getChildCount(); i++) walk((CommonTree) t.getChild(i), out); break; } } } catch (IOException e) { } }
public static void main(String[] args) { RunResults results; try { ObjectInputStream stdinStream = new ObjectInputStream(System.in); RunSetup setup = (RunSetup)stdinStream.readObject(); Settings settings = setup.getSettings(); boolean useFileTransfer = settings.getBooleanProperty("UseFileTransfer"); FileTransferSystem fts = null; if(useFileTransfer) { String className = settings.getSetting("FileTransferSystemClassName"); Settings ftsSettings = settings.getSettingsForClass(className); fts = FileTransferSystemFactory.getFactory().getFileTransferSystem(className, ftsSettings); fts.connect(); StringMap inputFiles = setup.getInputFiles(); for(String key : inputFiles.keySet()) { String path = inputFiles.get(key); String fileTransferSubpath = appendPathComponent(setup.getFileTransferSubpath(), "input"); String remotePath = appendPathComponent(fileTransferSubpath, path); String localPath = path; fts.downloadFile(remotePath, localPath); } fts.disconnect(); } String adapterClassName = settings.getSetting("AdapterClass"); Settings adapterSettings = settings.getSettingsForClass(adapterClassName); Adapter adapter = AdapterFactory.createAdapter(adapterClassName, adapterSettings); ParameterMap parameters = setup.getParameters(); int runNumber = setup.getRunNumber(); int rngSeed = setup.getRngSeed(); results = adapter.run(parameters, runNumber, rngSeed); if(useFileTransfer) { fts.connect(); StringList outputFiles = setup.getOutputFiles(); for(String outputFile : outputFiles) { String fileTransferSubpath = setup.getFileTransferSubpath(); String remotePath = appendPathComponent(fileTransferSubpath, outputFile); fts.uploadFile(outputFile, remotePath); } fts.disconnect(); } if(!useFileTransfer) { String stdoutFilename = "stdout." + runNumber; byte[] stdoutData = results.getStdoutData(); writeData(stdoutFilename, stdoutData); String stderrFilename = "stderr." + runNumber; byte[] stderrData = results.getStderrData(); writeData(stderrFilename, stderrData); } } catch(Exception e) { e.printStackTrace(); results = new RunResults(e); } try { ObjectOutputStream stdoutStream = new ObjectOutputStream(System.out); stdoutStream.writeObject(results); } catch(Exception e) {} }
public static void main(String[] args) { RunResults results; try { RunSetup setup; try { ObjectInputStream stdinStream = new ObjectInputStream(System.in); setup = (RunSetup)stdinStream.readObject(); } catch(Exception e) { ObjectInputStream stdinFileStream = new ObjectInputStream(new FileInputStream(".gsweep_in.0")); setup = (RunSetup)stdinFileStream.readObject(); } Settings settings = setup.getSettings(); boolean useFileTransfer = settings.getBooleanProperty("UseFileTransfer"); FileTransferSystem fts = null; if(useFileTransfer) { String className = settings.getSetting("FileTransferSystemClassName"); Settings ftsSettings = settings.getSettingsForClass(className); fts = FileTransferSystemFactory.getFactory().getFileTransferSystem(className, ftsSettings); fts.connect(); StringMap inputFiles = setup.getInputFiles(); for(String key : inputFiles.keySet()) { String path = inputFiles.get(key); String fileTransferSubpath = appendPathComponent(setup.getFileTransferSubpath(), "input"); String remotePath = appendPathComponent(fileTransferSubpath, path); String localPath = path; fts.downloadFile(remotePath, localPath); } fts.disconnect(); } String adapterClassName = settings.getSetting("AdapterClass"); Settings adapterSettings = settings.getSettingsForClass(adapterClassName); Adapter adapter = AdapterFactory.createAdapter(adapterClassName, adapterSettings); ParameterMap parameters = setup.getParameters(); int runNumber = setup.getRunNumber(); int rngSeed = setup.getRngSeed(); results = adapter.run(parameters, runNumber, rngSeed); if(useFileTransfer) { fts.connect(); StringList outputFiles = setup.getOutputFiles(); for(String outputFile : outputFiles) { String fileTransferSubpath = setup.getFileTransferSubpath(); String remotePath = appendPathComponent(fileTransferSubpath, outputFile); fts.uploadFile(outputFile, remotePath); } fts.disconnect(); } if(!useFileTransfer) { String stdoutFilename = "stdout." + runNumber; byte[] stdoutData = results.getStdoutData(); writeData(stdoutFilename, stdoutData); String stderrFilename = "stderr." + runNumber; byte[] stderrData = results.getStderrData(); writeData(stderrFilename, stderrData); } } catch(Exception e) { e.printStackTrace(); results = new RunResults(e); } try { ObjectOutputStream stdoutStream = new ObjectOutputStream(System.out); stdoutStream.writeObject(results); } catch(Exception e) {} }
public void run(){ this.setName(getEmployeeName()); Random r = new Random(); try { startSignal.await(); Thread.sleep(10 * r.nextInt(30)); System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " arrives at office"); dayStartTime = office.getTime(); dayEndTime = dayStartTime + 800; lunchTime = r.nextInt(200) + 1200; lunchDuration = r.nextInt((int) (1700-dayEndTime-30)) + 30; dayEndTime += lunchDuration; office.addTimeEvent(lunchTime); office.addTimeEvent(dayEndTime); if(isLead){ office.waitForStandupMeeting(); System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " is at standup meeting"); Thread.sleep(150); } office.waitForTeamMeeting(teamNumber); office.haveTeamMeeting(teamNumber, this); System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " left team meeting"); } catch (InterruptedException e) { e.printStackTrace(); } while(true){ office.startWorking(); if(!runChecks()){ break; } if(isLead && isWaitingQuestion){ office.getManager().askQuestion(this); } int random = r.nextInt(20); if(random == 0){ if(isLead){ office.getManager().askQuestion(this); } else{ if(r.nextBoolean()){ office.getLead(teamNumber).askQuestion(this); } } } if(!runChecks()){ break; } } System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " leaves"); }
public void run(){ this.setName(getEmployeeName()); Random r = new Random(); try { startSignal.await(); Thread.sleep(10 * r.nextInt(30)); System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " arrives at office"); dayStartTime = office.getTime(); dayEndTime = dayStartTime + 800; lunchTime = r.nextInt(60) + 1200 + r.nextInt(2)*100; lunchDuration = r.nextInt((int)(1700-dayEndTime-70)) + 30; dayEndTime += lunchDuration; office.addTimeEvent(lunchTime); office.addTimeEvent(dayEndTime); if(isLead){ office.waitForStandupMeeting(); System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " is at standup meeting"); Thread.sleep(150); } office.waitForTeamMeeting(teamNumber); office.haveTeamMeeting(teamNumber, this); System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " left team meeting"); } catch (InterruptedException e) { e.printStackTrace(); } while(true){ office.startWorking(); if(!runChecks()){ break; } if(isLead && isWaitingQuestion){ office.getManager().askQuestion(this); } int random = r.nextInt(20); if(random == 0){ if(isLead){ office.getManager().askQuestion(this); } else{ if(r.nextBoolean()){ office.getLead(teamNumber).askQuestion(this); } } } if(!runChecks()){ break; } } System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " leaves"); }
public static Set<Integer> allMemberGroupIDs(Context c, EPerson e) throws SQLException { Set<Integer> groupIDs = new HashSet<Integer>(); if (e != null) { TableRowIterator tri = DatabaseManager.queryTable(c, "epersongroup2eperson", "SELECT * FROM epersongroup2eperson WHERE eperson_id= ?", e .getID()); try { while (tri.hasNext()) { TableRow row = tri.next(); int childID = row.getIntColumn("eperson_group_id"); groupIDs.add(new Integer(childID)); } } finally { if (tri != null) tri.close(); } } if (c.getCurrentUser().getID() == e.getID()) { Group[] specialGroups = c.getSpecialGroups(); for(Group special : specialGroups) { groupIDs.add(new Integer(special.getID())); } } groupIDs.add(new Integer(0)); String groupQuery = ""; Iterator i = groupIDs.iterator(); Object[] parameters = new Object[groupIDs.size()]; int idx = 0; while (i.hasNext()) { int groupID = ((Integer) i.next()).intValue(); parameters[idx++] = new Integer(groupID); groupQuery += "child_id= ? "; if (i.hasNext()) groupQuery += " OR "; } TableRowIterator tri = DatabaseManager.queryTable(c, "group2groupcache", "SELECT * FROM group2groupcache WHERE " + groupQuery, parameters); try { while (tri.hasNext()) { TableRow row = tri.next(); int parentID = row.getIntColumn("parent_id"); groupIDs.add(new Integer(parentID)); } } finally { if (tri != null) tri.close(); } return groupIDs; }
public static Set<Integer> allMemberGroupIDs(Context c, EPerson e) throws SQLException { Set<Integer> groupIDs = new HashSet<Integer>(); if (e != null) { TableRowIterator tri = DatabaseManager.queryTable(c, "epersongroup2eperson", "SELECT * FROM epersongroup2eperson WHERE eperson_id= ?", e .getID()); try { while (tri.hasNext()) { TableRow row = tri.next(); int childID = row.getIntColumn("eperson_group_id"); groupIDs.add(new Integer(childID)); } } finally { if (tri != null) tri.close(); } } if ((c.getCurrentUser() != null) && (c.getCurrentUser().getID() == e.getID())) { Group[] specialGroups = c.getSpecialGroups(); for(Group special : specialGroups) { groupIDs.add(new Integer(special.getID())); } } groupIDs.add(new Integer(0)); String groupQuery = ""; Iterator i = groupIDs.iterator(); Object[] parameters = new Object[groupIDs.size()]; int idx = 0; while (i.hasNext()) { int groupID = ((Integer) i.next()).intValue(); parameters[idx++] = new Integer(groupID); groupQuery += "child_id= ? "; if (i.hasNext()) groupQuery += " OR "; } TableRowIterator tri = DatabaseManager.queryTable(c, "group2groupcache", "SELECT * FROM group2groupcache WHERE " + groupQuery, parameters); try { while (tri.hasNext()) { TableRow row = tri.next(); int parentID = row.getIntColumn("parent_id"); groupIDs.add(new Integer(parentID)); } } finally { if (tri != null) tri.close(); } return groupIDs; }
protected ObjectRecord createObjectRecord (String path, DObject object) { return new PeerDatabaseObjectRecord(path, object) { @Override protected void serialize (String name, String key, Object value) { setValue(key, StringUtil.hexlate(ExportUtil.toBytes(value))); fieldUpdated(name, value); } @Override protected Object deserialize (String value) { return ExportUtil.fromBytes(StringUtil.unhexlate(value)); } }; }
protected ObjectRecord createObjectRecord (String path, DObject object) { return new PeerDatabaseObjectRecord(path, object) { @Override protected void serialize (String name, String key, Object value) { setValue(key, StringUtil.hexlate(ExportUtil.toBytes(value))); } @Override protected Object deserialize (String value) { return ExportUtil.fromBytes(StringUtil.unhexlate(value)); } }; }
public static void process(List<String> xmlInputs, InputStream xsltStream, File docsdir, Map<String,String> parameters ) throws Exception { if (xmlInputs == null || xmlInputs.size() == 0) throw new IllegalArgumentException("no XML input file(s)"); System.out.println(getString("transforming.to.html")); System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); System.setProperty("javax.xml.parsers.SAXParserFactory", "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl"); if (xsltStream == null) { if(SDK_THEME) { xsltStream = XHTMLProcessingUtils.class.getResourceAsStream("resources/sdk.xsl"); } else { xsltStream = XHTMLProcessingUtils.class.getResourceAsStream("resources/javadoc.xsl"); } } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { pe(WARNING, "warning: ", exception); } public void error(SAXParseException exception) throws SAXException { pe(SEVERE, "error: ", exception); } public void fatalError(SAXParseException exception) throws SAXException { pe(SEVERE, "fatal error", exception); } private void pe(Level level, String string, SAXParseException exception) { p(level, string + " line: " + exception.getLineNumber() + " column: " + exception.getColumnNumber() + " " + exception.getLocalizedMessage()); } }); if (!docsdir.exists()) { docsdir.mkdir(); } p(INFO, getString("copying")); copyResource(docsdir,"index.html"); copyResource(docsdir,"empty.html"); copyResource(docsdir,"general.css"); copyResource(docsdir,"sdk.css"); copyResource(docsdir,"core.js"); copyResource(docsdir,"more.js"); copyResource(docsdir,"sessvars.js"); File images = new File(docsdir,"images"); images.mkdir(); copy(XHTMLProcessingUtils.class.getResource("resources/quote-background-1.gif"), new File(images, "quote-background-1.gif")); copyResource(images,"JFX_arrow_down.png"); copyResource(images,"JFX_arrow_right.png"); copyResource(images,"JFX_arrow_up.png"); copyResource(images,"JFX_highlight_dot.png"); p(INFO, getString("transforming")); Source xslt = new StreamSource(xsltStream); TransformerFactory transFact = TransformerFactory.newInstance(); transFact.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { p(INFO, "Trying to resolve: " + href + " " + base); if("javadoc.xsl".equals(href)) { URL url = XHTMLProcessingUtils.class.getResource("resources/javadoc.xsl"); p(INFO, "Resolved " + href + ":" + base + " to " + url); try { return new StreamSource(url.openStream()); } catch (IOException ex) { Logger.getLogger(XHTMLProcessingUtils.class.getName()).log(Level.SEVERE, null, ex); return null; } } return null; } }); Transformer trans = transFact.newTransformer(xslt); if(SDK_THEME) { trans.setParameter("inline-classlist","true"); trans.setParameter("inline-descriptions", "true"); } for(String key : parameters.keySet()) { System.out.println("using key: " + key + " " + parameters.get(key)); trans.setParameter(key, parameters.get(key)); } trans.setErrorListener(new MainErrorListener()); Document packages_doc = builder.newDocument(); Element package_list_elem = packages_doc.createElement("packageList"); packages_doc.appendChild(package_list_elem); Document unified = builder.newDocument(); Element javadocElement = unified.createElement("javadoc"); unified.appendChild(javadocElement); mergeDocuments(xmlInputs, builder, unified, javadocElement); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList packages = (NodeList) xpath.evaluate("//package", unified, XPathConstants.NODESET); p(INFO, MessageFormat.format(getString("creating.packages"), packages.getLength())); for (int i = 0; i < packages.getLength(); i++) { Element pkg = ((Element) packages.item(i)); String name = pkg.getAttribute("name"); Element package_elem = packages_doc.createElement("package"); package_elem.setAttribute("name", name); package_list_elem.appendChild(package_elem); copyDocComment(pkg,package_elem); Element first_line = packages_doc.createElement("first-line-comment"); first_line.appendChild(packages_doc.createTextNode("first line comment")); package_elem.appendChild(first_line); processPackage(name, pkg, xpath, docsdir, trans, package_elem); } package_list_elem.setAttribute("mode", "overview-frame"); trans.setParameter("root-path", "./"); trans.transform(new DOMSource(packages_doc), new StreamResult(new File(docsdir,"overview-frame.html"))); trans.setParameter("root-path", "./"); package_list_elem.setAttribute("mode", "overview-summary"); trans.transform(new DOMSource(packages_doc), new StreamResult(new File(docsdir,"overview-summary.html"))); p(INFO,getString("finished")); }
public static void process(List<String> xmlInputs, InputStream xsltStream, File docsdir, Map<String,String> parameters ) throws Exception { if (xmlInputs == null || xmlInputs.size() == 0) throw new IllegalArgumentException("no XML input file(s)"); System.out.println(getString("transforming.to.html")); System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); System.setProperty("javax.xml.parsers.SAXParserFactory", "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl"); if (xsltStream == null) { if(SDK_THEME) { xsltStream = XHTMLProcessingUtils.class.getResourceAsStream("resources/sdk.xsl"); } else { xsltStream = XHTMLProcessingUtils.class.getResourceAsStream("resources/javadoc.xsl"); } } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { pe(WARNING, "warning: ", exception); } public void error(SAXParseException exception) throws SAXException { pe(SEVERE, "error: ", exception); } public void fatalError(SAXParseException exception) throws SAXException { pe(SEVERE, "fatal error", exception); } private void pe(Level level, String string, SAXParseException exception) { p(level, string + " line: " + exception.getLineNumber() + " column: " + exception.getColumnNumber() + " " + exception.getLocalizedMessage()); } }); if (!docsdir.exists()) { docsdir.mkdir(); } p(INFO, getString("copying")); copyResource(docsdir,"empty.html"); copyResource(docsdir,"general.css"); copyResource(docsdir,"sdk.css"); copyResource(docsdir,"core.js"); copyResource(docsdir,"more.js"); copyResource(docsdir,"sessvars.js"); File images = new File(docsdir,"images"); images.mkdir(); copy(XHTMLProcessingUtils.class.getResource("resources/quote-background-1.gif"), new File(images, "quote-background-1.gif")); copyResource(images,"JFX_arrow_down.png"); copyResource(images,"JFX_arrow_right.png"); copyResource(images,"JFX_arrow_up.png"); copyResource(images,"JFX_highlight_dot.png"); p(INFO, getString("transforming")); Source xslt = new StreamSource(xsltStream); TransformerFactory transFact = TransformerFactory.newInstance(); transFact.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { p(INFO, "Trying to resolve: " + href + " " + base); if("javadoc.xsl".equals(href)) { URL url = XHTMLProcessingUtils.class.getResource("resources/javadoc.xsl"); p(INFO, "Resolved " + href + ":" + base + " to " + url); try { return new StreamSource(url.openStream()); } catch (IOException ex) { Logger.getLogger(XHTMLProcessingUtils.class.getName()).log(Level.SEVERE, null, ex); return null; } } return null; } }); Transformer trans = transFact.newTransformer(xslt); if(SDK_THEME) { trans.setParameter("inline-classlist","true"); trans.setParameter("inline-descriptions", "true"); } for(String key : parameters.keySet()) { System.out.println("using key: " + key + " " + parameters.get(key)); trans.setParameter(key, parameters.get(key)); } trans.setErrorListener(new MainErrorListener()); Document packages_doc = builder.newDocument(); Element package_list_elem = packages_doc.createElement("packageList"); packages_doc.appendChild(package_list_elem); Document unified = builder.newDocument(); Element javadocElement = unified.createElement("javadoc"); unified.appendChild(javadocElement); mergeDocuments(xmlInputs, builder, unified, javadocElement); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList packages = (NodeList) xpath.evaluate("//package", unified, XPathConstants.NODESET); p(INFO, MessageFormat.format(getString("creating.packages"), packages.getLength())); for (int i = 0; i < packages.getLength(); i++) { Element pkg = ((Element) packages.item(i)); String name = pkg.getAttribute("name"); Element package_elem = packages_doc.createElement("package"); package_elem.setAttribute("name", name); package_list_elem.appendChild(package_elem); copyDocComment(pkg,package_elem); Element first_line = packages_doc.createElement("first-line-comment"); first_line.appendChild(packages_doc.createTextNode("first line comment")); package_elem.appendChild(first_line); processPackage(name, pkg, xpath, docsdir, trans, package_elem); } trans.setParameter("root-path", "./"); package_list_elem.setAttribute("mode", "overview-summary"); trans.transform(new DOMSource(packages_doc), new StreamResult(new File(docsdir,"index.html"))); p(INFO,getString("finished")); }
public static void selfTest() { LotteryScheduler ls = new LotteryScheduler(); LotteryQueue[] pq = new LotteryQueue[5]; KThread[] t = new KThread[5]; ThreadState lts[] = new LotteryThreadState[5]; for (int i=0; i < 5; i++) pq[i] = ls.new LotteryQueue(true); for (int i=0; i < 5; i++) { t[i] = new KThread(); t[i].setName("thread" + i); lts[i] = ls.getThreadState(t[i]); } Machine.interrupt().disable(); System.out.println("===========LotteryScheduler Test============"); System.out.println("priority defaults to " + lts[0].priority); pq[0].acquire(t[0]); System.out.println("pq[0].acquire(t[0])"); System.out.println("lock holder effective priority is " + pq[0].holder.effectivePriority); lts[0].setPriority(5); System.out.println("lts[0].setPriority(5)"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); pq[0].waitForAccess(t[1]); System.out.println("pq[0].waitForAccess(t[1])"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); KThread temp = pq[0].pickNextThread().thread; System.out.println("pq[0].pickNextThread()"); System.out.println("Next Thread Null is: " + (temp == null)); lts[1].setPriority(3); System.out.println("lts[1].setPriority(3)"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); temp = pq[0].nextThread(); System.out.println("pq[0].nextThread()"); System.out.println("Next Thread Null is: " + (temp == null)); temp = pq[0].pickNextThread().thread; System.out.println("pq[0].pickNextThread()"); System.out.println("Next Thread Null is: " + (temp == null)); Machine.interrupt().enable(); }
public static void selfTest() { LotteryScheduler ls = new LotteryScheduler(); LotteryQueue[] pq = new LotteryQueue[5]; KThread[] t = new KThread[5]; ThreadState lts[] = new LotteryThreadState[5]; for (int i=0; i < 5; i++) pq[i] = ls.new LotteryQueue(true); for (int i=0; i < 5; i++) { t[i] = new KThread(); t[i].setName("thread" + i); lts[i] = ls.getThreadState(t[i]); } Machine.interrupt().disable(); System.out.println("===========LotteryScheduler Test============"); System.out.println("priority defaults to " + lts[0].priority); pq[0].acquire(t[0]); System.out.println("pq[0].acquire(t[0])"); System.out.println("lock holder effective priority is " + pq[0].holder.effectivePriority); lts[0].setPriority(5); System.out.println("lts[0].setPriority(5)"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); pq[0].waitForAccess(t[1]); System.out.println("pq[0].waitForAccess(t[1])"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); KThread temp = pq[0].pickNextThread().thread; System.out.println("pq[0].pickNextThread()"); System.out.println("nextThread == null is: " + (temp == null)); lts[1].setPriority(3); System.out.println("lts[1].setPriority(3)"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); temp = pq[0].nextThread(); System.out.println("pq[0].nextThread()"); System.out.println("nextThread == null is: " + (temp == null)); temp = pq[0].pickNextThread(); System.out.println("pq[0].pickNextThread()"); System.out.println("pickNextThread == null is: " + (temp == null)); Machine.interrupt().enable(); }
protected Iterable<Node> getAllNodes() { final Iterator<Node> iterator = GlobalGraphOperations.at(graphDB).getAllNodes().iterator(); return new Iterable<Node>() { @Override public Iterator<Node> iterator() { return new Iterator<Node>() { public Node next; @Override public boolean hasNext() { ensureNextIsFetched(); return next != null; } private void ensureNextIsFetched() { if (next == null && iterator.hasNext()) { next = iterator.next(); } if (next.getId() == 0) { next = null; ensureNextIsFetched(); } } @Override public Node next() { ensureNextIsFetched(); return next; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; }
protected Iterable<Node> getAllNodes() { final Iterator<Node> iterator = GlobalGraphOperations.at(graphDB).getAllNodes().iterator(); return new Iterable<Node>() { @Override public Iterator<Node> iterator() { return new Iterator<Node>() { public Node next; @Override public boolean hasNext() { ensureNextIsFetched(); return next != null; } private void ensureNextIsFetched() { if (next == null && iterator.hasNext()) { next = iterator.next(); } if (next != null && next.getId() == 0) { next = null; ensureNextIsFetched(); } } @Override public Node next() { ensureNextIsFetched(); Node nodeToReturn = next; next = null; return nodeToReturn; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; }
public void setUp() throws MojoExecutionException, MojoFailureException { builder = new Library(); if (directory != null) { builder.setDirectory(directory); } super.setUp(); builder.setOutput(outputFile); if (checkNullOrEmpty(includeClasses) && checkNullOrEmpty(includeFiles) && checkNullOrEmpty(includeNamespaces) && checkNullOrEmpty(includeResourceBundles) && checkNullOrEmpty(includeResourceBundlesArtifact) && checkNullOrEmpty(includeSources) && checkNullOrEmpty(includeStylesheet)) { throw new MojoExecutionException("Nothing to be included."); } if (!checkNullOrEmpty(includeClasses)) { for (String asClass : includeClasses) { builder.addComponent(asClass); } } if (!checkNullOrEmpty(includeFiles)) { for (File file : includeFiles) { if (file == null) { throw new MojoFailureException("Cannot include a null file"); } if (!file.exists()) { throw new MojoFailureException("File " + file.getName() + " not found"); } builder.addArchiveFile(file.getName(), file); } } if (!checkNullOrEmpty(includeNamespaces)) { for (String uri : includeNamespaces) { try { builder.addComponent(new URI(uri)); } catch (URISyntaxException e) { throw new MojoExecutionException("Invalid URI " + uri, e); } } } if (!checkNullOrEmpty(includeResourceBundles)) { for (String rb : includeResourceBundles) { builder.addResourceBundle(rb); } } if (!checkNullOrEmpty(includeResourceBundlesArtifact)) { for (MavenArtifact mvnArtifact : includeResourceBundlesArtifact) { Artifact artifact = artifactFactory .createArtifactWithClassifier(mvnArtifact.getGroupId(), mvnArtifact.getArtifactId(), mvnArtifact .getVersion(), "properties", "resource-bundle"); resolveArtifact(artifact, resolver, localRepository, remoteRepositories); String bundleFile; try { bundleFile = FileUtils.readFileToString(artifact.getFile()); } catch (IOException e) { throw new MojoExecutionException( "Ocorreu um erro ao ler o artefato " + artifact, e); } String[] bundles = bundleFile.split(" "); for (String bundle : bundles) { builder.addResourceBundle(bundle); } } } if (!checkNullOrEmpty(includeSources)) { for (File file : includeSources) { if (file == null) { throw new MojoFailureException("Cannot include a null file"); } if (!file.exists()) { throw new MojoFailureException("File " + file.getName() + " not found"); } builder.addComponent(file); } } if (checkNullOrEmpty(includeStylesheet)) { for (Stylesheet sheet : includeStylesheet) { if (!sheet.getPath().exists()) { throw new MojoExecutionException("Stylesheet not found: " + sheet.getPath()); } builder.addStyleSheet(sheet.getName(), sheet.getPath()); } } configuration.enableDigestComputation(computeDigest); }
public void setUp() throws MojoExecutionException, MojoFailureException { builder = new Library(); if (directory != null) { builder.setDirectory(directory); } super.setUp(); builder.setOutput(outputFile); if (checkNullOrEmpty(includeClasses) && checkNullOrEmpty(includeFiles) && checkNullOrEmpty(includeNamespaces) && checkNullOrEmpty(includeResourceBundles) && checkNullOrEmpty(includeResourceBundlesArtifact) && checkNullOrEmpty(includeSources) && checkNullOrEmpty(includeStylesheet)) { getLog().warn( "Nothing expecified to include. Assuming source folders."); includeSources = sourcePaths.clone(); } if (!checkNullOrEmpty(includeClasses)) { for (String asClass : includeClasses) { builder.addComponent(asClass); } } if (!checkNullOrEmpty(includeFiles)) { for (File file : includeFiles) { if (file == null) { throw new MojoFailureException("Cannot include a null file"); } if (!file.exists()) { throw new MojoFailureException("File " + file.getName() + " not found"); } builder.addArchiveFile(file.getName(), file); } } if (!checkNullOrEmpty(includeNamespaces)) { for (String uri : includeNamespaces) { try { builder.addComponent(new URI(uri)); } catch (URISyntaxException e) { throw new MojoExecutionException("Invalid URI " + uri, e); } } } if (!checkNullOrEmpty(includeResourceBundles)) { for (String rb : includeResourceBundles) { builder.addResourceBundle(rb); } } if (!checkNullOrEmpty(includeResourceBundlesArtifact)) { for (MavenArtifact mvnArtifact : includeResourceBundlesArtifact) { Artifact artifact = artifactFactory .createArtifactWithClassifier(mvnArtifact.getGroupId(), mvnArtifact.getArtifactId(), mvnArtifact .getVersion(), "properties", "resource-bundle"); resolveArtifact(artifact, resolver, localRepository, remoteRepositories); String bundleFile; try { bundleFile = FileUtils.readFileToString(artifact.getFile()); } catch (IOException e) { throw new MojoExecutionException( "Ocorreu um erro ao ler o artefato " + artifact, e); } String[] bundles = bundleFile.split(" "); for (String bundle : bundles) { builder.addResourceBundle(bundle); } } } if (!checkNullOrEmpty(includeSources)) { for (File file : includeSources) { if (file == null) { throw new MojoFailureException("Cannot include a null file"); } if (!file.exists()) { throw new MojoFailureException("File " + file.getName() + " not found"); } builder.addComponent(file); } } if (!checkNullOrEmpty(includeStylesheet)) { for (Stylesheet sheet : includeStylesheet) { if (!sheet.getPath().exists()) { throw new MojoExecutionException("Stylesheet not found: " + sheet.getPath()); } builder.addStyleSheet(sheet.getName(), sheet.getPath()); } } configuration.enableDigestComputation(computeDigest); }
public void testFindInRequestHistory() throws ProxyException { driver.get(GOOGLE); WebElement element = driver.findElement(By.name("q")); element.sendKeys("continuumsecurity"); element.submit(); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } List<HarEntry> hist = zaproxy.findInRequestHistory("continuumsecurity"); System.out.println(hist.get(0).getRequest().toString()); System.out.println(hist.get(1).getRequest().toString()); assertTrue(hist.get(0).getRequest().getMethod().equals("GET")); assertTrue(hist.get(0).getRequest().getQueryString().toString().contains("q")); assertTrue(hist.get(0).getRequest().getQueryString().toString().contains("continuumsecurity")); assertEquals("HTTP/1.1", hist.get(0).getRequest().getHttpVersion()); assertEquals(200, hist.get(0).getResponse().getStatus()); String content = new String(Base64.decode(hist.get(0).getResponse().getContent().getText())); System.out.println(content); assertTrue(content.contains("continuumsecurity.net")); }
public void testFindInRequestHistory() throws ProxyException { driver.get(GOOGLE); WebElement element = driver.findElement(By.name("q")); element.sendKeys("continuumsecurity"); element.submit(); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } List<HarEntry> hist = zaproxy.findInRequestHistory("continuumsecurity"); System.out.println(hist.get(0).getRequest().toString()); System.out.println(hist.get(1).getRequest().toString()); assertEquals(1,hist.size()); assertTrue(hist.get(0).getRequest().getMethod().equals("GET")); assertTrue(hist.get(0).getRequest().getQueryString().toString().contains("q")); assertTrue(hist.get(0).getRequest().getQueryString().toString().contains("continuumsecurity")); assertEquals("HTTP/1.1", hist.get(0).getRequest().getHttpVersion()); assertEquals(200, hist.get(0).getResponse().getStatus()); String content = new String(Base64.decode(hist.get(0).getResponse().getContent().getText())); System.out.println(content); assertTrue(content.contains("continuum security")); }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_WIDGET_UPDATE.equals(action)) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.vlcwidget); String title = intent.getStringExtra("title"); String artist = intent.getStringExtra("artist"); boolean isplaying = intent.getBooleanExtra("isplaying", false); Bitmap cover = intent.getParcelableExtra("cover"); views.setTextViewText(R.id.songName, title); views.setTextViewText(R.id.artist, artist); views.setImageViewResource(R.id.play_pause, isplaying ? R.drawable.ic_pause : R.drawable.ic_play); if (cover != null) views.setImageViewBitmap(R.id.cover, cover); else views.setImageViewResource(R.id.cover, R.drawable.cone); views.setViewVisibility(R.id.timeline_parent, artist.length() > 0 ? View.VISIBLE : View.INVISIBLE); Intent iBackward = new Intent(ACTION_REMOTE_BACKWARD); Intent iPlay = new Intent(ACTION_REMOTE_PLAYPAUSE); Intent iStop = new Intent(ACTION_REMOTE_STOP); Intent iForward = new Intent(ACTION_REMOTE_FORWARD); Intent iVlc = new Intent(); iVlc.setClassName(VLC_PACKAGE, isplaying ? VLC_PLAYER : VLC_MAIN); iVlc.putExtra(START_FROM_NOTIFICATION, true); PendingIntent piBackward = PendingIntent.getBroadcast(context, 0, iBackward, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piPlay = PendingIntent.getBroadcast(context, 0, iPlay, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piStop = PendingIntent.getBroadcast(context, 0, iStop, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piForward = PendingIntent.getBroadcast(context, 0, iForward, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piVlc = PendingIntent.getActivity(context, 0, iVlc, PendingIntent.FLAG_UPDATE_CURRENT); views.setOnClickPendingIntent(R.id.backward, piBackward); views.setOnClickPendingIntent(R.id.play_pause, piPlay); views.setOnClickPendingIntent(R.id.stop, piStop); views.setOnClickPendingIntent(R.id.forward, piForward); views.setOnClickPendingIntent(R.id.cover, piVlc); ComponentName widget = new ComponentName(context, VLCAppWidgetProvider.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(widget, views); } else if (ACTION_WIDGET_UPDATE_POSITION.equals(action)) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.vlcwidget); float pos = intent.getFloatExtra("position", 0f); views.setProgressBar(R.id.timeline, 100, (int) (100 * pos), false); ComponentName widget = new ComponentName(context, VLCAppWidgetProvider.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(widget, views); } else super.onReceive(context, intent); }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_WIDGET_UPDATE.equals(action)) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.vlcwidget); String title = intent.getStringExtra("title"); String artist = intent.getStringExtra("artist"); boolean isplaying = intent.getBooleanExtra("isplaying", false); Bitmap cover = intent.getParcelableExtra("cover"); views.setTextViewText(R.id.songName, title); views.setTextViewText(R.id.artist, artist); views.setImageViewResource(R.id.play_pause, isplaying ? R.drawable.ic_pause : R.drawable.ic_play); if (cover != null) views.setImageViewBitmap(R.id.cover, cover); else views.setImageViewResource(R.id.cover, R.drawable.cone); views.setViewVisibility(R.id.timeline_parent, artist != null && artist.length() > 0 ? View.VISIBLE : View.INVISIBLE); Intent iBackward = new Intent(ACTION_REMOTE_BACKWARD); Intent iPlay = new Intent(ACTION_REMOTE_PLAYPAUSE); Intent iStop = new Intent(ACTION_REMOTE_STOP); Intent iForward = new Intent(ACTION_REMOTE_FORWARD); Intent iVlc = new Intent(); iVlc.setClassName(VLC_PACKAGE, isplaying ? VLC_PLAYER : VLC_MAIN); iVlc.putExtra(START_FROM_NOTIFICATION, true); PendingIntent piBackward = PendingIntent.getBroadcast(context, 0, iBackward, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piPlay = PendingIntent.getBroadcast(context, 0, iPlay, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piStop = PendingIntent.getBroadcast(context, 0, iStop, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piForward = PendingIntent.getBroadcast(context, 0, iForward, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piVlc = PendingIntent.getActivity(context, 0, iVlc, PendingIntent.FLAG_UPDATE_CURRENT); views.setOnClickPendingIntent(R.id.backward, piBackward); views.setOnClickPendingIntent(R.id.play_pause, piPlay); views.setOnClickPendingIntent(R.id.stop, piStop); views.setOnClickPendingIntent(R.id.forward, piForward); views.setOnClickPendingIntent(R.id.cover, piVlc); ComponentName widget = new ComponentName(context, VLCAppWidgetProvider.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(widget, views); } else if (ACTION_WIDGET_UPDATE_POSITION.equals(action)) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.vlcwidget); float pos = intent.getFloatExtra("position", 0f); views.setProgressBar(R.id.timeline, 100, (int) (100 * pos), false); ComponentName widget = new ComponentName(context, VLCAppWidgetProvider.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(widget, views); } else super.onReceive(context, intent); }
public BreakPoss getNextBreakPoss(LayoutContext context) { LayoutProcessor curLM ; BreakPoss prev = null; BreakPoss bp = null; ArrayList vecPossEnd = new ArrayList(); MinOptMax availIPD = context.getStackLimit(); LayoutContext inlineLC = new LayoutContext(context); clearPrevIPD(); int iPrevLineEnd = vecInlineBreaks.size(); prevBP = null; while ((curLM = getChildLM()) != null) { boolean bFirstBPforLM = (vecInlineBreaks.isEmpty() || (((BreakPoss) vecInlineBreaks.get(vecInlineBreaks.size() - 1)). getLayoutManager() != curLM)); prev = (vecInlineBreaks.isEmpty()) ? null : (BreakPoss) vecInlineBreaks.get(vecInlineBreaks.size() - 1); initChildLC(inlineLC, prev, (vecInlineBreaks.size() == iPrevLineEnd), bFirstBPforLM, new SpaceSpecifier(true)); inlineLC.setFlags(LayoutContext.SUPPRESS_LEADING_SPACE, (vecInlineBreaks.size() == iPrevLineEnd && !vecInlineBreaks.isEmpty() && ((BreakPoss) vecInlineBreaks.get(vecInlineBreaks.size() - 1)). isForcedBreak() == false)); if ((bp = curLM.getNextBreakPoss(inlineLC)) != null) { MinOptMax prevIPD = updatePrevIPD(bp, prev, (vecInlineBreaks.size() == iPrevLineEnd), inlineLC.isFirstArea()); MinOptMax bpDim = MinOptMax.add(bp.getStackingSize(), prevIPD); boolean bBreakOK = couldEndLine(bp); if (bBreakOK) { bpDim.add(bp.resolveTrailingSpace(true)); } if (bpDim.min > availIPD.max) { if (bTextAlignment == TextAlign.JUSTIFY || prevBP == null) { if (inlineLC.tryHyphenate()) { break; } if (!bBreakOK) { vecInlineBreaks.add(bp); continue; } inlineLC.setHyphContext( getHyphenContext(prevBP, bp)); if (inlineLC.getHyphContext() == null) { break; } inlineLC.setFlags(LayoutContext.TRY_HYPHENATE, true); reset(); } else { break; } } else { vecInlineBreaks.add(bp); if (bBreakOK) { prevBP = bp; if (bp.isForcedBreak()) { break; } if (bpDim.max >= availIPD.min) { vecPossEnd.add(new BreakCost(bp, Math.abs(availIPD.opt - bpDim.opt))); } } else { } } } else { } if (inlineLC.tryHyphenate() && !inlineLC.getHyphContext().hasMoreHyphPoints()) { break; } } if ((curLM = getChildLM()) == null) { setFinished(true); } if (bp == null) { return null; } if (prevBP == null) { prevBP = bp; } if (!bp.isForcedBreak() && vecPossEnd.size() > 0) { prevBP = getBestBP(vecPossEnd); } if (bp != prevBP && !bp.couldEndLine()) { reset(); } int talign = bTextAlignment; if ((bTextAlignment == TextAlign.JUSTIFY && (prevBP.isForcedBreak() || isFinished()))) { talign = TextAlign.START; } return makeLineBreak(iPrevLineEnd, availIPD, talign); }
public BreakPoss getNextBreakPoss(LayoutContext context) { LayoutProcessor curLM ; BreakPoss prev = null; BreakPoss bp = null; ArrayList vecPossEnd = new ArrayList(); MinOptMax availIPD = context.getStackLimit(); LayoutContext inlineLC = new LayoutContext(context); clearPrevIPD(); int iPrevLineEnd = vecInlineBreaks.size(); prevBP = null; while ((curLM = getChildLM()) != null) { boolean bFirstBPforLM = (vecInlineBreaks.isEmpty() || (((BreakPoss) vecInlineBreaks.get(vecInlineBreaks.size() - 1)). getLayoutManager() != curLM)); prev = (vecInlineBreaks.isEmpty()) ? null : (BreakPoss) vecInlineBreaks.get(vecInlineBreaks.size() - 1); initChildLC(inlineLC, prev, (vecInlineBreaks.size() == iPrevLineEnd), bFirstBPforLM, new SpaceSpecifier(true)); inlineLC.setFlags(LayoutContext.SUPPRESS_LEADING_SPACE, (vecInlineBreaks.size() == iPrevLineEnd && !vecInlineBreaks.isEmpty() && ((BreakPoss) vecInlineBreaks.get(vecInlineBreaks.size() - 1)). isForcedBreak() == false)); if ((bp = curLM.getNextBreakPoss(inlineLC)) != null) { MinOptMax prevIPD = updatePrevIPD(bp, prev, (vecInlineBreaks.size() == iPrevLineEnd), inlineLC.isFirstArea()); MinOptMax bpDim = MinOptMax.add(bp.getStackingSize(), prevIPD); boolean bBreakOK = couldEndLine(bp); if (bBreakOK) { bpDim.add(bp.resolveTrailingSpace(true)); } if (bpDim.min > availIPD.max) { if (bTextAlignment == TextAlign.JUSTIFY || prevBP == null) { if (inlineLC.tryHyphenate()) { break; } if (!bBreakOK) { vecInlineBreaks.add(bp); continue; } inlineLC.setHyphContext( getHyphenContext(prevBP, bp)); if (inlineLC.getHyphContext() == null) { break; } inlineLC.setFlags(LayoutContext.TRY_HYPHENATE, true); reset(); } else { break; } } else { vecInlineBreaks.add(bp); if (bBreakOK) { prevBP = bp; if (bp.isForcedBreak()) { break; } if (bpDim.max >= availIPD.min) { vecPossEnd.add(new BreakCost(bp, Math.abs(availIPD.opt - bpDim.opt))); } } else { } } } else { } if (inlineLC.tryHyphenate() && !inlineLC.getHyphContext().hasMoreHyphPoints()) { break; } } if ((curLM = getChildLM()) == null) { setFinished(true); } if (bp == null) { return null; } if (prevBP == null) { prevBP = bp; } if (!bp.isForcedBreak() && vecPossEnd.size() > 0) { prevBP = getBestBP(vecPossEnd); } if (bp != prevBP && !prevBP.couldEndLine()) { reset(); } int talign = bTextAlignment; if ((bTextAlignment == TextAlign.JUSTIFY && (prevBP.isForcedBreak() || isFinished()))) { talign = TextAlign.START; } return makeLineBreak(iPrevLineEnd, availIPD, talign); }
private boolean checkOperation(Operation op, ISymbol...symbols) throws ECompilerException{ if (op.eIsProxy()) op = (Operation) EcoreUtil2.resolve(op, pack); if (op.getParams().size() != symbols.length) return false; for(int i=0;i<symbols.length;i++){ ParameterVariable pv = op.getParams().get(i); ISymbol s = symbols[i]; if (s instanceof ILiteralSymbol){ if (pv.getKind() == ParameterKind.VAR) return false; TypeDef td = pv.getVar().getType().getDef(); if (td instanceof DataTypeDef){ int bits = ((DataTypeDef) td).getBits(); if (1<<bits <= ((ILiteralSymbol) s).getValue()) return false; }else{ return false; } }else if (s instanceof IVariableSymbol){ if (pv.getKind() == ParameterKind.CONST) return false; if (s.getType() != pv.getVar().getType()) return false; }else{ throw new IllegalArgumentException("Unsupported operator symbol: "+s); } } return true; }
private boolean checkOperation(Operation op, ISymbol...symbols) throws ECompilerException{ if (op.eIsProxy()) op = (Operation) EcoreUtil2.resolve(op, pack); if (op.getParams().size() != symbols.length) return false; for(int i=0;i<symbols.length;i++){ ParameterVariable pv = op.getParams().get(i); ISymbol s = symbols[i]; if (s instanceof ILiteralSymbol && s.isLiteral()){ if (pv.getKind() == ParameterKind.VAR) return false; TypeDef td = pv.getVar().getType().getDef(); if (td instanceof DataTypeDef){ int bits = ((DataTypeDef) td).getBits(); if (1<<bits <= ((ILiteralSymbol) s).getValue()) return false; }else{ return false; } }else if (s instanceof IVariableSymbol){ if (pv.getKind() == ParameterKind.CONST) return false; if (s.getType() != pv.getVar().getType()) return false; }else{ throw new IllegalArgumentException("Unsupported operator symbol: "+s); } } return true; }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession httpSession = request.getSession(); Context.logout(); response.sendRedirect(request.getContextPath() + "?noredirect=true"); httpSession.invalidate(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession httpSession = request.getSession(); Context.logout(); response.sendRedirect(request.getContextPath() + "/index.htm?noredirect=true"); httpSession.invalidate(); }
public Integer parseArgs(String[] args, Configuration conf, HBaseIndexingOptions opts) { assert args != null; assert conf != null; assert opts != null; if (args.length == 0) { args = new String[] { "--help" }; } showNonSolrCloud = Arrays.asList(args).contains(SHOW_NON_SOLR_CLOUD); ArgumentParser parser = ArgumentParsers .newArgumentParser("hadoop [GenericOptions]... jar hbase-indexer-mr-*-job.jar", false) .defaultHelp(true) .description( "MapReduce batch job driver that takes input data from an HBase table and creates Solr index shards and writes the " + "indexes into HDFS, in a flexible, scalable, and fault-tolerant manner. It also supports merging the output shards " + "into a set of live customer-facing Solr servers in SolrCloud. Optionally, documents can be sent directly from the " + "mapper tasks to SolrCloud, which is a much less scalable approach but enables updating existing documents in SolrCloud. " + "The program proceeds in one or multiple consecutive MapReduce-based phases, as follows:\n\n" + "1) Mapper phase: This (parallel) phase scans over the input HBase table, extracts the relevant content, and " + "transforms it into SolrInputDocuments. If run as a mapper-only job, this phase also writes the SolrInputDocuments " + "directly to a live SolrCloud cluster. The conversion from HBase records into Solr documents is performed via a " + "hbase-indexer configuration and typically based on a morphline.\n\n" + "2) Reducer phase: This (parallel) phase loads the mapper's SolrInputDocuments into one EmbeddedSolrServer per reducer. " + "Each such reducer and Solr server can be seen as a (micro) shard. The Solr servers store their data in HDFS.\n\n" + "3) Mapper-only merge phase: This (parallel) phase merges the set of reducer shards into the number of " + "Solr shards expected by the user, using a mapper-only job. This phase is omitted if the number of shards is " + "already equal to the number of shards expected by the user\n\n" + "4) Go-live phase: This optional (parallel) phase merges the output shards of the previous phase into a set of " + "live customer-facing Solr servers in SolrCloud. If this phase is omitted you can expecitly point each Solr " + "server to one of the HDFS output shard directories\n\n" + "Fault Tolerance: Mapper and reducer task attempts are retried on failure per the standard MapReduce semantics. " + "On program startup all data in the --output-dir is deleted if that output directory already exists and " + "--overwrite-output-dir is specified. This means that if the whole job fails you can retry simply by rerunning " + "the program again using the same arguments." ); ArgumentGroup hbaseIndexerGroup = parser.addArgumentGroup("HBase Indexer parameters") .description("Parameters for specifying the HBase indexer definition and/or where it should be loaded from."); Argument indexerZkHostArg = hbaseIndexerGroup.addArgument("--hbase-indexer-zk") .metavar("STRING") .help("The address of the ZooKeeper ensemble from which to fetch the indexer definition named --hbase-indexer-name. " + "Format is: a list of comma separated host:port pairs, each corresponding to a zk server. " + "Example: '127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183'"); Argument indexNameArg = hbaseIndexerGroup.addArgument("--hbase-indexer-name") .metavar("STRING") .help("The name of the indexer configuration to fetch from the ZooKeeper ensemble specified " + "with --hbase-indexer-zk. Example: myIndexer"); Argument hbaseIndexerConfigArg = hbaseIndexerGroup.addArgument("--hbase-indexer-file") .metavar("FILE") .type(new FileArgumentType().verifyExists().verifyIsFile().verifyCanRead()) .help("Relative or absolute path to a local HBase indexer XML configuration file. If " + "supplied, this overrides --hbase-indexer-zk and --hbase-indexer-name. " + "Example: /path/to/morphline-hbase-mapper.xml"); Argument hbaseIndexerComponentFactoryArg = hbaseIndexerGroup.addArgument("--hbase-indexer-component-factory") .metavar("STRING") .help("Classname of the hbase indexer component factory."); ArgumentGroup scanArgumentGroup = parser.addArgumentGroup("HBase scan parameters") .description("Parameters for specifying what data is included while reading from HBase."); Argument hbaseTableNameArg = scanArgumentGroup.addArgument("--hbase-table-name") .metavar("STRING") .help("Optional name of the HBase table containing the records to be indexed. If " + "supplied, this overrides the value from the --hbase-indexer-* options. " + "Example: myTable"); Argument startRowArg = scanArgumentGroup.addArgument("--hbase-start-row") .metavar("BINARYSTRING") .help("Binary string representation of start row from which to start indexing (inclusive). " + "The format of the supplied row key should use two-digit hex values prefixed by " + "\\x for non-ascii characters (e.g. 'row\\x00'). The semantics of this " + "argument are the same as those for the HBase Scan#setStartRow method. " + "The default is to include the first row of the table. Example: AAAA"); Argument endRowArg = scanArgumentGroup.addArgument("--hbase-end-row") .metavar("BINARYSTRING") .help("Binary string representation of end row prefix at which to stop indexing (exclusive). " + "See the description of --hbase-start-row for more information. " + "The default is to include the last row of the table. Example: CCCC"); Argument startTimeArg = scanArgumentGroup.addArgument("--hbase-start-time") .metavar("STRING") .help("Earliest timestamp (inclusive) in time range of HBase cells to be included for indexing. " + "The default is to include all cells. Example: 0"); Argument endTimeArg = scanArgumentGroup.addArgument("--hbase-end-time") .metavar("STRING") .help("Latest timestamp (exclusive) of HBase cells to be included for indexing. " + "The default is to include all cells. Example: 123456789"); Argument timestampFormatArg = scanArgumentGroup.addArgument("--hbase-timestamp-format") .metavar("STRING") .help("Timestamp format to be used to interpret --hbase-start-time and --hbase-end-time. " + "This is a java.text.SimpleDateFormat compliant format (see " + "http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html). " + "If this parameter is omitted then the timestamps are interpreted as number of " + "milliseconds since the standard epoch (Unix time). " + "Example: yyyy-MM-dd'T'HH:mm:ss.SSSZ"); ArgumentGroup solrClusterInfoGroup = parser.addArgumentGroup("Solr cluster arguments") .description( "Arguments that provide information about your Solr cluster. " + nonSolrCloud("If you are building shards for a SolrCloud cluster, pass the --zk-host argument. " + "If you are building shards for " + "a Non-SolrCloud cluster, pass the --shard-url argument one or more times. To build indexes for " + "a replicated Non-SolrCloud cluster with --shard-url, pass replica urls consecutively and also pass --shards. " + "Using --go-live requires either --zk-host or --shard-url.")); Argument zkHostArg = solrClusterInfoGroup.addArgument("--zk-host") .metavar("STRING") .type(String.class) .help("The address of a ZooKeeper ensemble being used by a SolrCloud cluster. " + "This ZooKeeper ensemble will be examined to determine the number of output " + "shards to create as well as the Solr URLs to merge the output shards into when using the --go-live option. " + "Requires that you also pass the --collection to merge the shards into.\n" + "\n" + "The --zk-host option implements the same partitioning semantics as the standard SolrCloud " + "Near-Real-Time (NRT) API. This enables to mix batch updates from MapReduce ingestion with " + "updates from standard Solr NRT ingestion on the same SolrCloud cluster, " + "using identical unique document keys.\n" + "\n" + "Format is: a list of comma separated host:port pairs, each corresponding to a zk " + "server. Example: '127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183' If " + "the optional chroot suffix is used the example would look " + "like: '127.0.0.1:2181/solr,127.0.0.1:2182/solr,127.0.0.1:2183/solr' " + "where the client would be rooted at '/solr' and all paths " + "would be relative to this root - i.e. getting/setting/etc... " + "'/foo/bar' would result in operations being run on " + "'/solr/foo/bar' (from the server perspective).\n" + nonSolrCloud("\n" + "If --solr-home-dir is not specified, the Solr home directory for the collection " + "will be downloaded from this ZooKeeper ensemble.")); Argument shardUrlsArg = nonSolrCloud(solrClusterInfoGroup.addArgument("--shard-url") .metavar("URL") .type(String.class) .action(Arguments.append()) .help("Solr URL to merge resulting shard into if using --go-live. " + "Example: http://solr001.mycompany.com:8983/solr/collection1. " + "Multiple --shard-url arguments can be specified, one for each desired shard. " + "If you are merging shards into a SolrCloud cluster, use --zk-host instead.")); Argument shardsArg = nonSolrCloud(solrClusterInfoGroup.addArgument("--shards") .metavar("INTEGER") .type(Integer.class).choices(new RangeArgumentChoice(1, Integer.MAX_VALUE)) .help("Number of output shards to generate.")); ArgumentGroup goLiveGroup = parser.addArgumentGroup("Go live arguments") .description("Arguments for merging the shards that are built into a live Solr cluster. " + "Also see the Cluster arguments."); Argument goLiveArg = goLiveGroup.addArgument("--go-live") .action(Arguments.storeTrue()) .help("Allows you to optionally merge the final index shards into a live Solr cluster after they are built. " + "You can pass the ZooKeeper address with --zk-host and the relevant cluster information will be auto detected. " + nonSolrCloud("If you are not using a SolrCloud cluster, --shard-url arguments can be used to specify each SolrCore to merge " + "each shard into.")); Argument collectionArg = goLiveGroup.addArgument("--collection") .metavar("STRING") .help("The SolrCloud collection to merge shards into when using --go-live and --zk-host. Example: collection1"); Argument goLiveThreadsArg = goLiveGroup.addArgument("--go-live-threads") .metavar("INTEGER") .type(Integer.class) .choices(new RangeArgumentChoice(1, Integer.MAX_VALUE)) .setDefault(1000) .help("Tuning knob that indicates the maximum number of live merges to run in parallel at one time."); ArgumentGroup optionalGroup = parser.addArgumentGroup("Optional arguments"); optionalGroup.addArgument("--help", "-help", "-h").help("Show this help message and exit") .action(new HelpArgumentAction() { @Override public void run(ArgumentParser parser, Argument arg, Map<String, Object> attrs, String flag, Object value) throws ArgumentParserException { parser.printHelp(new PrintWriter(System.out, true)); System.out.println(); System.out.print(ForkedToolRunnerHelpFormatter.getGenericCommandUsage()); System.out.println("Examples: \n\n" + "# (Re)index a table in GoLive mode based on a local indexer config file\n" + "hadoop --config /etc/hadoop/conf \\\n" + " jar hbase-indexer-mr-*-job.jar \\\n" + " --conf /etc/hbase/conf/hbase-site.xml \\\n" + " -D 'mapred.child.java.opts=-Xmx500m' \\\n" + " --hbase-indexer-file indexer.xml \\\n" + " --zk-host 127.0.0.1/solr \\\n" + " --collection collection1 \\\n" + " --go-live \\\n" + " --log4j src/test/resources/log4j.properties\n\n" + "# (Re)index a table in GoLive mode using a local morphline-based indexer config file\n" + "# Also include extra library jar file containing JSON tweet Java parser:\n" + "hadoop --config /etc/hadoop/conf \\\n" + " jar hbase-indexer-mr-*-job.jar \\\n" + " --conf /etc/hbase/conf/hbase-site.xml \\\n" + " --libjars /path/to/kite-morphlines-twitter-0.10.0.jar \\\n" + " -D 'mapred.child.java.opts=-Xmx500m' \\\n" + " --hbase-indexer-file src/test/resources/morphline_indexer_without_zk.xml \\\n" + " --zk-host 127.0.0.1/solr \\\n" + " --collection collection1 \\\n" + " --go-live \\\n" + " --morphline-file src/test/resources/morphlines.conf \\\n" + " --output-dir hdfs://c2202.mycompany.com/user/$USER/test \\\n" + " --overwrite-output-dir \\\n" + " --log4j src/test/resources/log4j.properties\n\n" + "# (Re)index a table in GoLive mode\n" + "hadoop --config /etc/hadoop/conf \\\n" + " jar hbase-indexer-mr-*-job.jar \\\n" + " --conf /etc/hbase/conf/hbase-site.xml \\\n" + " -D 'mapred.child.java.opts=-Xmx500m' \\\n" + " --hbase-indexer-file indexer.xml \\\n" + " --zk-host 127.0.0.1/solr \\\n" + " --collection collection1 \\\n" + " --go-live \\\n" + " --log4j src/test/resources/log4j.properties\n\n" + "# (Re)index a table with direct writes to SolrCloud\n" + "hadoop --config /etc/hadoop/conf \\\n" + " jar hbase-indexer-mr-*-job.jar \\\n" + " --conf /etc/hbase/conf/hbase-site.xml \\\n" + " -D 'mapred.child.java.opts=-Xmx500m' \\\n" + " --hbase-indexer-file indexer.xml \\\n" + " --zk-host 127.0.0.1/solr \\\n" + " --collection collection1 \\\n" + " --reducers 0 \\\n" + " --log4j src/test/resources/log4j.properties\n\n" + "# (Re)index a table based on a indexer config stored in ZK\n" + "hadoop --config /etc/hadoop/conf \\\n" + " jar hbase-indexer-mr-*-job.jar \\\n" + " --conf /etc/hbase/conf/hbase-site.xml \\\n" + " -D 'mapred.child.java.opts=-Xmx500m' \\\n" + " --hbase-indexer-zk zk01 \\\n" + " --hbase-indexer-name docindexer \\\n" + " --go-live \\\n" + " --log4j src/test/resources/log4j.properties\n\n"); throw new FoundHelpArgument(); } }); Argument outputDirArg = optionalGroup.addArgument("--output-dir") .metavar("HDFS_URI") .type(new PathArgumentType(conf) { @Override public Path convert(ArgumentParser parser, Argument arg, String value) throws ArgumentParserException { Path path = super.convert(parser, arg, value); if ("hdfs".equals(path.toUri().getScheme()) && path.toUri().getAuthority() == null) { throw new ArgumentParserException("Missing authority in path URI: " + path, parser); } return path; } }.verifyHasScheme().verifyIsAbsolute().verifyCanWriteParent()) .help("HDFS directory to write Solr indexes to. Inside there one output directory per shard will be generated. " + "Example: hdfs://c2202.mycompany.com/user/$USER/test"); Argument overwriteOutputDirArg = optionalGroup.addArgument("--overwrite-output-dir") .action(Arguments.storeTrue()) .help("Overwrite the directory specified by --output-dir if it already exists. Using this parameter will result in " + "the output directory being recursively deleted at job startup."); Argument morphlineFileArg = optionalGroup.addArgument("--morphline-file") .metavar("FILE") .type(new FileArgumentType().verifyExists().verifyIsFile().verifyCanRead()) .help("Relative or absolute path to a local config file that contains one or more morphlines. " + "The file must be UTF-8 encoded. The file will be uploaded to each MR task. " + "If supplied, this overrides the value from the --hbase-indexer-* options. " + "Example: /path/to/morphlines.conf"); Argument morphlineIdArg = optionalGroup.addArgument("--morphline-id") .metavar("STRING") .type(String.class) .help("The identifier of the morphline that shall be executed within the morphline config file, " + "e.g. specified by --morphline-file. If the --morphline-id option is ommitted the first (i.e. " + "top-most) morphline within the config file is used. If supplied, this overrides the value " + "from the --hbase-indexer-* options. Example: morphline1 "); Argument solrHomeDirArg = nonSolrCloud(optionalGroup.addArgument("--solr-home-dir") .metavar("DIR") .type(new FileArgumentType() { @Override public File convert(ArgumentParser parser, Argument arg, String value) throws ArgumentParserException { File solrHomeDir = super.convert(parser, arg, value); File solrConfigFile = new File(new File(solrHomeDir, "conf"), "solrconfig.xml"); new FileArgumentType().verifyExists().verifyIsFile().verifyCanRead() .convert(parser, arg, solrConfigFile.getPath()); return solrHomeDir; } }.verifyIsDirectory().verifyCanRead()) .required(false) .help("Relative or absolute path to a local dir containing Solr conf/ dir and in particular " + "conf/solrconfig.xml and optionally also lib/ dir. This directory will be uploaded to each MR task. " + "Example: src/test/resources/solr/minimr")); Argument updateConflictResolverArg = optionalGroup.addArgument("--update-conflict-resolver") .metavar("FQCN") .type(String.class) .setDefault(RetainMostRecentUpdateConflictResolver.class.getName()) .help("Fully qualified class name of a Java class that implements the UpdateConflictResolver interface. " + "This enables deduplication and ordering of a series of document updates for the same unique document " + "key. For example, a MapReduce batch job might index multiple files in the same job where some of the " + "files contain old and new versions of the very same document, using the same unique document key.\n" + "Typically, implementations of this interface forbid collisions by throwing an exception, or ignore all but " + "the most recent document version, or, in the general case, order colliding updates ascending from least " + "recent to most recent (partial) update. The caller of this interface (i.e. the Hadoop Reducer) will then " + "apply the updates to Solr in the order returned by the orderUpdates() method.\n" + "The default RetainMostRecentUpdateConflictResolver implementation ignores all but the most recent document " + "version, based on a configurable numeric Solr field, which defaults to the file_last_modified timestamp"); Argument reducersArg = optionalGroup.addArgument("--reducers") .metavar("INTEGER") .type(Integer.class) .choices(new RangeArgumentChoice(-2, Integer.MAX_VALUE)) .setDefault(-1) .help("Tuning knob that indicates the number of reducers to index into. " + "0 indicates that no reducers should be used, and documents should be sent directly from the mapper tasks to live Solr servers. " + "-1 indicates use all reduce slots available on the cluster. " + "-2 indicates use one reducer per output shard, which disables the mtree merge MR algorithm. " + "The mtree merge MR algorithm improves scalability by spreading load " + "(in particular CPU load) among a number of parallel reducers that can be much larger than the number " + "of solr shards expected by the user. It can be seen as an extension of concurrent lucene merges " + "and tiered lucene merges to the clustered case. The subsequent mapper-only phase " + "merges the output of said large number of reducers to the number of shards expected by the user, " + "again by utilizing more available parallelism on the cluster."); Argument fanoutArg = optionalGroup.addArgument("--fanout") .metavar("INTEGER") .type(Integer.class) .choices(new RangeArgumentChoice(2, Integer.MAX_VALUE)) .setDefault(Integer.MAX_VALUE) .help(FeatureControl.SUPPRESS); Argument maxSegmentsArg = optionalGroup.addArgument("--max-segments") .metavar("INTEGER") .type(Integer.class) .choices(new RangeArgumentChoice(1, Integer.MAX_VALUE)) .setDefault(1) .help("Tuning knob that indicates the maximum number of segments to be contained on output in the index of " + "each reducer shard. After a reducer has built its output index it applies a merge policy to merge segments " + "until there are <= maxSegments lucene segments left in this index. " + "Merging segments involves reading and rewriting all data in all these segment files, " + "potentially multiple times, which is very I/O intensive and time consuming. " + "However, an index with fewer segments can later be merged faster, " + "and it can later be queried faster once deployed to a live Solr serving shard. " + "Set maxSegments to 1 to optimize the index for low query latency. " + "In a nutshell, a small maxSegments value trades indexing latency for subsequently improved query latency. " + "This can be a reasonable trade-off for batch indexing systems."); Argument fairSchedulerPoolArg = optionalGroup.addArgument("--fair-scheduler-pool") .metavar("STRING") .help("Optional tuning knob that indicates the name of the fair scheduler pool to submit jobs to. " + "The Fair Scheduler is a pluggable MapReduce scheduler that provides a way to share large clusters. " + "Fair scheduling is a method of assigning resources to jobs such that all jobs get, on average, an " + "equal share of resources over time. When there is a single job running, that job uses the entire " + "cluster. When other jobs are submitted, tasks slots that free up are assigned to the new jobs, so " + "that each job gets roughly the same amount of CPU time. Unlike the default Hadoop scheduler, which " + "forms a queue of jobs, this lets short jobs finish in reasonable time while not starving long jobs. " + "It is also an easy way to share a cluster between multiple of users. Fair sharing can also work with " + "job priorities - the priorities are used as weights to determine the fraction of total compute time " + "that each job gets."); Argument dryRunArg = optionalGroup.addArgument("--dry-run") .action(Arguments.storeTrue()) .help("Run in local mode and print documents to stdout instead of loading them into Solr. This executes " + "the morphline in the client process (without submitting a job to MR) for quicker turnaround during " + "early trial & debug sessions."); Argument log4jConfigFileArg = optionalGroup.addArgument("--log4j") .metavar("FILE") .type(new FileArgumentType().verifyExists().verifyIsFile().verifyCanRead()) .help("Relative or absolute path to a log4j.properties config file on the local file system. This file " + "will be uploaded to each MR task. Example: /path/to/log4j.properties"); Argument verboseArg = optionalGroup.addArgument("--verbose", "-v") .action(Arguments.storeTrue()) .help("Turn on verbose output."); Argument clearIndexArg = optionalGroup.addArgument("--clear-index") .action(Arguments.storeTrue()) .help("Will attempt to delete all entries in a solr index before starting batch build. This is not " + "transactional so if the build fails the index will be empty."); optionalGroup.addArgument(SHOW_NON_SOLR_CLOUD) .action(Arguments.storeTrue()) .help("Also show options for Non-SolrCloud mode as part of --help."); Namespace ns; try { ns = parser.parseArgs(args); } catch (FoundHelpArgument e) { return 0; } catch (ArgumentParserException e) { parser.handleError(e); return 1; } opts.log4jConfigFile = (File) ns.get(log4jConfigFileArg.getDest()); if (opts.log4jConfigFile != null) { PropertyConfigurator.configure(opts.log4jConfigFile.getPath()); } LOG.debug("Parsed command line args: " + ns); opts.inputLists = Collections.EMPTY_LIST; opts.outputDir = (Path) ns.get(outputDirArg.getDest()); opts.overwriteOutputDir = ns.getBoolean(overwriteOutputDirArg.getDest()); opts.reducers = ns.getInt(reducersArg.getDest()); opts.updateConflictResolver = ns.getString(updateConflictResolverArg.getDest()); opts.fanout = ns.getInt(fanoutArg.getDest()); opts.maxSegments = ns.getInt(maxSegmentsArg.getDest()); opts.morphlineFile = (File) ns.get(morphlineFileArg.getDest()); opts.morphlineId = ns.getString(morphlineIdArg.getDest()); opts.solrHomeDir = (File) ns.get(solrHomeDirArg.getDest()); opts.fairSchedulerPool = ns.getString(fairSchedulerPoolArg.getDest()); opts.isDryRun = ns.getBoolean(dryRunArg.getDest()); opts.isVerbose = ns.getBoolean(verboseArg.getDest()); opts.zkHost = ns.getString(zkHostArg.getDest()); opts.shards = ns.getInt(shardsArg.getDest()); opts.shardUrls = ForkedMapReduceIndexerTool.buildShardUrls(ns.getList(shardUrlsArg.getDest()), opts.shards); opts.goLive = ns.getBoolean(goLiveArg.getDest()); opts.goLiveThreads = ns.getInt(goLiveThreadsArg.getDest()); opts.collection = ns.getString(collectionArg.getDest()); opts.clearIndex = ns.getBoolean(clearIndexArg.getDest()); opts.hbaseIndexerComponentFactory = (String) ns.get(hbaseIndexerComponentFactoryArg.getDest()); opts.hbaseIndexerConfigFile = (File) ns.get(hbaseIndexerConfigArg.getDest()); opts.hbaseIndexerZkHost = ns.getString(indexerZkHostArg.getDest()); opts.hbaseIndexerName = ns.getString(indexNameArg.getDest()); opts.hbaseTableName = ns.getString(hbaseTableNameArg.getDest()); opts.hbaseStartRow = ns.getString(startRowArg.getDest()); opts.hbaseEndRow = ns.getString(endRowArg.getDest()); opts.hbaseStartTimeString = ns.getString(startTimeArg.getDest()); opts.hbaseEndTimeString = ns.getString(endTimeArg.getDest()); opts.hbaseTimestampFormat = ns.getString(timestampFormatArg.getDest()); try { try { opts.evaluate(); } catch (IllegalStateException ise) { throw new ArgumentParserException(ise.getMessage(), parser); } } catch (ArgumentParserException e) { parser.handleError(e); return 1; } return null; }
public Integer parseArgs(String[] args, Configuration conf, HBaseIndexingOptions opts) { assert args != null; assert conf != null; assert opts != null; if (args.length == 0) { args = new String[] { "--help" }; } showNonSolrCloud = Arrays.asList(args).contains(SHOW_NON_SOLR_CLOUD); ArgumentParser parser = ArgumentParsers .newArgumentParser("hadoop [GenericOptions]... jar hbase-indexer-mr-*-job.jar", false) .defaultHelp(true) .description( "MapReduce batch job driver that takes input data from an HBase table and creates Solr index shards and writes the " + "indexes into HDFS, in a flexible, scalable, and fault-tolerant manner. It also supports merging the output shards " + "into a set of live customer-facing Solr servers in SolrCloud. Optionally, documents can be sent directly from the " + "mapper tasks to SolrCloud, which is a much less scalable approach but enables updating existing documents in SolrCloud. " + "The program proceeds in one or multiple consecutive MapReduce-based phases, as follows:\n\n" + "1) Mapper phase: This (parallel) phase scans over the input HBase table, extracts the relevant content, and " + "transforms it into SolrInputDocuments. If run as a mapper-only job, this phase also writes the SolrInputDocuments " + "directly to a live SolrCloud cluster. The conversion from HBase records into Solr documents is performed via a " + "hbase-indexer configuration and typically based on a morphline.\n\n" + "2) Reducer phase: This (parallel) phase loads the mapper's SolrInputDocuments into one EmbeddedSolrServer per reducer. " + "Each such reducer and Solr server can be seen as a (micro) shard. The Solr servers store their data in HDFS.\n\n" + "3) Mapper-only merge phase: This (parallel) phase merges the set of reducer shards into the number of " + "Solr shards expected by the user, using a mapper-only job. This phase is omitted if the number of shards is " + "already equal to the number of shards expected by the user\n\n" + "4) Go-live phase: This optional (parallel) phase merges the output shards of the previous phase into a set of " + "live customer-facing Solr servers in SolrCloud. If this phase is omitted you can explicitly point each Solr " + "server to one of the HDFS output shard directories\n\n" + "Fault Tolerance: Mapper and reducer task attempts are retried on failure per the standard MapReduce semantics. " + "On program startup all data in the --output-dir is deleted if that output directory already exists and " + "--overwrite-output-dir is specified. This means that if the whole job fails you can retry simply by rerunning " + "the program again using the same arguments." ); ArgumentGroup hbaseIndexerGroup = parser.addArgumentGroup("HBase Indexer parameters") .description("Parameters for specifying the HBase indexer definition and/or where it should be loaded from."); Argument indexerZkHostArg = hbaseIndexerGroup.addArgument("--hbase-indexer-zk") .metavar("STRING") .help("The address of the ZooKeeper ensemble from which to fetch the indexer definition named --hbase-indexer-name. " + "Format is: a list of comma separated host:port pairs, each corresponding to a zk server. " + "Example: '127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183'"); Argument indexNameArg = hbaseIndexerGroup.addArgument("--hbase-indexer-name") .metavar("STRING") .help("The name of the indexer configuration to fetch from the ZooKeeper ensemble specified " + "with --hbase-indexer-zk. Example: myIndexer"); Argument hbaseIndexerConfigArg = hbaseIndexerGroup.addArgument("--hbase-indexer-file") .metavar("FILE") .type(new FileArgumentType().verifyExists().verifyIsFile().verifyCanRead()) .help("Relative or absolute path to a local HBase indexer XML configuration file. If " + "supplied, this overrides --hbase-indexer-zk and --hbase-indexer-name. " + "Example: /path/to/morphline-hbase-mapper.xml"); Argument hbaseIndexerComponentFactoryArg = hbaseIndexerGroup.addArgument("--hbase-indexer-component-factory") .metavar("STRING") .help("Classname of the hbase indexer component factory."); ArgumentGroup scanArgumentGroup = parser.addArgumentGroup("HBase scan parameters") .description("Parameters for specifying what data is included while reading from HBase."); Argument hbaseTableNameArg = scanArgumentGroup.addArgument("--hbase-table-name") .metavar("STRING") .help("Optional name of the HBase table containing the records to be indexed. If " + "supplied, this overrides the value from the --hbase-indexer-* options. " + "Example: myTable"); Argument startRowArg = scanArgumentGroup.addArgument("--hbase-start-row") .metavar("BINARYSTRING") .help("Binary string representation of start row from which to start indexing (inclusive). " + "The format of the supplied row key should use two-digit hex values prefixed by " + "\\x for non-ascii characters (e.g. 'row\\x00'). The semantics of this " + "argument are the same as those for the HBase Scan#setStartRow method. " + "The default is to include the first row of the table. Example: AAAA"); Argument endRowArg = scanArgumentGroup.addArgument("--hbase-end-row") .metavar("BINARYSTRING") .help("Binary string representation of end row prefix at which to stop indexing (exclusive). " + "See the description of --hbase-start-row for more information. " + "The default is to include the last row of the table. Example: CCCC"); Argument startTimeArg = scanArgumentGroup.addArgument("--hbase-start-time") .metavar("STRING") .help("Earliest timestamp (inclusive) in time range of HBase cells to be included for indexing. " + "The default is to include all cells. Example: 0"); Argument endTimeArg = scanArgumentGroup.addArgument("--hbase-end-time") .metavar("STRING") .help("Latest timestamp (exclusive) of HBase cells to be included for indexing. " + "The default is to include all cells. Example: 123456789"); Argument timestampFormatArg = scanArgumentGroup.addArgument("--hbase-timestamp-format") .metavar("STRING") .help("Timestamp format to be used to interpret --hbase-start-time and --hbase-end-time. " + "This is a java.text.SimpleDateFormat compliant format (see " + "http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html). " + "If this parameter is omitted then the timestamps are interpreted as number of " + "milliseconds since the standard epoch (Unix time). " + "Example: yyyy-MM-dd'T'HH:mm:ss.SSSZ"); ArgumentGroup solrClusterInfoGroup = parser.addArgumentGroup("Solr cluster arguments") .description( "Arguments that provide information about your Solr cluster. " + nonSolrCloud("If you are building shards for a SolrCloud cluster, pass the --zk-host argument. " + "If you are building shards for " + "a Non-SolrCloud cluster, pass the --shard-url argument one or more times. To build indexes for " + "a replicated Non-SolrCloud cluster with --shard-url, pass replica urls consecutively and also pass --shards. " + "Using --go-live requires either --zk-host or --shard-url.")); Argument zkHostArg = solrClusterInfoGroup.addArgument("--zk-host") .metavar("STRING") .type(String.class) .help("The address of a ZooKeeper ensemble being used by a SolrCloud cluster. " + "This ZooKeeper ensemble will be examined to determine the number of output " + "shards to create as well as the Solr URLs to merge the output shards into when using the --go-live option. " + "Requires that you also pass the --collection to merge the shards into.\n" + "\n" + "The --zk-host option implements the same partitioning semantics as the standard SolrCloud " + "Near-Real-Time (NRT) API. This enables to mix batch updates from MapReduce ingestion with " + "updates from standard Solr NRT ingestion on the same SolrCloud cluster, " + "using identical unique document keys.\n" + "\n" + "Format is: a list of comma separated host:port pairs, each corresponding to a zk " + "server. Example: '127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183' If " + "the optional chroot suffix is used the example would look " + "like: '127.0.0.1:2181/solr,127.0.0.1:2182/solr,127.0.0.1:2183/solr' " + "where the client would be rooted at '/solr' and all paths " + "would be relative to this root - i.e. getting/setting/etc... " + "'/foo/bar' would result in operations being run on " + "'/solr/foo/bar' (from the server perspective).\n" + nonSolrCloud("\n" + "If --solr-home-dir is not specified, the Solr home directory for the collection " + "will be downloaded from this ZooKeeper ensemble.")); Argument shardUrlsArg = nonSolrCloud(solrClusterInfoGroup.addArgument("--shard-url") .metavar("URL") .type(String.class) .action(Arguments.append()) .help("Solr URL to merge resulting shard into if using --go-live. " + "Example: http://solr001.mycompany.com:8983/solr/collection1. " + "Multiple --shard-url arguments can be specified, one for each desired shard. " + "If you are merging shards into a SolrCloud cluster, use --zk-host instead.")); Argument shardsArg = nonSolrCloud(solrClusterInfoGroup.addArgument("--shards") .metavar("INTEGER") .type(Integer.class).choices(new RangeArgumentChoice(1, Integer.MAX_VALUE)) .help("Number of output shards to generate.")); ArgumentGroup goLiveGroup = parser.addArgumentGroup("Go live arguments") .description("Arguments for merging the shards that are built into a live Solr cluster. " + "Also see the Cluster arguments."); Argument goLiveArg = goLiveGroup.addArgument("--go-live") .action(Arguments.storeTrue()) .help("Allows you to optionally merge the final index shards into a live Solr cluster after they are built. " + "You can pass the ZooKeeper address with --zk-host and the relevant cluster information will be auto detected. " + nonSolrCloud("If you are not using a SolrCloud cluster, --shard-url arguments can be used to specify each SolrCore to merge " + "each shard into.")); Argument collectionArg = goLiveGroup.addArgument("--collection") .metavar("STRING") .help("The SolrCloud collection to merge shards into when using --go-live and --zk-host. Example: collection1"); Argument goLiveThreadsArg = goLiveGroup.addArgument("--go-live-threads") .metavar("INTEGER") .type(Integer.class) .choices(new RangeArgumentChoice(1, Integer.MAX_VALUE)) .setDefault(1000) .help("Tuning knob that indicates the maximum number of live merges to run in parallel at one time."); ArgumentGroup optionalGroup = parser.addArgumentGroup("Optional arguments"); optionalGroup.addArgument("--help", "-help", "-h").help("Show this help message and exit") .action(new HelpArgumentAction() { @Override public void run(ArgumentParser parser, Argument arg, Map<String, Object> attrs, String flag, Object value) throws ArgumentParserException { parser.printHelp(new PrintWriter(System.out, true)); System.out.println(); System.out.print(ForkedToolRunnerHelpFormatter.getGenericCommandUsage()); System.out.println("Examples: \n\n" + "# (Re)index a table in GoLive mode based on a local indexer config file\n" + "hadoop --config /etc/hadoop/conf \\\n" + " jar hbase-indexer-mr-*-job.jar \\\n" + " --conf /etc/hbase/conf/hbase-site.xml \\\n" + " -D 'mapred.child.java.opts=-Xmx500m' \\\n" + " --hbase-indexer-file indexer.xml \\\n" + " --zk-host 127.0.0.1/solr \\\n" + " --collection collection1 \\\n" + " --go-live \\\n" + " --log4j src/test/resources/log4j.properties\n\n" + "# (Re)index a table in GoLive mode using a local morphline-based indexer config file\n" + "# Also include extra library jar file containing JSON tweet Java parser:\n" + "hadoop --config /etc/hadoop/conf \\\n" + " jar hbase-indexer-mr-*-job.jar \\\n" + " --conf /etc/hbase/conf/hbase-site.xml \\\n" + " --libjars /path/to/kite-morphlines-twitter-0.10.0.jar \\\n" + " -D 'mapred.child.java.opts=-Xmx500m' \\\n" + " --hbase-indexer-file src/test/resources/morphline_indexer_without_zk.xml \\\n" + " --zk-host 127.0.0.1/solr \\\n" + " --collection collection1 \\\n" + " --go-live \\\n" + " --morphline-file src/test/resources/morphlines.conf \\\n" + " --output-dir hdfs://c2202.mycompany.com/user/$USER/test \\\n" + " --overwrite-output-dir \\\n" + " --log4j src/test/resources/log4j.properties\n\n" + "# (Re)index a table in GoLive mode\n" + "hadoop --config /etc/hadoop/conf \\\n" + " jar hbase-indexer-mr-*-job.jar \\\n" + " --conf /etc/hbase/conf/hbase-site.xml \\\n" + " -D 'mapred.child.java.opts=-Xmx500m' \\\n" + " --hbase-indexer-file indexer.xml \\\n" + " --zk-host 127.0.0.1/solr \\\n" + " --collection collection1 \\\n" + " --go-live \\\n" + " --log4j src/test/resources/log4j.properties\n\n" + "# (Re)index a table with direct writes to SolrCloud\n" + "hadoop --config /etc/hadoop/conf \\\n" + " jar hbase-indexer-mr-*-job.jar \\\n" + " --conf /etc/hbase/conf/hbase-site.xml \\\n" + " -D 'mapred.child.java.opts=-Xmx500m' \\\n" + " --hbase-indexer-file indexer.xml \\\n" + " --zk-host 127.0.0.1/solr \\\n" + " --collection collection1 \\\n" + " --reducers 0 \\\n" + " --log4j src/test/resources/log4j.properties\n\n" + "# (Re)index a table based on a indexer config stored in ZK\n" + "hadoop --config /etc/hadoop/conf \\\n" + " jar hbase-indexer-mr-*-job.jar \\\n" + " --conf /etc/hbase/conf/hbase-site.xml \\\n" + " -D 'mapred.child.java.opts=-Xmx500m' \\\n" + " --hbase-indexer-zk zk01 \\\n" + " --hbase-indexer-name docindexer \\\n" + " --go-live \\\n" + " --log4j src/test/resources/log4j.properties\n\n"); throw new FoundHelpArgument(); } }); Argument outputDirArg = optionalGroup.addArgument("--output-dir") .metavar("HDFS_URI") .type(new PathArgumentType(conf) { @Override public Path convert(ArgumentParser parser, Argument arg, String value) throws ArgumentParserException { Path path = super.convert(parser, arg, value); if ("hdfs".equals(path.toUri().getScheme()) && path.toUri().getAuthority() == null) { throw new ArgumentParserException("Missing authority in path URI: " + path, parser); } return path; } }.verifyHasScheme().verifyIsAbsolute().verifyCanWriteParent()) .help("HDFS directory to write Solr indexes to. Inside there one output directory per shard will be generated. " + "Example: hdfs://c2202.mycompany.com/user/$USER/test"); Argument overwriteOutputDirArg = optionalGroup.addArgument("--overwrite-output-dir") .action(Arguments.storeTrue()) .help("Overwrite the directory specified by --output-dir if it already exists. Using this parameter will result in " + "the output directory being recursively deleted at job startup."); Argument morphlineFileArg = optionalGroup.addArgument("--morphline-file") .metavar("FILE") .type(new FileArgumentType().verifyExists().verifyIsFile().verifyCanRead()) .help("Relative or absolute path to a local config file that contains one or more morphlines. " + "The file must be UTF-8 encoded. The file will be uploaded to each MR task. " + "If supplied, this overrides the value from the --hbase-indexer-* options. " + "Example: /path/to/morphlines.conf"); Argument morphlineIdArg = optionalGroup.addArgument("--morphline-id") .metavar("STRING") .type(String.class) .help("The identifier of the morphline that shall be executed within the morphline config file, " + "e.g. specified by --morphline-file. If the --morphline-id option is ommitted the first (i.e. " + "top-most) morphline within the config file is used. If supplied, this overrides the value " + "from the --hbase-indexer-* options. Example: morphline1 "); Argument solrHomeDirArg = nonSolrCloud(optionalGroup.addArgument("--solr-home-dir") .metavar("DIR") .type(new FileArgumentType() { @Override public File convert(ArgumentParser parser, Argument arg, String value) throws ArgumentParserException { File solrHomeDir = super.convert(parser, arg, value); File solrConfigFile = new File(new File(solrHomeDir, "conf"), "solrconfig.xml"); new FileArgumentType().verifyExists().verifyIsFile().verifyCanRead() .convert(parser, arg, solrConfigFile.getPath()); return solrHomeDir; } }.verifyIsDirectory().verifyCanRead()) .required(false) .help("Relative or absolute path to a local dir containing Solr conf/ dir and in particular " + "conf/solrconfig.xml and optionally also lib/ dir. This directory will be uploaded to each MR task. " + "Example: src/test/resources/solr/minimr")); Argument updateConflictResolverArg = optionalGroup.addArgument("--update-conflict-resolver") .metavar("FQCN") .type(String.class) .setDefault(RetainMostRecentUpdateConflictResolver.class.getName()) .help("Fully qualified class name of a Java class that implements the UpdateConflictResolver interface. " + "This enables deduplication and ordering of a series of document updates for the same unique document " + "key. For example, a MapReduce batch job might index multiple files in the same job where some of the " + "files contain old and new versions of the very same document, using the same unique document key.\n" + "Typically, implementations of this interface forbid collisions by throwing an exception, or ignore all but " + "the most recent document version, or, in the general case, order colliding updates ascending from least " + "recent to most recent (partial) update. The caller of this interface (i.e. the Hadoop Reducer) will then " + "apply the updates to Solr in the order returned by the orderUpdates() method.\n" + "The default RetainMostRecentUpdateConflictResolver implementation ignores all but the most recent document " + "version, based on a configurable numeric Solr field, which defaults to the file_last_modified timestamp"); Argument reducersArg = optionalGroup.addArgument("--reducers") .metavar("INTEGER") .type(Integer.class) .choices(new RangeArgumentChoice(-2, Integer.MAX_VALUE)) .setDefault(-1) .help("Tuning knob that indicates the number of reducers to index into. " + "0 indicates that no reducers should be used, and documents should be sent directly from the mapper tasks to live Solr servers. " + "-1 indicates use all reduce slots available on the cluster. " + "-2 indicates use one reducer per output shard, which disables the mtree merge MR algorithm. " + "The mtree merge MR algorithm improves scalability by spreading load " + "(in particular CPU load) among a number of parallel reducers that can be much larger than the number " + "of solr shards expected by the user. It can be seen as an extension of concurrent lucene merges " + "and tiered lucene merges to the clustered case. The subsequent mapper-only phase " + "merges the output of said large number of reducers to the number of shards expected by the user, " + "again by utilizing more available parallelism on the cluster."); Argument fanoutArg = optionalGroup.addArgument("--fanout") .metavar("INTEGER") .type(Integer.class) .choices(new RangeArgumentChoice(2, Integer.MAX_VALUE)) .setDefault(Integer.MAX_VALUE) .help(FeatureControl.SUPPRESS); Argument maxSegmentsArg = optionalGroup.addArgument("--max-segments") .metavar("INTEGER") .type(Integer.class) .choices(new RangeArgumentChoice(1, Integer.MAX_VALUE)) .setDefault(1) .help("Tuning knob that indicates the maximum number of segments to be contained on output in the index of " + "each reducer shard. After a reducer has built its output index it applies a merge policy to merge segments " + "until there are <= maxSegments lucene segments left in this index. " + "Merging segments involves reading and rewriting all data in all these segment files, " + "potentially multiple times, which is very I/O intensive and time consuming. " + "However, an index with fewer segments can later be merged faster, " + "and it can later be queried faster once deployed to a live Solr serving shard. " + "Set maxSegments to 1 to optimize the index for low query latency. " + "In a nutshell, a small maxSegments value trades indexing latency for subsequently improved query latency. " + "This can be a reasonable trade-off for batch indexing systems."); Argument fairSchedulerPoolArg = optionalGroup.addArgument("--fair-scheduler-pool") .metavar("STRING") .help("Optional tuning knob that indicates the name of the fair scheduler pool to submit jobs to. " + "The Fair Scheduler is a pluggable MapReduce scheduler that provides a way to share large clusters. " + "Fair scheduling is a method of assigning resources to jobs such that all jobs get, on average, an " + "equal share of resources over time. When there is a single job running, that job uses the entire " + "cluster. When other jobs are submitted, tasks slots that free up are assigned to the new jobs, so " + "that each job gets roughly the same amount of CPU time. Unlike the default Hadoop scheduler, which " + "forms a queue of jobs, this lets short jobs finish in reasonable time while not starving long jobs. " + "It is also an easy way to share a cluster between multiple of users. Fair sharing can also work with " + "job priorities - the priorities are used as weights to determine the fraction of total compute time " + "that each job gets."); Argument dryRunArg = optionalGroup.addArgument("--dry-run") .action(Arguments.storeTrue()) .help("Run in local mode and print documents to stdout instead of loading them into Solr. This executes " + "the morphline in the client process (without submitting a job to MR) for quicker turnaround during " + "early trial & debug sessions."); Argument log4jConfigFileArg = optionalGroup.addArgument("--log4j") .metavar("FILE") .type(new FileArgumentType().verifyExists().verifyIsFile().verifyCanRead()) .help("Relative or absolute path to a log4j.properties config file on the local file system. This file " + "will be uploaded to each MR task. Example: /path/to/log4j.properties"); Argument verboseArg = optionalGroup.addArgument("--verbose", "-v") .action(Arguments.storeTrue()) .help("Turn on verbose output."); Argument clearIndexArg = optionalGroup.addArgument("--clear-index") .action(Arguments.storeTrue()) .help("Will attempt to delete all entries in a solr index before starting batch build. This is not " + "transactional so if the build fails the index will be empty."); optionalGroup.addArgument(SHOW_NON_SOLR_CLOUD) .action(Arguments.storeTrue()) .help("Also show options for Non-SolrCloud mode as part of --help."); Namespace ns; try { ns = parser.parseArgs(args); } catch (FoundHelpArgument e) { return 0; } catch (ArgumentParserException e) { parser.handleError(e); return 1; } opts.log4jConfigFile = (File) ns.get(log4jConfigFileArg.getDest()); if (opts.log4jConfigFile != null) { PropertyConfigurator.configure(opts.log4jConfigFile.getPath()); } LOG.debug("Parsed command line args: " + ns); opts.inputLists = Collections.EMPTY_LIST; opts.outputDir = (Path) ns.get(outputDirArg.getDest()); opts.overwriteOutputDir = ns.getBoolean(overwriteOutputDirArg.getDest()); opts.reducers = ns.getInt(reducersArg.getDest()); opts.updateConflictResolver = ns.getString(updateConflictResolverArg.getDest()); opts.fanout = ns.getInt(fanoutArg.getDest()); opts.maxSegments = ns.getInt(maxSegmentsArg.getDest()); opts.morphlineFile = (File) ns.get(morphlineFileArg.getDest()); opts.morphlineId = ns.getString(morphlineIdArg.getDest()); opts.solrHomeDir = (File) ns.get(solrHomeDirArg.getDest()); opts.fairSchedulerPool = ns.getString(fairSchedulerPoolArg.getDest()); opts.isDryRun = ns.getBoolean(dryRunArg.getDest()); opts.isVerbose = ns.getBoolean(verboseArg.getDest()); opts.zkHost = ns.getString(zkHostArg.getDest()); opts.shards = ns.getInt(shardsArg.getDest()); opts.shardUrls = ForkedMapReduceIndexerTool.buildShardUrls(ns.getList(shardUrlsArg.getDest()), opts.shards); opts.goLive = ns.getBoolean(goLiveArg.getDest()); opts.goLiveThreads = ns.getInt(goLiveThreadsArg.getDest()); opts.collection = ns.getString(collectionArg.getDest()); opts.clearIndex = ns.getBoolean(clearIndexArg.getDest()); opts.hbaseIndexerComponentFactory = (String) ns.get(hbaseIndexerComponentFactoryArg.getDest()); opts.hbaseIndexerConfigFile = (File) ns.get(hbaseIndexerConfigArg.getDest()); opts.hbaseIndexerZkHost = ns.getString(indexerZkHostArg.getDest()); opts.hbaseIndexerName = ns.getString(indexNameArg.getDest()); opts.hbaseTableName = ns.getString(hbaseTableNameArg.getDest()); opts.hbaseStartRow = ns.getString(startRowArg.getDest()); opts.hbaseEndRow = ns.getString(endRowArg.getDest()); opts.hbaseStartTimeString = ns.getString(startTimeArg.getDest()); opts.hbaseEndTimeString = ns.getString(endTimeArg.getDest()); opts.hbaseTimestampFormat = ns.getString(timestampFormatArg.getDest()); try { try { opts.evaluate(); } catch (IllegalStateException ise) { throw new ArgumentParserException(ise.getMessage(), parser); } } catch (ArgumentParserException e) { parser.handleError(e); return 1; } return null; }
public void run() { this.eventLogger = getEventLoggerService(); this.eventAdmin = getEventAdminService(); try { kernelStarting(); Bundle[] bundles = this.context.getBundles(); try { long waitTime = TimeUnit.SECONDS.toMillis(this.startupWaitTime); for (Bundle bundle : bundles) { if (!BundleUtils.isFragmentBundle(bundle) && isKernelBundle(bundle)) { BlockingAbortableSignal signal = new BlockingAbortableSignal(); this.asyncBundleStartTracker.trackStart(bundle, signal); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Awaiting startup of bundle {} for up to {} milliseconds with signal {}.", new Object[]{bundle, waitTime, signal}); } long startTime = System.currentTimeMillis(); boolean bundleStarted = signal.awaitCompletion(waitTime, TimeUnit.MILLISECONDS); waitTime -= System.currentTimeMillis() - startTime; if (!bundleStarted) { if(signal.isAborted()){ LOGGER.error("Bundle {} aborted before the Kernel timeout of {} seconds with {} seconds remaining.", bundle, this.startupWaitTime, TimeUnit.MILLISECONDS.toSeconds(waitTime)); kernelStartAborted(bundle); } else if (waitTime <= 0) { LOGGER.error("Kernel has failed to start before the timeout of {} seconds.", this.startupWaitTime); kernelStartTimedOut(); } else { LOGGER.error("Bundle {} did not start within the Kernel timeout of {} seconds.", bundle, this.startupWaitTime); kernelStartTimedOut(); } return; } } } } catch (FailureSignalledException fse) { kernelStartFailed(fse.getCause()); return; } catch (Exception e) { kernelStartFailed(e); return; } kernelStarted(); } finally { this.serviceReferenceTracker.ungetAll(); } }
public void run() { this.eventLogger = getEventLoggerService(); this.eventAdmin = getEventAdminService(); try { kernelStarting(); Bundle[] bundles = this.context.getBundles(); try { long waitTime = TimeUnit.SECONDS.toMillis(this.startupWaitTime); for (Bundle bundle : bundles) { if (!BundleUtils.isFragmentBundle(bundle) && isKernelBundle(bundle)) { BlockingAbortableSignal signal = new BlockingAbortableSignal(); this.asyncBundleStartTracker.trackStart(bundle, signal); LOGGER.debug("Awaiting startup of bundle {} for up to {} milliseconds with signal {}.", new Object[]{bundle, waitTime, signal}); long startTime = System.currentTimeMillis(); boolean bundleStarted = signal.awaitCompletion(waitTime, TimeUnit.MILLISECONDS); waitTime -= System.currentTimeMillis() - startTime; if (!bundleStarted) { if(signal.isAborted()){ LOGGER.error("Bundle {} aborted before the Kernel timeout of {} seconds with {} seconds remaining.", new Object[]{bundle, this.startupWaitTime, TimeUnit.MILLISECONDS.toSeconds(waitTime)}); kernelStartAborted(bundle); } else if (waitTime <= 0) { LOGGER.error("Kernel has failed to start before the timeout of {} seconds.", this.startupWaitTime); kernelStartTimedOut(); } else { LOGGER.error("Bundle {} did not start within the Kernel timeout of {} seconds.", bundle, this.startupWaitTime); kernelStartTimedOut(); } return; } } } } catch (FailureSignalledException fse) { kernelStartFailed(fse.getCause()); return; } catch (Exception e) { kernelStartFailed(e); return; } kernelStarted(); } finally { this.serviceReferenceTracker.ungetAll(); } }
private void initComponents() { jFileChooser1 = new javax.swing.JFileChooser(); jFrame1 = new javax.swing.JFrame(); jLabel1 = new javax.swing.JLabel(); jSplitPane1 = new javax.swing.JSplitPane(); jScrollPane2 = new javax.swing.JScrollPane(); syntaxArea = new javax.swing.JTextArea(); jScrollPane1 = new javax.swing.JScrollPane(); eventArea = new javax.swing.JTextArea(); LoadEvent = new javax.swing.JButton(); LoadSyntax = new javax.swing.JButton(); SaveSyntax = new javax.swing.JButton(); NVariable = new javax.swing.JButton(); NOperation = new javax.swing.JButton(); NDataBase = new javax.swing.JButton(); NTable = new javax.swing.JButton(); deshacer = new javax.swing.JButton(); editar = new javax.swing.JToggleButton(); rehacer = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jFrame1.setBounds(new java.awt.Rectangle(0, 0, 225, 206)); jFrame1.setLocationByPlatform(true); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("<html><img src=\"http://farm4.staticflickr.com/3227/3115937621_650616f2b0.jpg\" width=210 height=180></html>"); javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane()); jFrame1.getContentPane().setLayout(jFrame1Layout); jFrame1Layout.setHorizontalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 15, Short.MAX_VALUE)) ); jFrame1Layout.setVerticalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(38, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("KiwiSyntaxManager"); setFocusCycleRoot(false); setLocationByPlatform(true); jSplitPane1.setResizeWeight(0.5); jScrollPane2.setToolTipText(""); syntaxArea.setColumns(20); syntaxArea.setRows(5); jScrollPane2.setViewportView(syntaxArea); jSplitPane1.setRightComponent(jScrollPane2); eventArea.setColumns(20); eventArea.setRows(5); jScrollPane1.setViewportView(eventArea); jSplitPane1.setLeftComponent(jScrollPane1); LoadEvent.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_lightning.png"))); LoadEvent.setToolTipText("Load Event"); LoadEvent.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LoadEventActionPerformed(evt); } }); LoadSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_put.png"))); LoadSyntax.setToolTipText("Load Syntax"); LoadSyntax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LoadSyntaxActionPerformed(evt); } }); SaveSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/disk.png"))); SaveSyntax.setToolTipText("Save"); SaveSyntax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SaveSyntaxActionPerformed(evt); } }); NVariable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/tag_blue_add.png"))); NVariable.setToolTipText("New Variable"); NVariable.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NVariableActionPerformed(evt); } }); NOperation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/cog_add.png"))); NOperation.setToolTipText("New Operation"); NOperation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NOperationActionPerformed(evt); } }); NDataBase.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/database_add.png"))); NDataBase.setToolTipText("New DataBase"); NDataBase.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NDataBaseActionPerformed(evt); } }); NTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/table_add.png"))); NTable.setToolTipText("New Table"); NTable.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NTableActionPerformed(evt); } }); deshacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_undo.png"))); deshacer.setToolTipText("Undo"); deshacer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { undoActionPerformed(evt); } }); editar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_edit.png"))); editar.setToolTipText("Edit Code"); editar.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_delete.png"))); editar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editarActionPerformed(evt); } }); rehacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_redo.png"))); rehacer.setToolTipText("Redo"); rehacer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { redoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 20, Short.MAX_VALUE) ); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/bug_edit.png"))); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(LoadEvent, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(LoadSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(SaveSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NVariable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NOperation, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NDataBase, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NTable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(editar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(deshacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rehacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 906, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(LoadEvent) .addComponent(SaveSyntax) .addComponent(NVariable) .addComponent(NOperation) .addComponent(NDataBase) .addComponent(NTable) .addComponent(editar) .addComponent(deshacer) .addComponent(rehacer) .addComponent(LoadSyntax) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); deshacer.getAccessibleContext().setAccessibleDescription(""); pack(); }
private void initComponents() { jFileChooser1 = new javax.swing.JFileChooser(); jFrame1 = new javax.swing.JFrame(); jLabel1 = new javax.swing.JLabel(); jSplitPane1 = new javax.swing.JSplitPane(); jScrollPane2 = new javax.swing.JScrollPane(); syntaxArea = new javax.swing.JTextArea(); jScrollPane1 = new javax.swing.JScrollPane(); eventArea = new javax.swing.JTextArea(); LoadEvent = new javax.swing.JButton(); LoadSyntax = new javax.swing.JButton(); SaveSyntax = new javax.swing.JButton(); NVariable = new javax.swing.JButton(); NOperation = new javax.swing.JButton(); NDataBase = new javax.swing.JButton(); NTable = new javax.swing.JButton(); deshacer = new javax.swing.JButton(); editar = new javax.swing.JToggleButton(); rehacer = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jFrame1.setBounds(new java.awt.Rectangle(0, 0, 225, 206)); jFrame1.setLocationByPlatform(true); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("<html><img src=\"http://farm4.staticflickr.com/3227/3115937621_650616f2b0.jpg\" width=210 height=180></html>"); javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane()); jFrame1.getContentPane().setLayout(jFrame1Layout); jFrame1Layout.setHorizontalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 15, Short.MAX_VALUE)) ); jFrame1Layout.setVerticalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(38, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("KiwiSyntaxManager"); setFocusCycleRoot(false); setLocationByPlatform(true); jSplitPane1.setResizeWeight(0.5); jScrollPane2.setToolTipText(""); syntaxArea.setColumns(20); syntaxArea.setRows(5); jScrollPane2.setViewportView(syntaxArea); jSplitPane1.setRightComponent(jScrollPane2); eventArea.setColumns(20); eventArea.setRows(5); jScrollPane1.setViewportView(eventArea); jSplitPane1.setLeftComponent(jScrollPane1); LoadEvent.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_lightning.png"))); LoadEvent.setToolTipText("Load Event"); LoadEvent.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LoadEventActionPerformed(evt); } }); LoadSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_put.png"))); LoadSyntax.setToolTipText("Load Syntax"); LoadSyntax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LoadSyntaxActionPerformed(evt); } }); SaveSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/disk.png"))); SaveSyntax.setToolTipText("Save"); SaveSyntax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SaveSyntaxActionPerformed(evt); } }); NVariable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/tag_blue_add.png"))); NVariable.setToolTipText("New Variable"); NVariable.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NVariableActionPerformed(evt); } }); NOperation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/cog_add.png"))); NOperation.setToolTipText("New Operation"); NOperation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NOperationActionPerformed(evt); } }); NDataBase.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/database_add.png"))); NDataBase.setToolTipText("New DataBase"); NDataBase.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NDataBaseActionPerformed(evt); } }); NTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/table_add.png"))); NTable.setToolTipText("New Table"); NTable.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NTableActionPerformed(evt); } }); deshacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_undo.png"))); deshacer.setToolTipText("Undo"); deshacer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { undoActionPerformed(evt); } }); editar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_edit.png"))); editar.setToolTipText("Edit Code"); editar.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_delete.png"))); editar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editarActionPerformed(evt); } }); rehacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_redo.png"))); rehacer.setToolTipText("Redo"); rehacer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { redoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 20, Short.MAX_VALUE) ); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/bug_edit.png"))); jButton1.setToolTipText("Failure manager"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(LoadEvent, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(LoadSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(SaveSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NVariable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NOperation, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NDataBase, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NTable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(editar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(deshacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rehacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 906, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(LoadEvent) .addComponent(SaveSyntax) .addComponent(NVariable) .addComponent(NOperation) .addComponent(NDataBase) .addComponent(NTable) .addComponent(editar) .addComponent(deshacer) .addComponent(rehacer) .addComponent(LoadSyntax) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); deshacer.getAccessibleContext().setAccessibleDescription(""); pack(); }
public void send(int index, Object o) { Reaction selectedReaction = null; Object[] args = null; synchronized (this) { final LinkedList writing = writes[index]; if ( writing == null ) { throw new IndexOutOfBoundsException(); } writing.addLast(o); mask |= 1L << index; for (Reaction reaction: reactions) { if ( ( reaction.mask & mask ) == reaction.mask ) { selectedReaction = reaction; final int[] indices = reaction.indices; args = new Object[indices.length]; for ( int i = 0 ; i < indices.length ; ++i ) { final LinkedList reading = writes[indices[i]]; args[i] = reading.removeFirst(); if (reading.isEmpty()) { mask &= ~(1L << i); } } break; } } } if ( selectedReaction != null ) { selectedReaction.react(this, args); } }
public void send(int index, Object o) { Reaction selectedReaction = null; Object[] args = null; synchronized (this) { final LinkedList writing = writes[index]; if ( writing == null ) { throw new IndexOutOfBoundsException(); } writing.addLast(o); mask |= 1L << index; for (Reaction reaction: reactions) { if ( ( reaction.mask & mask ) == reaction.mask ) { selectedReaction = reaction; final int[] indices = reaction.indices; args = new Object[indices.length]; for ( int i = 0 ; i < indices.length ; ++i ) { final int readIndex = indices[i]; final LinkedList reading = writes[readIndex]; args[i] = reading.removeFirst(); if (reading.isEmpty()) { mask &= ~(1L << readIndex); } } break; } } } if ( selectedReaction != null ) { selectedReaction.react(this, args); } }
public SyntaxHighlightResult getTokenInformation(String text, int offset) { Preconditions.checkNotNull(text); Preconditions.checkArgument(offset >= 0); List<String> lines = Lists.newArrayList(text.split("\n")); int[] lineSpacing = new int[lines.size()]; for (int i = 0; i < lines.size(); i++) { if (lines.get(i).endsWith("\r")) { lineSpacing[i] = 2; } else { lineSpacing[i] = 1; } } int beginningLexState = START; List<ClassificationInfo> entries = Lists.newArrayList(); List<Integer> offsets = Lists.newArrayList(); List<String> firstLines; Class<ClassificationResults> resultType = ClassificationResults.class; int lineBunchSize = 100; while (lines.size() > 0) { if (lines.size() > lineBunchSize) { firstLines = lines.subList(0, lineBunchSize); lines = lines.subList(lineBunchSize, lines.size()); } else { firstLines = lines; lines = lines.subList(lines.size(), lines.size()); } GetClassificationsForLinesRequest request = new GetClassificationsForLinesRequest(firstLines, beginningLexState); ClassificationResults classificationResults = this.typeScriptBridge.sendRequest(request, resultType); int lineNumber = 0; for (ClassificationResult classificationResult : classificationResults.getResults()) { for (ClassificationInfo entry : classificationResult.getEntries()) { offsets.add(offset); entries.add(entry); offset += entry.getLength(); } offset += lineSpacing[lineNumber]; lineNumber++; } beginningLexState = classificationResults.getFinalLexState(); } return new SyntaxHighlightResult(entries, offsets); }
public SyntaxHighlightResult getTokenInformation(String text, int offset) { Preconditions.checkNotNull(text); Preconditions.checkArgument(offset >= 0); List<String> lines = Lists.newArrayList(text.split("\n")); int[] lineSpacing = new int[lines.size()]; for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (line.endsWith("\r")) { line = line.substring(0, line.length() - 1); lines.set(i, line); lineSpacing[i] = 2; } else { lineSpacing[i] = 1; } } int beginningLexState = START; List<ClassificationInfo> entries = Lists.newArrayList(); List<Integer> offsets = Lists.newArrayList(); List<String> firstLines; Class<ClassificationResults> resultType = ClassificationResults.class; int lineBunchSize = 100; int lineNumber = 0; while (lines.size() > 0) { if (lines.size() > lineBunchSize) { firstLines = lines.subList(0, lineBunchSize); lines = lines.subList(lineBunchSize, lines.size()); } else { firstLines = lines; lines = lines.subList(lines.size(), lines.size()); } GetClassificationsForLinesRequest request = new GetClassificationsForLinesRequest(firstLines, beginningLexState); ClassificationResults classificationResults = this.typeScriptBridge.sendRequest(request, resultType); for (ClassificationResult classificationResult : classificationResults.getResults()) { for (ClassificationInfo entry : classificationResult.getEntries()) { offsets.add(offset); entries.add(entry); offset += entry.getLength(); } offset += lineSpacing[lineNumber]; lineNumber++; } beginningLexState = classificationResults.getFinalLexState(); } return new SyntaxHighlightResult(entries, offsets); }
public ResponseEntity<?> query( ServletServerHttpRequest request, PagingAndSorting pageSort, UriComponentsBuilder uriBuilder, @PathVariable String repository, @PathVariable String query ) throws InvocationTargetException, IllegalAccessException, IOException { URI baseUri = uriBuilder.build().toUri(); Page page = null; RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Repository repo = repoMeta.repository(); RepositoryQueryMethod queryMethod = repoMeta.queryMethod( query ); if ( null == queryMethod ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } Class<?>[] paramTypes = queryMethod.paramTypes(); String[] paramNames = queryMethod.paramNames(); Object[] paramVals = new Object[paramTypes.length]; for ( int i = 0; i < paramVals.length; i++ ) { String queryVal = request.getServletRequest().getParameter( paramNames[i] ); if ( String.class.isAssignableFrom( paramTypes[i] ) ) { paramVals[i] = queryVal; } else if ( Pageable.class.isAssignableFrom( paramTypes[i] ) ) { paramVals[i] = pageSort; } else if ( Sort.class.isAssignableFrom( paramTypes[i] ) ) { paramVals[i] = (null != pageSort ? pageSort.getSort() : null); } else if ( conversionService.canConvert( String.class, paramTypes[i] ) ) { paramVals[i] = conversionService.convert( queryVal, paramTypes[i] ); } else { try { paramVals[i] = objectMapper.readValue( queryVal, paramTypes[i] ); } catch ( IOException e ) { throw new IllegalArgumentException( e ); } } } Object result = queryMethod.method().invoke( repo, paramVals ); Iterator iter; if ( result instanceof Collection ) { iter = ((Collection) result).iterator(); } else if ( result instanceof Page ) { page = (Page) result; iter = page.iterator(); } else { List l = new ArrayList(); l.add( result ); iter = l.iterator(); } Map<String, Object> resultMap = new HashMap<String, Object>(); Links links = new Links(); resultMap.put( LINKS, links.getLinks() ); List resultList = new ArrayList(); resultMap.put( "results", resultList ); boolean returnLinks = shouldReturnLinks( request.getServletRequest().getHeader( "Accept" ) ); while ( iter.hasNext() ) { Object obj = iter.next(); RepositoryMetadata elemRepoMeta = repositoryMetadataFor( obj.getClass() ); if ( null != elemRepoMeta ) { String id = elemRepoMeta.entityMetadata().idAttribute().get( obj ).toString(); if ( returnLinks ) { String rel = elemRepoMeta.rel() + "." + elemRepoMeta.entityMetadata().type().getSimpleName(); URI path = buildUri( baseUri, repository, id ); links.add( new SimpleLink( rel, path ) ); } else { Map<String, Object> entityDto = extractPropertiesLinkAware( repoMeta.rel(), obj, repoMeta.entityMetadata(), buildUri( baseUri, repository, id ) ); addSelfLink( baseUri, entityDto, repository, id ); resultList.add( entityDto ); } } } if ( null != page ) { resultMap.put( "totalCount", page.getTotalElements() ); resultMap.put( "totalPages", page.getTotalPages() ); resultMap.put( "currentPage", page.getNumber() + 1 ); UriComponentsBuilder urib = UriComponentsBuilder.fromUri( baseUri ).pathSegment( repository, "search", query ); for ( String name : ((Map<String, Object>) request.getServletRequest().getParameterMap()).keySet() ) { if ( !config.getPageParamName().equals( name ) && !config.getLimitParamName().equals( name ) && !config.getSortParamName().equals( name ) ) { urib.queryParam( name, request.getServletRequest().getParameter( name ) ); } } URI nextPrevBase = urib.build().toUri(); maybeAddPrevNextLink( nextPrevBase, repoMeta, pageSort, page, !page.isFirstPage() && page.hasPreviousPage(), page.getNumber(), "prev", links ); maybeAddPrevNextLink( nextPrevBase, repoMeta, pageSort, page, !page.isLastPage() && page.hasNextPage(), page.getNumber() + 2, "next", links ); } else { resultMap.put( "totalCount", resultList.size() ); } return negotiateResponse( request, HttpStatus.OK, EMPTY_HEADERS, resultMap ); }
public ResponseEntity<?> query( ServletServerHttpRequest request, PagingAndSorting pageSort, UriComponentsBuilder uriBuilder, @PathVariable String repository, @PathVariable String query ) throws InvocationTargetException, IllegalAccessException, IOException { URI baseUri = uriBuilder.build().toUri(); Page page = null; RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Repository repo = repoMeta.repository(); RepositoryQueryMethod queryMethod = repoMeta.queryMethod( query ); if ( null == queryMethod ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } Class<?>[] paramTypes = queryMethod.paramTypes(); String[] paramNames = queryMethod.paramNames(); Object[] paramVals = new Object[paramTypes.length]; for ( int i = 0; i < paramVals.length; i++ ) { String queryVal = request.getServletRequest().getParameter( paramNames[i] ); if ( String.class.isAssignableFrom( paramTypes[i] ) ) { paramVals[i] = queryVal; } else if ( Pageable.class.isAssignableFrom( paramTypes[i] ) ) { paramVals[i] = pageSort; } else if ( Sort.class.isAssignableFrom( paramTypes[i] ) ) { paramVals[i] = (null != pageSort ? pageSort.getSort() : null); } else if ( conversionService.canConvert( String.class, paramTypes[i] ) ) { paramVals[i] = conversionService.convert( queryVal, paramTypes[i] ); } else { try { paramVals[i] = objectMapper.readValue( queryVal, paramTypes[i] ); } catch ( IOException e ) { throw new IllegalArgumentException( e ); } } } Object result = queryMethod.method().invoke( repo, paramVals ); Iterator iter; if ( null != result ) { if ( result instanceof Collection ) { iter = ((Collection) result).iterator(); } else if ( result instanceof Page ) { page = (Page) result; iter = page.iterator(); } else { List l = new ArrayList(); l.add( result ); iter = l.iterator(); } } else { iter = Collections.emptyList().iterator(); } Map<String, Object> resultMap = new HashMap<String, Object>(); Links links = new Links(); resultMap.put( LINKS, links.getLinks() ); List resultList = new ArrayList(); resultMap.put( "results", resultList ); boolean returnLinks = shouldReturnLinks( request.getServletRequest().getHeader( "Accept" ) ); while ( iter.hasNext() ) { Object obj = iter.next(); RepositoryMetadata elemRepoMeta = repositoryMetadataFor( obj.getClass() ); if ( null != elemRepoMeta ) { String id = elemRepoMeta.entityMetadata().idAttribute().get( obj ).toString(); if ( returnLinks ) { String rel = elemRepoMeta.rel() + "." + elemRepoMeta.entityMetadata().type().getSimpleName(); URI path = buildUri( baseUri, repository, id ); links.add( new SimpleLink( rel, path ) ); } else { Map<String, Object> entityDto = extractPropertiesLinkAware( repoMeta.rel(), obj, repoMeta.entityMetadata(), buildUri( baseUri, repository, id ) ); addSelfLink( baseUri, entityDto, repository, id ); resultList.add( entityDto ); } } } if ( null != page ) { resultMap.put( "totalCount", page.getTotalElements() ); resultMap.put( "totalPages", page.getTotalPages() ); resultMap.put( "currentPage", page.getNumber() + 1 ); UriComponentsBuilder urib = UriComponentsBuilder.fromUri( baseUri ).pathSegment( repository, "search", query ); for ( String name : ((Map<String, Object>) request.getServletRequest().getParameterMap()).keySet() ) { if ( !config.getPageParamName().equals( name ) && !config.getLimitParamName().equals( name ) && !config.getSortParamName().equals( name ) ) { urib.queryParam( name, request.getServletRequest().getParameter( name ) ); } } URI nextPrevBase = urib.build().toUri(); maybeAddPrevNextLink( nextPrevBase, repoMeta, pageSort, page, !page.isFirstPage() && page.hasPreviousPage(), page.getNumber(), "prev", links ); maybeAddPrevNextLink( nextPrevBase, repoMeta, pageSort, page, !page.isLastPage() && page.hasNextPage(), page.getNumber() + 2, "next", links ); } else { resultMap.put( "totalCount", resultList.size() ); } return negotiateResponse( request, HttpStatus.OK, EMPTY_HEADERS, resultMap ); }
public void step() { cobweb.Agent adjAgent; mustFlip = getPosition().checkFlip(facing); cobweb.Environment.Location destPos = getPosition().getAdjacent(facing); if (canStep(destPos)) { cobweb.Environment.Location breedPos = null; if (destPos.testFlag(ComplexEnvironment.FLAG_FOOD)) { if (params.broadcastMode & canBroadcast()) { broadcastFood(destPos); } if (canEat(destPos)) { eat(destPos); } if (pregnant && energy >= params.breedEnergy && pregPeriod <= 0) { breedPos = getPosition(); energy -= params.initEnergy; energy -= energyPenalty(true); wasteCounterLoss -= params.initEnergy; info.useOthers(params.initEnergy); } else { if (!pregnant) tryAsexBreed(); } } for (StepMutator m : stepMutators) m.onStep(this, getPosition(), destPos); move(destPos); if (breedPos != null) { if (breedPartner == null) { info.addDirectChild(); new ComplexAgent(breedPos, this, this.pdCheater); } else { int childStrategy = -1; if (this.pdCheater != -1) { boolean choose = cobweb.globals.random.nextBoolean(); if (choose) { childStrategy = this.pdCheater; } else { childStrategy = breedPartner.pdCheater; } } info.addDirectChild(); breedPartner.info.addDirectChild(); new ComplexAgent(breedPos, this, breedPartner, childStrategy); info.addSexPreg(); } breedPartner = null; pregnant = false; } energy -= params.stepEnergy; wasteCounterLoss -= params.stepEnergy; info.useStepEnergy(params.stepEnergy); info.addStep(); info.addPathStep(this.getPosition()); } else if ((adjAgent = getAdjacentAgent()) != null && adjAgent instanceof ComplexAgent && ((ComplexAgent) adjAgent).info != null) { ComplexAgent adjacentAgent = (ComplexAgent) adjAgent; for (ContactMutator mut : contactMutators) { mut.onContact(this, adjacentAgent); } if (canEat(adjacentAgent)) { eat(adjacentAgent); } if (this.pdCheater != -1) { want2meet = true; } int othersID = adjacentAgent.info.getAgentNumber(); for (int i = 0; i < params.pdMemory; i++) { if (photo_memory[i] == othersID) { want2meet = false; } } if (adjacentAgent.agentType == agentType) { double sim = 0.0; boolean canBreed = !pregnant && energy >= params.breedEnergy && params.sexualBreedChance != 0.0 && cobweb.globals.random.nextFloat() < params.sexualBreedChance; sim = simCalc.similarity(this, adjacentAgent); if (sim >= params.commSimMin) { communicate(adjacentAgent); } if (canBreed && sim >= params.breedSimMin && ((want2meet && adjacentAgent.want2meet) || (pdCheater == -1))) { pregnant = true; pregPeriod = params.sexualPregnancyPeriod; breedPartner = adjacentAgent; } } if (!pregnant && want2meet && adjacentAgent.want2meet) { playPDonStep(adjacentAgent, othersID); } energy -= params.stepAgentEnergy; wasteCounterLoss -= params.stepAgentEnergy; info.useAgentBumpEnergy(params.stepAgentEnergy); info.addAgentBump(); } else if (destPos != null && destPos.testFlag(ComplexEnvironment.FLAG_WASTE)) { energy -= params.wastePen; wasteCounterLoss -= params.wastePen; info.useRockBumpEnergy(params.wastePen); info.addRockBump(); } else { energy -= params.stepRockEnergy; wasteCounterLoss -= params.stepRockEnergy; info.useRockBumpEnergy(params.stepRockEnergy); info.addRockBump(); } energy -= energyPenalty(true); if (energy <= 0) die(); if (energy < params.breedEnergy) { pregnant = false; breedPartner = null; } if (pregnant) { pregPeriod--; } }
public void step() { cobweb.Agent adjAgent; mustFlip = getPosition().checkFlip(facing); cobweb.Environment.Location destPos = getPosition().getAdjacent(facing); if (canStep(destPos)) { cobweb.Environment.Location breedPos = null; if (destPos.testFlag(ComplexEnvironment.FLAG_FOOD)) { if (params.broadcastMode & canBroadcast()) { broadcastFood(destPos); } if (canEat(destPos)) { eat(destPos); } if (pregnant && energy >= params.breedEnergy && pregPeriod <= 0) { breedPos = getPosition(); energy -= params.initEnergy; energy -= energyPenalty(true); wasteCounterLoss -= params.initEnergy; info.useOthers(params.initEnergy); } else { if (!pregnant) tryAsexBreed(); } } for (StepMutator m : stepMutators) m.onStep(this, getPosition(), destPos); move(destPos); if (breedPos != null) { if (breedPartner == null) { info.addDirectChild(); new ComplexAgent(breedPos, this, this.pdCheater); } else { int childStrategy = -1; if (this.pdCheater != -1) { boolean choose = cobweb.globals.random.nextBoolean(); if (choose) { childStrategy = this.pdCheater; } else { childStrategy = breedPartner.pdCheater; } } info.addDirectChild(); breedPartner.info.addDirectChild(); new ComplexAgent(breedPos, this, breedPartner, childStrategy); info.addSexPreg(); } breedPartner = null; pregnant = false; } energy -= params.stepEnergy; wasteCounterLoss -= params.stepEnergy; info.useStepEnergy(params.stepEnergy); info.addStep(); } else if ((adjAgent = getAdjacentAgent()) != null && adjAgent instanceof ComplexAgent && ((ComplexAgent) adjAgent).info != null) { ComplexAgent adjacentAgent = (ComplexAgent) adjAgent; for (ContactMutator mut : contactMutators) { mut.onContact(this, adjacentAgent); } if (canEat(adjacentAgent)) { eat(adjacentAgent); } if (this.pdCheater != -1) { want2meet = true; } int othersID = adjacentAgent.info.getAgentNumber(); for (int i = 0; i < params.pdMemory; i++) { if (photo_memory[i] == othersID) { want2meet = false; } } if (adjacentAgent.agentType == agentType) { double sim = 0.0; boolean canBreed = !pregnant && energy >= params.breedEnergy && params.sexualBreedChance != 0.0 && cobweb.globals.random.nextFloat() < params.sexualBreedChance; sim = simCalc.similarity(this, adjacentAgent); if (sim >= params.commSimMin) { communicate(adjacentAgent); } if (canBreed && sim >= params.breedSimMin && ((want2meet && adjacentAgent.want2meet) || (pdCheater == -1))) { pregnant = true; pregPeriod = params.sexualPregnancyPeriod; breedPartner = adjacentAgent; } } if (!pregnant && want2meet && adjacentAgent.want2meet) { playPDonStep(adjacentAgent, othersID); } energy -= params.stepAgentEnergy; wasteCounterLoss -= params.stepAgentEnergy; info.useAgentBumpEnergy(params.stepAgentEnergy); info.addAgentBump(); } else if (destPos != null && destPos.testFlag(ComplexEnvironment.FLAG_WASTE)) { energy -= params.wastePen; wasteCounterLoss -= params.wastePen; info.useRockBumpEnergy(params.wastePen); info.addRockBump(); } else { energy -= params.stepRockEnergy; wasteCounterLoss -= params.stepRockEnergy; info.useRockBumpEnergy(params.stepRockEnergy); info.addRockBump(); } energy -= energyPenalty(true); if (energy <= 0) die(); if (energy < params.breedEnergy) { pregnant = false; breedPartner = null; } if (pregnant) { pregPeriod--; } }
private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType, boolean reportProblems) { ResolvedType rtx = factory.fromEclipse(sourceType); if (!decA.matches(rtx)) { return false; } if (!rtx.isExposedToWeaver()) { return false; } ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS, sourceType.sourceName); UnresolvedType aspectType = decA.getAspect(); if (aspectType instanceof ReferenceType) { ReferenceType rt = (ReferenceType) aspectType; if (rt.isParameterizedType() || rt.isRawType()) { aspectType = rt.getGenericType(); } } TypeBinding tb = factory.makeTypeBinding(aspectType); SourceTypeBinding stb = (SourceTypeBinding) tb; Annotation[] toAdd = null; long abits = 0; if (stb instanceof BinaryTypeBinding) { ReferenceType rt = (ReferenceType) factory.fromEclipse(stb); ResolvedMember[] methods = rt.getDeclaredMethods(); ResolvedMember decaMethod = null; String nameToLookFor = decA.getAnnotationMethod(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals(nameToLookFor)) { decaMethod = methods[i]; break; } } if (decaMethod != null) { AnnotationAJ[] axs = decaMethod.getAnnotations(); if (axs != null) { toAdd = new Annotation[1]; toAdd[0] = createAnnotationFromBcelAnnotation(axs[0], decaMethod.getSourceLocation().getOffset(), factory); if (toAdd[0].resolvedType != null) { abits = toAdd[0].resolvedType.getAnnotationTagBits(); } } } } else if (stb != null) { MethodBinding[] mbs = stb.getMethods(decA.getAnnotationMethod().toCharArray()); abits = mbs[0].getAnnotationTagBits(); TypeDeclaration typeDecl = ((SourceTypeBinding) mbs[0].declaringClass).scope.referenceContext; AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(mbs[0]); toAdd = methodDecl.annotations; toAdd[0] = createAnnotationCopy(toAdd[0]); if (toAdd[0].resolvedType != null) { abits = toAdd[0].resolvedType.getAnnotationTagBits(); } } if (toAdd == null || toAdd[0] == null || toAdd[0].type == null) { CompilationAndWeavingContext.leavingPhase(tok); return false; } if (sourceType instanceof BinaryTypeBinding) { ResolvedType theTargetType = factory.fromEclipse(sourceType); TypeBinding theAnnotationType = toAdd[0].resolvedType; String sig = new String(theAnnotationType.signature()); UnresolvedType bcelAnnotationType = UnresolvedType.forSignature(sig); String name = bcelAnnotationType.getName(); if (theTargetType.hasAnnotation(bcelAnnotationType)) { CompilationAndWeavingContext.leavingPhase(tok); return false; } boolean giveupnow = false; if (((abits & TagBits.AnnotationTargetMASK) != 0)) { if (isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(abits)) { giveupnow = true; } else if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0) || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) { if (reportProblems) { if (decA.isExactPattern()) { factory.showMessage(IMessage.ERROR, WeaverMessages.format( WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type, stringifyTargets(abits)), decA.getSourceLocation(), null); } } giveupnow = true; } } if (giveupnow) { CompilationAndWeavingContext.leavingPhase(tok); return false; } theTargetType.addAnnotation(new BcelAnnotation(new FakeAnnotation(name, sig, (abits & TagBits.AnnotationRuntimeRetention) != 0), factory.getWorld())); CompilationAndWeavingContext.leavingPhase(tok); return true; } Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations; if (currentAnnotations != null) { for (int i = 0; i < currentAnnotations.length; i++) { Annotation annotation = currentAnnotations[i]; String a = CharOperation.toString(annotation.type.getTypeName()); String b = CharOperation.toString(toAdd[0].type.getTypeName()); if (a.equals(b)) { CompilationAndWeavingContext.leavingPhase(tok); return false; } } } if (((abits & TagBits.AnnotationTargetMASK) != 0)) { if ((abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0) { CompilationAndWeavingContext.leavingPhase(tok); return false; } if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0) || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) { if (reportProblems) { if (decA.isExactPattern()) { factory.showMessage(IMessage.ERROR, WeaverMessages.format( WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type, stringifyTargets(abits)), decA.getSourceLocation(), null); } } CompilationAndWeavingContext.leavingPhase(tok); return false; } } sourceType.scope.referenceContext.rememberAnnotations(); Annotation abefore[] = sourceType.scope.referenceContext.annotations; Annotation[] newset = new Annotation[toAdd.length + (abefore == null ? 0 : abefore.length)]; System.arraycopy(toAdd, 0, newset, 0, toAdd.length); if (abefore != null) { System.arraycopy(abefore, 0, newset, toAdd.length, abefore.length); } sourceType.scope.referenceContext.annotations = newset; CompilationAndWeavingContext.leavingPhase(tok); return true; }
private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType, boolean reportProblems) { ResolvedType rtx = factory.fromEclipse(sourceType); if (!decA.matches(rtx)) { return false; } if (!rtx.isExposedToWeaver()) { return false; } ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS, sourceType.sourceName); UnresolvedType aspectType = decA.getAspect(); if (aspectType instanceof ReferenceType) { ReferenceType rt = (ReferenceType) aspectType; if (rt.isParameterizedType() || rt.isRawType()) { aspectType = rt.getGenericType(); } } TypeBinding tb = factory.makeTypeBinding(aspectType); SourceTypeBinding stb = (SourceTypeBinding) tb; Annotation[] toAdd = null; long abits = 0; if (stb instanceof BinaryTypeBinding) { ReferenceType rt = (ReferenceType) factory.fromEclipse(stb); ResolvedMember[] methods = rt.getDeclaredMethods(); ResolvedMember decaMethod = null; String nameToLookFor = decA.getAnnotationMethod(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals(nameToLookFor)) { decaMethod = methods[i]; break; } } if (decaMethod != null) { AnnotationAJ[] axs = decaMethod.getAnnotations(); if (axs != null) { toAdd = new Annotation[1]; toAdd[0] = createAnnotationFromBcelAnnotation(axs[0], decaMethod.getSourceLocation().getOffset(), factory); if (toAdd[0].resolvedType != null) { abits = toAdd[0].resolvedType.getAnnotationTagBits(); } } } } else if (stb != null) { MethodBinding[] mbs = stb.getMethods(decA.getAnnotationMethod().toCharArray()); abits = mbs[0].getAnnotationTagBits(); TypeDeclaration typeDecl = ((SourceTypeBinding) mbs[0].declaringClass).scope.referenceContext; AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(mbs[0]); toAdd = methodDecl.annotations; toAdd[0] = createAnnotationCopy(toAdd[0]); if (toAdd[0].resolvedType != null) { abits = toAdd[0].resolvedType.getAnnotationTagBits(); } } if (toAdd == null || toAdd[0] == null || toAdd[0].type == null) { CompilationAndWeavingContext.leavingPhase(tok); return false; } if (sourceType instanceof BinaryTypeBinding) { ResolvedType theTargetType = factory.fromEclipse(sourceType); TypeBinding theAnnotationType = toAdd[0].resolvedType; if (theAnnotationType == null) { return false; } String sig = new String(theAnnotationType.signature()); UnresolvedType bcelAnnotationType = UnresolvedType.forSignature(sig); String name = bcelAnnotationType.getName(); if (theTargetType.hasAnnotation(bcelAnnotationType)) { CompilationAndWeavingContext.leavingPhase(tok); return false; } boolean giveupnow = false; if (((abits & TagBits.AnnotationTargetMASK) != 0)) { if (isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(abits)) { giveupnow = true; } else if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0) || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) { if (reportProblems) { if (decA.isExactPattern()) { factory.showMessage(IMessage.ERROR, WeaverMessages.format( WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type, stringifyTargets(abits)), decA.getSourceLocation(), null); } } giveupnow = true; } } if (giveupnow) { CompilationAndWeavingContext.leavingPhase(tok); return false; } theTargetType.addAnnotation(new BcelAnnotation(new FakeAnnotation(name, sig, (abits & TagBits.AnnotationRuntimeRetention) != 0), factory.getWorld())); CompilationAndWeavingContext.leavingPhase(tok); return true; } Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations; if (currentAnnotations != null) { for (int i = 0; i < currentAnnotations.length; i++) { Annotation annotation = currentAnnotations[i]; String a = CharOperation.toString(annotation.type.getTypeName()); String b = CharOperation.toString(toAdd[0].type.getTypeName()); if (a.equals(b)) { CompilationAndWeavingContext.leavingPhase(tok); return false; } } } if (((abits & TagBits.AnnotationTargetMASK) != 0)) { if ((abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0) { CompilationAndWeavingContext.leavingPhase(tok); return false; } if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0) || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) { if (reportProblems) { if (decA.isExactPattern()) { factory.showMessage(IMessage.ERROR, WeaverMessages.format( WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type, stringifyTargets(abits)), decA.getSourceLocation(), null); } } CompilationAndWeavingContext.leavingPhase(tok); return false; } } sourceType.scope.referenceContext.rememberAnnotations(); Annotation abefore[] = sourceType.scope.referenceContext.annotations; Annotation[] newset = new Annotation[toAdd.length + (abefore == null ? 0 : abefore.length)]; System.arraycopy(toAdd, 0, newset, 0, toAdd.length); if (abefore != null) { System.arraycopy(abefore, 0, newset, toAdd.length, abefore.length); } sourceType.scope.referenceContext.annotations = newset; CompilationAndWeavingContext.leavingPhase(tok); return true; }
public Document convert() { Document d = new Document(super.convert()); d.setAttachmentNodeId(getAttachmentNodeId()); d.setRenditionIds(getRenditionIds()); d.setLatestVersion(isLatestVersion()); d.setMajorVersion(isMajorVersion()); d.setLatestMajorVersion(isLatestMajorVersion()); d.setVersionSeriesId(getVersionSeriesId()); d.setVersionLabel(getVersionLabel()); d.setPrivateWorkingCopy(isPrivateWorkingCopy()); d.setImmutable(isImmutable()); return d; }
public Document convert() { Document d = new Document(super.convert()); d.setAttachmentNodeId(getAttachmentNodeId()); d.setRenditionIds(getRenditionIds()); d.setLatestVersion(isLatestVersion()); d.setMajorVersion(isMajorVersion()); d.setLatestMajorVersion(isLatestMajorVersion()); d.setVersionSeriesId(getVersionSeriesId()); d.setVersionLabel(getVersionLabel()); d.setPrivateWorkingCopy(isPrivateWorkingCopy()); d.setCheckinComment(getCheckinComment()); d.setImmutable(isImmutable()); return d; }
public Object call(lure.lang.List args) { java.util.ArrayList a = args.getArrayList(); int total = 0; for (int i = 0; i < a.size(); i++) { total *= ((Integer)a.get(i)); } return total; }
public Object call(Object args) { java.util.ArrayList a = ((lure.lang.List)args).getArrayList(); int total = 0; for (int i = 0; i < a.size(); i++) { total += ((Integer)a.get(i)); } return total; }
protected void drawForeground(final EventDraw event) { final ViewState viewState = event.viewState; Page page = viewState.model.getPageObject(bFlipRight ? foreIndex : backIndex); if (page == null) { page = viewState.model.getCurrentPageObject(); } if (page != null) { updateForeBitmap(event, page); final Rect src = new Rect(0, 0, (int) viewState.viewRect.width(), (int) viewState.viewRect.height()); final RectF dst = new RectF(0, 0, viewState.viewRect.width(), viewState.viewRect.height()); event.canvas.drawBitmap(foreBitmap.getBitmap(), src, dst, PAINT); } }
protected void drawForeground(final EventDraw event) { final ViewState viewState = event.viewState; Page page = null; if (bFlipping) { page = viewState.model.getPageObject(bFlipRight ? foreIndex : backIndex); } if (page == null) { page = viewState.model.getCurrentPageObject(); } if (page != null) { updateForeBitmap(event, page); final Rect src = new Rect(0, 0, (int) viewState.viewRect.width(), (int) viewState.viewRect.height()); final RectF dst = new RectF(0, 0, viewState.viewRect.width(), viewState.viewRect.height()); event.canvas.drawBitmap(foreBitmap.getBitmap(), src, dst, PAINT); } }
public void digeste(InputStream inputStream) throws Exception { Digester digester = new Digester(); digester.push(this); digester.addSetProperties("mashup"); digester.addObjectCreate("mashup/cookiestore", CookieStore.class); digester.addSetProperties("mashup/cookiestore"); digester.addSetNext("mashup/cookiestore", "setCookieStore"); digester.addObjectCreate("mashup/proxy", Proxy.class); digester.addSetProperties("mashup/proxy"); digester.addSetNext("mashup/proxy", "setProxy"); digester.addObjectCreate("mashup/page", Page.class); digester.addSetProperties("mashup/page"); digester.addCallMethod("mashup/page/url", "setUrl", 0); digester.addSetNext("mashup/page", "addPage"); digester.addObjectCreate("mashup/page/param", Param.class); digester.addSetProperties("mashup/page/param"); digester.addSetNext("mashup/page/param", "addParam"); digester.addObjectCreate("mashup/page/extractor", Extractor.class); digester.addSetProperties("mashup/page/extractor"); digester.addSetNext("mashup/page/extractor", "addExtractor"); digester.addObjectCreate("mashup/page/extractor/property", Property.class); digester.addSetProperties("mashup/page/extractor/property"); digester.addCallMethod("mashup/page/extractor/property", "setValue", 0); digester.addSetNext("mashup/page/extractor/property", "addProperty"); digester.addObjectCreate("mashup/page/errorhandler", ErrorHandler.class); digester.addSetProperties("mashup/page/errorhandler"); digester.addSetNext("mashup/page/errorhandler", "setErrorHandler"); digester.addObjectCreate("mashup/page/errorhandler/extractor", Extractor.class); digester.addSetProperties("mashup/page/errorhandler/extractor"); digester.addSetNext("mashup/page/errorhandler/extractor", "addExtractor"); digester.addObjectCreate("mashup/page/errorhandler/extractor/property", Property.class); digester.addSetProperties("mashup/page/errorhandler/extractor/property"); digester.addCallMethod("mashup/page/extractor/property", "setValue", 0); digester.addSetNext("mashup/page/errorhandler/extractor/property", "addProperty"); digester.parse(inputStream); }
public void digeste(InputStream inputStream) throws Exception { Digester digester = new Digester(); digester.push(this); digester.addSetProperties("mashup"); digester.addObjectCreate("mashup/cookiestore", CookieStore.class); digester.addSetProperties("mashup/cookiestore"); digester.addSetNext("mashup/cookiestore", "setCookieStore"); digester.addObjectCreate("mashup/proxy", Proxy.class); digester.addSetProperties("mashup/proxy"); digester.addSetNext("mashup/proxy", "setProxy"); digester.addObjectCreate("mashup/page", Page.class); digester.addSetProperties("mashup/page"); digester.addCallMethod("mashup/page/url", "setUrl", 0); digester.addSetNext("mashup/page", "addPage"); digester.addObjectCreate("mashup/page/param", Param.class); digester.addSetProperties("mashup/page/param"); digester.addSetNext("mashup/page/param", "addParam"); digester.addObjectCreate("mashup/page/extractor", Extractor.class); digester.addSetProperties("mashup/page/extractor"); digester.addSetNext("mashup/page/extractor", "addExtractor"); digester.addObjectCreate("mashup/page/extractor/property", Property.class); digester.addSetProperties("mashup/page/extractor/property"); digester.addCallMethod("mashup/page/extractor/property", "setValue", 0); digester.addSetNext("mashup/page/extractor/property", "addProperty"); digester.addObjectCreate("mashup/page/errorhandler", ErrorHandler.class); digester.addSetProperties("mashup/page/errorhandler"); digester.addSetNext("mashup/page/errorhandler", "setErrorHandler"); digester.addObjectCreate("mashup/page/errorhandler/extractor", Extractor.class); digester.addSetProperties("mashup/page/errorhandler/extractor"); digester.addSetNext("mashup/page/errorhandler/extractor", "addExtractor"); digester.addObjectCreate("mashup/page/errorhandler/extractor/property", Property.class); digester.addSetProperties("mashup/page/errorhandler/extractor/property"); digester.addCallMethod("mashup/page/errorhandler/extractor/property", "setValue", 0); digester.addSetNext("mashup/page/errorhandler/extractor/property", "addProperty"); digester.parse(inputStream); }
public Varargs invoke(Varargs args) { return LuaValue.valueOf(((LivingEntity) ((LukkitObject) args.arg(1)).getObject()).setCustomNameVisible(args.toboolean(2))); }
public Varargs invoke(Varargs args) { ((LivingEntity) ((LukkitObject) args.arg(1)).getObject()).setCustomNameVisible(args.toboolean(2)); return LuaValue.NIL; }
public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(name + "("); boolean isFirst = true; for (AspectParam p : params) { if (!isFirst) { buffer.append(","); } buffer.append(p.toString()); isFirst = false; } buffer.append(")"); if (returnType != null) { buffer.append(":" + returnType); } return buffer.toString(); }
public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(name + "("); boolean isFirst = true; for (AspectParam p : params) { if (!isFirst) { buffer.append(","); } buffer.append(p.toString()); isFirst = false; } buffer.append(")"); if (returnType != null && returnType != "null") { buffer.append(":" + returnType); } return buffer.toString(); }
protected void processRequest(VitroRequest vreq, HttpServletResponse response) { String uriToDelete = vreq.getParameter("deletion"); if (StringUtils.isEmpty(uriToDelete)) { doError(response, "No individual specified for deletion", 500); return; } boolean hasPermission = true; if( !hasPermission ){ doError(response,"Insufficent permissions.",HttpStatus.SC_UNAUTHORIZED); return; } WebappDaoFactory wdf = vreq.getWebappDaoFactory(); IndividualDao idao = wdf.getIndividualDao(); int result = idao.deleteIndividual(uriToDelete); if (result == 1) { doError(response, "Error deleting individual", 500); } }
protected void processRequest(VitroRequest vreq, HttpServletResponse response) { String uriToDelete = vreq.getParameter("deletion"); if (StringUtils.isEmpty(uriToDelete)) { doError(response, "No individual specified for deletion", 500); return; } boolean hasPermission = true; if( !hasPermission ){ doError(response,"Insufficent permissions.", HttpStatus.SC_UNAUTHORIZED); return; } WebappDaoFactory wdf = vreq.getWebappDaoFactory(); IndividualDao idao = wdf.getIndividualDao(); int result = idao.deleteIndividual(uriToDelete); if (result == 1) { doError(response, "Error deleting individual", 500); } }
public View getView(int position, View convertView, ViewGroup parent) { Book book = list.get(position); View view; if(position < list.size()-1) { view = activity.getLayoutInflater().inflate( R.layout.list_item_book, parent, false); ((TextView) view.findViewById(R.id.search_result_title)) .setText(book.getName()); ((TextView) view.findViewById(R.id.search_result_author)) .setText(book.getAuthor()); if (showAvailable) { ((ImageView) view.findViewById(R.id.search_result_available)) .setImageResource(book.getAvailable() > 0 ? android.R.drawable.presence_online : android.R.drawable.presence_busy); } } else { view = activity.getLayoutInflater().inflate(R.layout.more_search_results, parent, false); } return view; }
public View getView(int position, View convertView, ViewGroup parent) { Book book = list.get(position); View view; if(position < list.size()-1 || list.size() < 50) { view = activity.getLayoutInflater().inflate( R.layout.list_item_book, parent, false); ((TextView) view.findViewById(R.id.search_result_title)) .setText(book.getName()); ((TextView) view.findViewById(R.id.search_result_author)) .setText(book.getAuthor()); if (showAvailable) { ((ImageView) view.findViewById(R.id.search_result_available)) .setImageResource(book.getAvailable() > 0 ? android.R.drawable.presence_online : android.R.drawable.presence_busy); } } else { view = activity.getLayoutInflater().inflate(R.layout.more_search_results, parent, false); } return view; }
private void bootstrap() { logger.debug("Started bootstrapping database"); Session session = hibernateSessionFactory.getCurrentSession(); Collection<RoomType> types = new ArrayList<>(); RoomType luxury = new RoomType("luxury"); RoomType cheap = new RoomType("cheap"); RoomType niceOne = new RoomType("nice one"); types.addAll(Arrays.asList(luxury, cheap, niceOne)); Collection<Room> rooms; Money standardPrice = Money.parse("USD 100"); Money upchargeExtraPerson = Money.parse("USD 110"); Money upchargeExtraBed = Money.parse("USD 120"); Room L100 = new Room("L", new RoomName("100"), luxury, HousekeepingStatus.CLEAN, RoomAvailability.AVAILABLE, 1, new Occupancy(3, 4), standardPrice, upchargeExtraPerson, upchargeExtraBed); Room L101 = new Room("L", new RoomName("101"), luxury, HousekeepingStatus.CLEAN, RoomAvailability.AVAILABLE, 1, new Occupancy(2, 3), standardPrice.plus(10), upchargeExtraPerson.plus(10), upchargeExtraBed.plus(10)); Room L102 = new Room("L", new RoomName("102"), luxury, HousekeepingStatus.CLEAN, RoomAvailability.OCCUPIED, 3, new Occupancy(2, 4), standardPrice.plus(30), upchargeExtraPerson.plus(30), upchargeExtraBed.plus(30)); Room C103 = new Room("C", new RoomName("103"), cheap, HousekeepingStatus.CLEAN, RoomAvailability.AVAILABLE, 4, new Occupancy(4, 10), standardPrice.plus(30), upchargeExtraPerson.plus(30), upchargeExtraBed.plus(30)); Room C104 = new Room("C", new RoomName("104"), cheap, HousekeepingStatus.CLEAN, RoomAvailability.AVAILABLE, 5, new Occupancy(6, 12), standardPrice.plus(40), upchargeExtraPerson.plus(40), upchargeExtraBed.plus(40)); Room N105 = new Room("N", new RoomName("105"), niceOne, HousekeepingStatus.CLEAN, RoomAvailability.AVAILABLE, 2, new Occupancy(2, 5), standardPrice.plus(50), upchargeExtraPerson.plus(50), upchargeExtraBed.plus(50)); rooms = Arrays.asList(L100, L101, L102, C103, C104, N105); Collection<Rate> rates; Season season = new BasicSeason("winter special", new AvailabilityPeriod(DateTime.now(), DateTime.now().plusDays(90), true)); Season season2 = new BasicSeason("christmas special", new AvailabilityPeriod(DateTime.now(), DateTime.now().plusDays(30), true)); Rate rate1_L100 = new SeasonRate(Money.parse("USD 50"), Money.parse("USD 60"), Money.parse("USD 70"), L100, season); Rate rate2_L100 = new SeasonRate(Money.parse("USD 20"), Money.parse("USD 60"), Money.parse("USD 70"), L100, season2); Rate rate1_L101 = new SeasonRate(Money.parse("USD 60"), Money.parse("USD 70"), Money.parse("USD 60"), L101, season); Rate rate2_L101 = new SeasonRate(Money.parse("USD 20"), Money.parse("USD 70"), Money.parse("USD 60"), L101, season2); Rate rate1_L102 = new SeasonRate(Money.parse("USD 60"), Money.parse("USD 70"), Money.parse("USD 60"), L102, season); Rate rate2_L102 = new SeasonRate(Money.parse("USD 20"), Money.parse("USD 70"), Money.parse("USD 60"), L102, season2); Rate rate1_C103 = new SeasonRate(Money.parse("USD 40"), Money.parse("USD 70"), Money.parse("USD 60"), C103, season); Rate rate2_C103 = new SeasonRate(Money.parse("USD 30"), Money.parse("USD 70"), Money.parse("USD 60"), C103, season2); Rate rate1_C104 = new SeasonRate(Money.parse("USD 70"), Money.parse("USD 70"), Money.parse("USD 60"), C104, season); Rate rate2_C104 = new SeasonRate(Money.parse("USD 50"), Money.parse("USD 70"), Money.parse("USD 60"), C104, season2); Rate rate1_N105 = new SeasonRate(Money.parse("USD 80"), Money.parse("USD 70"), Money.parse("USD 60"), N105, season); Rate rate2_N105 = new SeasonRate(Money.parse("USD 90"), Money.parse("USD 70"), Money.parse("USD 60"), N105, season2); Collection<Season> seasons = Arrays.asList(season, season2); rates = Arrays.asList(rate1_L100, rate2_L100, rate1_L101, rate2_L101, rate1_L102, rate2_L102, rate1_C103, rate2_C103, rate1_C104, rate2_C104, rate1_N105, rate2_N105); Guest guest1 = new Guest("Mr", "John", "Doe", Gender.MALE, DocumentType.DRIVER_LICENSE, "Drivers123", "555123123"); Guest guest2 = new Guest("Mr", "Johnson", "Donnel", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI123", "555555123"); Guest guest3 = new Guest("Mr", "Johnathan", "Doougles", Gender.MALE, DocumentType.DRIVER_LICENSE, "DDRI1555", "555123123"); Guest guest4 = new Guest("Miss", "Joana", "Dooues", Gender.FEMALE, DocumentType.PERSONAL_ID, "APK132555", "819238923"); Guest guest5 = new Guest("Ms", "Kate", "Hudson", Gender.FEMALE, DocumentType.PERSONAL_ID, "DSA123889", "534098123"); Guest guest6 = new Guest("Mr", "Jack", "Hack", Gender.MALE, DocumentType.PERSONAL_ID, "LKK123555", "123589124"); Guest guest7 = new Guest("Ms", "Ewa", "Kowalska", Gender.FEMALE, DocumentType.PERSONAL_ID, "PAS123553", "123985332"); Guest guest8 = new Guest("Ms", "Karolina", "Iksinska", Gender.FEMALE, DocumentType.DRIVER_LICENSE, "DRI132511", "898123532"); Guest guest9 = new Guest("Mr", "Grzegorz", "Brzeczyszczykiewicz", Gender.MALE, DocumentType.PERSONAL_ID, "AAA123123", "342089123"); Guest guest10 = new Guest("Mrs", "John", "ToBeRemoved", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI132135", "12312353"); Guest guest11 = new Guest("Mr", "John", "ToBeRemoved1", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI132136", "12312353"); Guest guest12 = new Guest("Mr", "John", "ToBeRemoved2", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI132137", "12312353"); Guest guest13 = new Guest("Mr", "John", "ToBeRemoved3", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI132138", "12312353"); Guest guest14 = new Guest("Mr", "John", "ToBeRemoved4", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI132139", "12312353"); Guest guest15 = new Guest("Mr", "John", "ToBeRemoved5", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI132110", "12312353"); Collection<Guest> guests = Arrays.asList(guest1, guest2, guest3, guest4, guest5, guest6, guest7, guest8, guest9, guest10, guest11, guest12, guest13, guest14, guest15); for (Guest guest : guests) { guest.setNationality("Polish"); } Reservation reservation = new Reservation(Id.NO_ID, guest1, L100.rackRate(), new DateTime(new DateMidnight(2012, 12, 1)), new DateTime(new DateMidnight(2012, 12, 5)), 2, 0, 0, ReservationStatus.INHOUSE); Reservation reservation2 = new Reservation(Id.NO_ID, guest2, L102.rackRate(), new DateTime(new DateMidnight(2012, 12, 3)), new DateTime(new DateMidnight(2012, 12, 8)), 2, 0, 0, ReservationStatus.RESERVED); Reservation reservation3 = new Reservation(Id.NO_ID, guest2, rate1_C103, new DateTime(new DateMidnight(2012, 12, 2)), new DateTime(new DateMidnight(2012, 12, 15)), 3, 0, 0, ReservationStatus.RESERVED); Reservation reservation4 = new Reservation(Id.NO_ID, guest3, rate1_N105, new DateTime(new DateMidnight(2012, 12, 10)), new DateTime(new DateMidnight(2012, 12, 14)), 2, 0, 0, ReservationStatus.RESERVED); Reservation reservation5 = new Reservation(Id.NO_ID, guest5, rate2_C104, new DateTime(new DateMidnight(2012, 12, 20)), new DateTime(new DateMidnight(2012, 12, 28)), 1, 0, 0, ReservationStatus.RESERVED); Reservation reservation6 = new Reservation(Id.NO_ID, guest5, rate2_C104, new DateTime(DateMidnight.now()), new DateTime(DateMidnight.now().plusDays(5)), 1, 0, 0, ReservationStatus.RESERVED); Collection<Reservation> reservations = Arrays.asList(reservation, reservation2, reservation3, reservation4, reservation5, reservation6); session.beginTransaction(); logger.debug("adding room types:"); for (RoomType type : types) { session.save(type); logger.debug("room type: " + type.toString()); } logger.debug("adding rooms"); for (Room room : rooms) { logger.debug("room: " + room.toString()); session.save(room); } logger.debug("adding seasons"); for (Season s : seasons) { logger.debug("season: " + s.toString()); session.save(s); } logger.debug("adding season rates"); for (Rate rate : rates) { logger.debug("rate: " + rate.toString()); session.save(rate); } logger.debug("adding guests"); for (Guest guest : guests) { logger.debug("guest: " + guest.toString()); session.save(guest); } logger.debug("adding reservations"); for (Reservation res : reservations) { logger.debug("reservation: " + res.toString()); session.save(res); } session.getTransaction().commit(); logger.debug("Finished bootstrapping database"); }
private void bootstrap() { logger.debug("Started bootstrapping database"); Session session = hibernateSessionFactory.getCurrentSession(); Collection<RoomType> types = new ArrayList<>(); RoomType luxury = new RoomType("luxury"); RoomType cheap = new RoomType("cheap"); RoomType niceOne = new RoomType("nice one"); types.addAll(Arrays.asList(luxury, cheap, niceOne)); Collection<Room> rooms; Money standardPrice = Money.parse("USD 100"); Money upchargeExtraPerson = Money.parse("USD 110"); Money upchargeExtraBed = Money.parse("USD 120"); Room L100 = new Room("L", new RoomName("100"), luxury, HousekeepingStatus.CLEAN, RoomAvailability.AVAILABLE, 1, new Occupancy(3, 4), standardPrice, upchargeExtraPerson, upchargeExtraBed); Room L101 = new Room("L", new RoomName("101"), luxury, HousekeepingStatus.CLEAN, RoomAvailability.AVAILABLE, 1, new Occupancy(2, 3), standardPrice.plus(10), upchargeExtraPerson.plus(10), upchargeExtraBed.plus(10)); Room L102 = new Room("L", new RoomName("102"), luxury, HousekeepingStatus.CLEAN, RoomAvailability.OCCUPIED, 3, new Occupancy(2, 4), standardPrice.plus(30), upchargeExtraPerson.plus(30), upchargeExtraBed.plus(30)); Room C103 = new Room("C", new RoomName("103"), cheap, HousekeepingStatus.CLEAN, RoomAvailability.AVAILABLE, 4, new Occupancy(4, 10), standardPrice.plus(30), upchargeExtraPerson.plus(30), upchargeExtraBed.plus(30)); Room C104 = new Room("C", new RoomName("104"), cheap, HousekeepingStatus.CLEAN, RoomAvailability.AVAILABLE, 5, new Occupancy(6, 12), standardPrice.plus(40), upchargeExtraPerson.plus(40), upchargeExtraBed.plus(40)); Room N105 = new Room("N", new RoomName("105"), niceOne, HousekeepingStatus.CLEAN, RoomAvailability.AVAILABLE, 2, new Occupancy(2, 5), standardPrice.plus(50), upchargeExtraPerson.plus(50), upchargeExtraBed.plus(50)); rooms = Arrays.asList(L100, L101, L102, C103, C104, N105); Collection<Rate> rates; Season season = new BasicSeason("winter special", new AvailabilityPeriod(DateTime.now(), DateTime.now().plusDays(90), true)); Season season2 = new BasicSeason("christmas special", new AvailabilityPeriod(DateTime.now(), DateTime.now().plusDays(30), true)); Rate rate1_L100 = new SeasonRate(Money.parse("USD 50"), Money.parse("USD 60"), Money.parse("USD 70"), L100, season); Rate rate2_L100 = new SeasonRate(Money.parse("USD 20"), Money.parse("USD 60"), Money.parse("USD 70"), L100, season2); Rate rate1_L101 = new SeasonRate(Money.parse("USD 60"), Money.parse("USD 70"), Money.parse("USD 60"), L101, season); Rate rate2_L101 = new SeasonRate(Money.parse("USD 20"), Money.parse("USD 70"), Money.parse("USD 60"), L101, season2); Rate rate1_L102 = new SeasonRate(Money.parse("USD 60"), Money.parse("USD 70"), Money.parse("USD 60"), L102, season); Rate rate2_L102 = new SeasonRate(Money.parse("USD 20"), Money.parse("USD 70"), Money.parse("USD 60"), L102, season2); Rate rate1_C103 = new SeasonRate(Money.parse("USD 40"), Money.parse("USD 70"), Money.parse("USD 60"), C103, season); Rate rate2_C103 = new SeasonRate(Money.parse("USD 30"), Money.parse("USD 70"), Money.parse("USD 60"), C103, season2); Rate rate1_C104 = new SeasonRate(Money.parse("USD 70"), Money.parse("USD 70"), Money.parse("USD 60"), C104, season); Rate rate2_C104 = new SeasonRate(Money.parse("USD 50"), Money.parse("USD 70"), Money.parse("USD 60"), C104, season2); Rate rate1_N105 = new SeasonRate(Money.parse("USD 80"), Money.parse("USD 70"), Money.parse("USD 60"), N105, season); Rate rate2_N105 = new SeasonRate(Money.parse("USD 90"), Money.parse("USD 70"), Money.parse("USD 60"), N105, season2); Collection<Season> seasons = Arrays.asList(season, season2); rates = Arrays.asList(rate1_L100, rate2_L100, rate1_L101, rate2_L101, rate1_L102, rate2_L102, rate1_C103, rate2_C103, rate1_C104, rate2_C104, rate1_N105, rate2_N105); Guest guest1 = new Guest("Mr", "John", "Doe", Gender.MALE, DocumentType.DRIVER_LICENSE, "Drivers123", "555123123"); Guest guest2 = new Guest("Mr", "Johnson", "Donnel", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI123", "555555123"); Guest guest3 = new Guest("Mr", "Johnathan", "Doougles", Gender.MALE, DocumentType.DRIVER_LICENSE, "DDRI1555", "555123123"); Guest guest4 = new Guest("Miss", "Joana", "Dooues", Gender.FEMALE, DocumentType.PERSONAL_ID, "APK132555", "819238923"); Guest guest5 = new Guest("Ms", "Kate", "Hudson", Gender.FEMALE, DocumentType.PERSONAL_ID, "DSA123889", "534098123"); Guest guest6 = new Guest("Mr", "Jack", "Hack", Gender.MALE, DocumentType.PERSONAL_ID, "LKK123555", "123589124"); Guest guest7 = new Guest("Ms", "Ewa", "Kowalska", Gender.FEMALE, DocumentType.PERSONAL_ID, "PAS123553", "123985332"); Guest guest8 = new Guest("Ms", "Karolina", "Iksinska", Gender.FEMALE, DocumentType.DRIVER_LICENSE, "DRI132511", "898123532"); Guest guest9 = new Guest("Mr", "Grzegorz", "Brzeczyszczykiewicz", Gender.MALE, DocumentType.PERSONAL_ID, "AAA123123", "342089123"); Guest guest10 = new Guest("Mrs", "John", "ToBeRemoved", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI132135", "12312353"); Guest guest11 = new Guest("Mr", "John", "ToBeRemoved1", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI132136", "12312353"); Guest guest12 = new Guest("Mr", "John", "ToBeRemoved2", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI132137", "12312353"); Guest guest13 = new Guest("Mr", "John", "ToBeRemoved3", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI132138", "12312353"); Guest guest14 = new Guest("Mr", "John", "ToBeRemoved4", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI132139", "12312353"); Guest guest15 = new Guest("Mr", "John", "ToBeRemoved5", Gender.MALE, DocumentType.DRIVER_LICENSE, "DRI132110", "12312353"); Collection<Guest> guests = Arrays.asList(guest1, guest2, guest3, guest4, guest5, guest6, guest7, guest8, guest9, guest10, guest11, guest12, guest13, guest14, guest15); for (Guest guest : guests) { guest.setNationality("Polish"); } Reservation reservation = new Reservation(Id.NO_ID, guest1, L100.rackRate(), new DateTime(new DateMidnight(2012, 12, 1)), new DateTime(new DateMidnight(2012, 12, 5)), 2, 0, 0, ReservationStatus.INHOUSE); Reservation reservation2 = new Reservation(Id.NO_ID, guest2, L102.rackRate(), new DateTime(new DateMidnight(2012, 12, 3)), new DateTime(new DateMidnight(2012, 12, 8)), 2, 0, 0, ReservationStatus.RESERVED); Reservation reservation3 = new Reservation(Id.NO_ID, guest2, rate1_C103, new DateTime(new DateMidnight(2012, 12, 2)), new DateTime(new DateMidnight(2012, 12, 15)), 3, 0, 0, ReservationStatus.RESERVED); Reservation reservation4 = new Reservation(Id.NO_ID, guest3, rate1_N105, new DateTime(new DateMidnight(2012, 12, 10)), new DateTime(new DateMidnight(2012, 12, 14)), 2, 0, 0, ReservationStatus.RESERVED); Reservation reservation5 = new Reservation(Id.NO_ID, guest5, rate2_C104, new DateTime(new DateMidnight(2012, 12, 20)), new DateTime(new DateMidnight(2012, 12, 28)), 1, 0, 0, ReservationStatus.RESERVED); Reservation reservation6 = new Reservation(Id.NO_ID, guest5, rate2_C104, new DateTime(DateMidnight.now().plusDays(1)), new DateTime(DateMidnight.now().plusDays(5)), 1, 0, 0, ReservationStatus.RESERVED); Collection<Reservation> reservations = Arrays.asList(reservation, reservation2, reservation3, reservation4, reservation5, reservation6); session.beginTransaction(); logger.debug("adding room types:"); for (RoomType type : types) { session.save(type); logger.debug("room type: " + type.toString()); } logger.debug("adding rooms"); for (Room room : rooms) { logger.debug("room: " + room.toString()); session.save(room); } logger.debug("adding seasons"); for (Season s : seasons) { logger.debug("season: " + s.toString()); session.save(s); } logger.debug("adding season rates"); for (Rate rate : rates) { logger.debug("rate: " + rate.toString()); session.save(rate); } logger.debug("adding guests"); for (Guest guest : guests) { logger.debug("guest: " + guest.toString()); session.save(guest); } logger.debug("adding reservations"); for (Reservation res : reservations) { logger.debug("reservation: " + res.toString()); session.save(res); } session.getTransaction().commit(); logger.debug("Finished bootstrapping database"); }
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { IPath path; IAnnotationModel model; if (textViewer instanceof ISourceViewer) { path = null; model = ((ISourceViewer) textViewer).getAnnotationModel(); } else { path = getEditorInputPath(); model = getAnnotationModel(path); } if (model == null) { return null; } try { final IPreferenceStore store = getCombinedPreferenceStore(); Iterator<Annotation> e = new ScriptAnnotationIterator(model, true, fAllAnnotations); int layer = -1; String message = null; boolean multi = false; while (e.hasNext()) { Annotation a = e.next(); AnnotationPreference preference = getAnnotationPreference(a); if (preference == null) { continue; } if (!isActive(store, preference.getTextPreferenceKey()) && !isActive(store, preference.getHighlightPreferenceKey())) { continue; } Position p = model.getPosition(a); int l = fAnnotationAccess.getLayer(a); if (l >= layer && p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) { String msg = getMessageFromAnnotation(a); if (msg != null && msg.trim().length() > 0) { if (message != null) { message = message + "\n-" + msg; multi = true; } else { message = msg; } layer = l; } } } if (layer > -1) { if (multi) { message = "Multiply Markers:\n-" + message; } return formatMessage(message); } } finally { try { if (path != null) { ITextFileBufferManager manager = FileBuffers .getTextFileBufferManager(); manager.disconnect(path, LocationKind.NORMALIZE, null); } } catch (CoreException ex) { DLTKUIPlugin.log(ex.getStatus()); } } return null; }
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { IPath path; IAnnotationModel model; if (textViewer instanceof ISourceViewer) { path = null; model = ((ISourceViewer) textViewer).getAnnotationModel(); } else { path = getEditorInputPath(); model = getAnnotationModel(path); } if (model == null) { return null; } try { final IPreferenceStore store = getCombinedPreferenceStore(); Iterator<Annotation> e = new ScriptAnnotationIterator(model, true, fAllAnnotations); int layer = -1; String message = null; boolean multi = false; while (e.hasNext()) { Annotation a = e.next(); AnnotationPreference preference = getAnnotationPreference(a); if (preference == null) { continue; } if (!isActive(store, preference.getTextPreferenceKey()) && !isActive(store, preference.getHighlightPreferenceKey())) { continue; } Position p = model.getPosition(a); int l = fAnnotationAccess.getLayer(a); if (l >= layer && p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) { String msg = getMessageFromAnnotation(a); if (msg != null && msg.trim().length() > 0) { if (message != null) { message = message + "\n-" + msg; multi = true; } else { message = msg; } layer = l; } } } if (layer > -1) { if (multi) { message = "Multiple markers:\n-" + message; } return formatMessage(message); } } finally { try { if (path != null) { ITextFileBufferManager manager = FileBuffers .getTextFileBufferManager(); manager.disconnect(path, LocationKind.NORMALIZE, null); } } catch (CoreException ex) { DLTKUIPlugin.log(ex.getStatus()); } } return null; }