code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2011 The Zed Attack Proxy Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.extension.autoupdate; import java.awt.EventQueue; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.FileAlreadyExistsException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.net.ssl.SSLHandshakeException; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.SwingWorker; import javax.swing.filechooser.FileFilter; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.httpclient.URI; import org.apache.log4j.Logger; import org.parosproxy.paros.Constant; import org.parosproxy.paros.control.Control; import org.parosproxy.paros.extension.Extension; import org.parosproxy.paros.extension.ExtensionAdaptor; import org.parosproxy.paros.extension.ExtensionHook; import org.parosproxy.paros.model.FileCopier; import org.parosproxy.paros.model.Model; import org.parosproxy.paros.network.HttpMessage; import org.parosproxy.paros.network.HttpSender; import org.parosproxy.paros.network.HttpStatusCode; import org.parosproxy.paros.view.View; import org.zaproxy.zap.control.AddOn; import org.zaproxy.zap.control.AddOn.AddOnRunRequirements; import org.zaproxy.zap.control.AddOnCollection; import org.zaproxy.zap.control.AddOnCollection.Platform; import org.zaproxy.zap.control.AddOnRunIssuesUtils; import org.zaproxy.zap.control.AddOnUninstallationProgressCallback; import org.zaproxy.zap.control.ExtensionFactory; import org.zaproxy.zap.control.ZapRelease; import org.zaproxy.zap.extension.api.API; import org.zaproxy.zap.extension.autoupdate.AddOnDependencyChecker.AddOnChangesResult; import org.zaproxy.zap.extension.autoupdate.UninstallationProgressDialogue.AddOnUninstallListener; import org.zaproxy.zap.extension.autoupdate.UninstallationProgressDialogue.UninstallationProgressEvent; import org.zaproxy.zap.extension.autoupdate.UninstallationProgressDialogue.UninstallationProgressHandler; import org.zaproxy.zap.extension.log4j.ExtensionLog4j; import org.zaproxy.zap.utils.ZapXmlConfiguration; import org.zaproxy.zap.view.ScanStatus; import org.zaproxy.zap.view.ZapMenuItem; public class ExtensionAutoUpdate extends ExtensionAdaptor implements CheckForUpdateCallback { // The short URL means that the number of checkForUpdates can be tracked - see https://bitly.com/u/psiinon // Note that URLs must now use https (unless you change the code;) private static final String ZAP_VERSIONS_DEV_XML_SHORT = "https://bit.ly/owaspzap-dev"; private static final String ZAP_VERSIONS_DEV_XML_WEEKLY_SHORT = "https://bit.ly/owaspzap-devw"; private static final String ZAP_VERSIONS_DEV_XML_FULL = "https://raw.githubusercontent.com/zaproxy/zap-admin/master/ZapVersions-dev.xml"; // URLs for use when testing locally ;) //private static final String ZAP_VERSIONS_XML_SHORT = "https://localhost:8080/zapcfu/ZapVersions.xml"; //private static final String ZAP_VERSIONS_XML_FULL = "https://localhost:8080/zapcfu/ZapVersions.xml"; private static final String VERSION_FILE_NAME = "ZapVersions.xml"; private ZapMenuItem menuItemCheckUpdate = null; private ZapMenuItem menuItemLoadAddOn = null; private static final Logger logger = Logger.getLogger(ExtensionAutoUpdate.class); private HttpSender httpSender = null; private DownloadManager downloadManager = null; private ManageAddOnsDialog addonsDialog = null; //private UpdateDialog updateDialog = null; private Thread downloadProgressThread = null; private Thread remoteCallThread = null; private ScanStatus scanStatus = null; private JButton addonsButton = null; private AddOnCollection latestVersionInfo = null; private AddOnCollection localVersionInfo = null; private AddOnCollection previousVersionInfo = null; private AutoUpdateAPI api = null; // Files currently being downloaded private List<Downloader> downloadFiles = new ArrayList<>(); /** * */ public ExtensionAutoUpdate() { super(); initialize(); } /** * This method initializes this */ private void initialize() { this.setName("ExtensionAutoUpdate"); this.setOrder(40); this.downloadManager = new DownloadManager(Model.getSingleton().getOptionsParam().getConnectionParam()); this.downloadManager.start(); // Do this before it can get overwritten by the latest one this.getPreviousVersionInfo(); } /** * This method initializes menuItemEncoder * * @return javax.swing.JMenuItem */ private ZapMenuItem getMenuItemCheckUpdate() { if (menuItemCheckUpdate == null) { menuItemCheckUpdate = new ZapMenuItem("cfu.help.menu.check", KeyStroke.getKeyStroke(KeyEvent.VK_U, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false)); menuItemCheckUpdate.setText(Constant.messages.getString("cfu.help.menu.check")); menuItemCheckUpdate.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { getAddOnsDialog().setVisible(true); getAddOnsDialog().checkForUpdates(); } }); } return menuItemCheckUpdate; } private ZapMenuItem getMenuItemLoadAddOn() { if (menuItemLoadAddOn == null) { menuItemLoadAddOn = new ZapMenuItem("cfu.file.menu.loadaddon", KeyStroke.getKeyStroke(KeyEvent.VK_L, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false)); menuItemLoadAddOn.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { try { JFileChooser chooser = new JFileChooser(Model.getSingleton().getOptionsParam().getUserDirectory()); File file = null; chooser.setFileFilter(new FileFilter() { @Override public boolean accept(File file) { if (file.isDirectory()) { return true; } else if (file.isFile() && file.getName().endsWith(".zap")) { return true; } return false; } @Override public String getDescription() { return Constant.messages.getString("file.format.zap.addon"); } }); int rc = chooser.showOpenDialog(View.getSingleton().getMainFrame()); if(rc == JFileChooser.APPROVE_OPTION) { file = chooser.getSelectedFile(); if (file == null) { return; } installLocalAddOn(file); } } catch (Exception e1) { logger.error(e1.getMessage(), e1); } } }); } return menuItemLoadAddOn; } private void installLocalAddOn(File file) throws Exception { if (!AddOn.isAddOn(file)) { showWarningMessageInvalidAddOnFile(); return; } AddOn ao; try { ao = new AddOn(file); } catch (Exception e) { showWarningMessageInvalidAddOnFile(); return; } if (!ao.canLoadInCurrentVersion()) { showWarningMessageCantLoadAddOn(ao); return; } AddOnDependencyChecker dependencyChecker = new AddOnDependencyChecker(getLocalVersionInfo(), latestVersionInfo == null ? getLocalVersionInfo() : latestVersionInfo); AddOnChangesResult result = dependencyChecker.calculateInstallChanges(ao); if (result.getOldVersions().isEmpty() && result.getUninstalls().isEmpty()) { AddOnRunRequirements reqs = ao.calculateRunRequirements(getLocalVersionInfo().getAddOns()); if (!reqs.isRunnable()) { if (!AddOnRunIssuesUtils.askConfirmationAddOnNotRunnable( Constant.messages.getString("cfu.warn.addOnNotRunnable.message"), Constant.messages.getString("cfu.warn.addOnNotRunnable.question"), getLocalVersionInfo(), ao)) { return; } } installLocalAddOn(ao); return; } if (!dependencyChecker.confirmInstallChanges(getView().getMainFrame(), result)) { return; } result.getInstalls().remove(ao); processAddOnChanges(getView().getMainFrame(), result); installLocalAddOn(ao); } private void installLocalAddOn(AddOn ao) { File addOnFile; try { addOnFile = copyAddOnFileToLocalPluginFolder(ao.getFile()); } catch (FileAlreadyExistsException e) { showWarningMessageAddOnFileAlreadyExists(e.getFile(), e.getOtherFile()); logger.warn("Unable to copy add-on, a file with the same name already exists.", e); return; } catch (IOException e) { showWarningMessageUnableToCopyAddOnFile(); logger.warn("Unable to copy add-on to local plugin folder.", e); return; } ao.setFile(addOnFile); install(ao); } private void showWarningMessageInvalidAddOnFile() { View.getSingleton().showWarningDialog(Constant.messages.getString("cfu.warn.invalidAddOn")); } private void showWarningMessageCantLoadAddOn(AddOn ao) { String message = MessageFormat.format( Constant.messages.getString("cfu.warn.cantload"), ao.getNotBeforeVersion(), ao.getNotFromVersion()); View.getSingleton().showWarningDialog(message); } private static File copyAddOnFileToLocalPluginFolder(File file) throws IOException { if (isFileInLocalPluginFolder(file)) { return file; } File targetFile = new File(Constant.FOLDER_LOCAL_PLUGIN, file.getName()); if (targetFile.exists()) { throw new FileAlreadyExistsException(file.getAbsolutePath(), targetFile.getAbsolutePath(), ""); } FileCopier fileCopier = new FileCopier(); fileCopier.copy(file, targetFile); return targetFile; } private static boolean isFileInLocalPluginFolder(File file) { File fileLocalPluginFolder = new File(Constant.FOLDER_LOCAL_PLUGIN, file.getName()); if (fileLocalPluginFolder.getAbsolutePath().equals(file.getAbsolutePath())) { return true; } return false; } private static void showWarningMessageAddOnFileAlreadyExists(String file, String targetFile) { String message = MessageFormat.format(Constant.messages.getString("cfu.warn.addOnAlreadExists"), file, targetFile); View.getSingleton().showWarningDialog(message); } private static void showWarningMessageUnableToCopyAddOnFile() { String pathPluginFolder = new File(Constant.FOLDER_LOCAL_PLUGIN).getAbsolutePath(); String message = MessageFormat.format(Constant.messages.getString("cfu.warn.unableToCopyAddOn"), pathPluginFolder); View.getSingleton().showWarningDialog(message); } private synchronized ManageAddOnsDialog getAddOnsDialog() { if (addonsDialog == null) { addonsDialog = new ManageAddOnsDialog(this, this.getCurrentVersion(), getLocalVersionInfo()); if (this.previousVersionInfo != null) { addonsDialog.setPreviousVersionInfo(this.previousVersionInfo); } if (this.latestVersionInfo != null) { addonsDialog.setLatestVersionInfo(this.latestVersionInfo); } } return addonsDialog; } private void downloadFile (URL url, File targetFile, long size, String hash) { if (View.isInitialised()) { // Report info to the Output tab View.getSingleton().getOutputPanel().append( MessageFormat.format( Constant.messages.getString("cfu.output.downloading") + "\n", url.toString(), targetFile.getAbsolutePath())); } this.downloadFiles.add(this.downloadManager.downloadFile(url, targetFile, size, hash)); if (View.isInitialised()) { // Means we do have a UI if (this.downloadProgressThread != null && ! this.downloadProgressThread.isAlive()) { this.downloadProgressThread = null; } if (this.downloadProgressThread == null) { this.downloadProgressThread = new Thread() { @Override public void run() { while (downloadManager.getCurrentDownloadCount() > 0) { getScanStatus().setScanCount(downloadManager.getCurrentDownloadCount()); if (addonsDialog != null && addonsDialog.isVisible()) { addonsDialog.showProgress(); } try { sleep(100); } catch (InterruptedException e) { // Ignore } } // Complete download progress if (addonsDialog != null) { addonsDialog.showProgress(); } getScanStatus().setScanCount(0); installNewExtensions(); } }; this.downloadProgressThread.start(); } } } public void installNewExtensions() { List<Downloader> handledFiles = new ArrayList<>(); for (Downloader dl : downloadFiles) { if (dl.getFinished() == null) { continue; } handledFiles.add(dl); try { if (!dl.isValidated()) { logger.debug("Ignoring unvalidated download: " + dl.getUrl()); if (addonsDialog != null) { addonsDialog.notifyAddOnDownloadFailed(dl.getUrl().toString()); } else { String url = dl.getUrl().toString(); for (AddOn addOn : latestVersionInfo.getAddOns()) { if (url.equals(addOn.getUrl().toString())) { addOn.setInstallationStatus(AddOn.InstallationStatus.AVAILABLE); break; } } } } else if (AddOn.isAddOn(dl.getTargetFile())) { AddOn ao = new AddOn(dl.getTargetFile()); if (ao.canLoadInCurrentVersion()) { install(ao); } else { logger.info("Cant load add-on " + ao.getName() + " Not before=" + ao.getNotBeforeVersion() + " Not from=" + ao.getNotFromVersion() + " Version=" + Constant.PROGRAM_VERSION); } } } catch (Exception e) { logger.error(e.getMessage(), e); } } for (Downloader dl : handledFiles) { // Cant remove in loop above as we're iterating through the list this.downloadFiles.remove(dl); } } public int getDownloadProgressPercent(URL url) throws Exception { return this.downloadManager.getProgressPercent(url); } public int getCurrentDownloadCount() { return this.downloadManager.getCurrentDownloadCount(); } @Override public void hook(ExtensionHook extensionHook) { super.hook(extensionHook); if (getView() != null) { extensionHook.getHookMenu().addHelpMenuItem(getMenuItemCheckUpdate()); extensionHook.getHookMenu().addFileMenuItem(getMenuItemLoadAddOn()); View.getSingleton().addMainToolbarButton(getAddonsButton()); View.getSingleton().getMainFrame().getMainFooterPanel().addFooterToolbarRightLabel(getScanStatus().getCountLabel()); } this.api = new AutoUpdateAPI(this); this.api.addApiOptions(getModel().getOptionsParam().getCheckForUpdatesParam()); API.getInstance().registerApiImplementor(this.api); } private ScanStatus getScanStatus() { if (scanStatus == null) { scanStatus = new ScanStatus( new ImageIcon( ExtensionLog4j.class.getResource("/resource/icon/fugue/download.png")), Constant.messages.getString("cfu.downloads.icon.title")); } return scanStatus; } private JButton getAddonsButton() { if (addonsButton == null) { addonsButton = new JButton(); addonsButton.setIcon(new ImageIcon(ExtensionAutoUpdate.class.getResource("/resource/icon/fugue/block.png"))); addonsButton.setToolTipText(Constant.messages.getString("cfu.button.addons.browse")); addonsButton.setEnabled(true); addonsButton.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { getAddOnsDialog().setVisible(true); } }); } return this.addonsButton; } @Override public String getAuthor() { return Constant.ZAP_TEAM; } @Override public String getDescription() { return Constant.messages.getString("autoupdate.desc"); } @Override public URL getURL() { try { return new URL(Constant.ZAP_HOMEPAGE); } catch (MalformedURLException e) { return null; } } @Override public void destroy() { this.downloadManager.shutdown(true); } private HttpSender getHttpSender() { if (httpSender == null) { httpSender = new HttpSender(Model.getSingleton().getOptionsParam().getConnectionParam(), true, HttpSender.CHECK_FOR_UPDATES_INITIATOR); } return httpSender; } /* * */ public void alertIfNewVersions() { // Kicks off a thread and pops up a window if there are new verisons // (depending on the options the user has chosen // Only expect this to be called on startup final OptionsParamCheckForUpdates options = getModel().getOptionsParam().getCheckForUpdatesParam(); if (View.isInitialised()) { if (options.isCheckOnStartUnset()) { // First time in int result = getView().showConfirmDialog( Constant.messages.getString("cfu.confirm.startCheck")); if (result == JOptionPane.OK_OPTION) { options.setCheckOnStart(true); options.setCheckAddonUpdates(true); options.setDownloadNewRelease(true); } else { options.setCheckOnStart(false); } // Save try { this.getModel().getOptionsParam().getConfig().save(); } catch (ConfigurationException ce) { logger.error(ce.getMessage(), ce); getView().showWarningDialog( Constant.messages.getString("cfu.confirm.error")); return; } } if (! options.isCheckOnStart()) { return; } } if (! options.checkOnStart()) { // Top level option not set, dont do anything, unless already downloaded last release if (View.isInitialised() && this.getPreviousVersionInfo() != null) { ZapRelease rel = this.getPreviousVersionInfo().getZapRelease(); if (rel != null && rel.isNewerThan(this.getCurrentVersion())) { File f = new File(Constant.FOLDER_LOCAL_PLUGIN, rel.getFileName()); if (f.exists() && f.length() >= rel.getSize()) { // Already downloaded, prompt to install and exit this.promptToLaunchReleaseAndClose(rel.getVersion(), f); } } } return; } // Handle the response in a callback this.getLatestVersionInfo(this); } private AddOnCollection getLocalVersionInfo () { if (localVersionInfo == null) { localVersionInfo = ExtensionFactory.getAddOnLoader().getAddOnCollection(); } return localVersionInfo; } private ZapXmlConfiguration getRemoteConfigurationUrl(String url) throws IOException, ConfigurationException, InvalidCfuUrlException { HttpMessage msg = new HttpMessage(new URI(url, true), Model.getSingleton().getOptionsParam().getConnectionParam()); getHttpSender().sendAndReceive(msg,true); if (msg.getResponseHeader().getStatusCode() != HttpStatusCode.OK) { throw new IOException(); } if (! msg.getRequestHeader().isSecure()) { // Only access the cfu page over https throw new InvalidCfuUrlException(msg.getRequestHeader().getURI().toString()); } ZapXmlConfiguration config = new ZapXmlConfiguration(); config.setDelimiterParsingDisabled(true); config.load(new StringReader(msg.getResponseBody().toString())); // Save version file so we can report new addons next time File f = new File(Constant.FOLDER_LOCAL_PLUGIN, VERSION_FILE_NAME); FileWriter out = null; try { out = new FileWriter(f); out.write(msg.getResponseBody().toString()); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { // Ignore } } return config; } protected String getLatestVersionNumber() { if (this.getLatestVersionInfo() == null || this.getLatestVersionInfo().getZapRelease() == null) { return null; } return this.getLatestVersionInfo().getZapRelease().getVersion(); } protected boolean isLatestVersion() { if (this.getLatestVersionInfo() == null || this.getLatestVersionInfo().getZapRelease() == null) { return true; } return ! this.getLatestVersionInfo().getZapRelease().isNewerThan(this.getCurrentVersion()); } protected boolean downloadLatestRelease() { if (Constant.isKali()) { if (View.isInitialised()) { // Just tell the user to use one of the Kali options View.getSingleton().showMessageDialog(this.getAddOnsDialog(), Constant.messages.getString("cfu.kali.options")); } return false; } if (this.getLatestVersionInfo() == null || this.getLatestVersionInfo().getZapRelease() == null) { return false; } ZapRelease latestRelease = this.getLatestVersionInfo().getZapRelease(); if (latestRelease.isNewerThan(this.getCurrentVersion())) { File f = new File(Constant.FOLDER_LOCAL_PLUGIN, latestRelease.getFileName()); downloadFile(latestRelease.getUrl(), f, latestRelease.getSize(), latestRelease.getHash()); return true; } return false; } private AddOnCollection getPreviousVersionInfo() { if (this.previousVersionInfo == null) { File f = new File(Constant.FOLDER_LOCAL_PLUGIN, VERSION_FILE_NAME); if (f.exists()) { try { this.previousVersionInfo = new AddOnCollection(new ZapXmlConfiguration(f), this.getPlatform()); } catch (ConfigurationException e) { logger.error(e.getMessage(), e); } } } return this.previousVersionInfo; } protected List<Downloader> getAllDownloadsProgress() { return this.downloadManager.getProgress(); } private List<AddOn> getUpdatedAddOns() { return getLocalVersionInfo().getUpdatedAddOns(this.getLatestVersionInfo()); } private List<AddOn> getNewAddOns() { if (this.getPreviousVersionInfo() != null) { return this.getPreviousVersionInfo().getNewAddOns(this.getLatestVersionInfo()); } return getLocalVersionInfo().getNewAddOns(this.getLatestVersionInfo()); } protected AddOnCollection getLatestVersionInfo () { return getLatestVersionInfo(null); } protected AddOnCollection getLatestVersionInfo (final CheckForUpdateCallback callback) { if (latestVersionInfo == null) { if (this.remoteCallThread == null || !this.remoteCallThread.isAlive()) { this.remoteCallThread = new Thread() { @Override public void run() { // Using a thread as the first call could timeout // and we dont want the ui to hang in the meantime this.setName("ZAP-cfu"); String url = ZAP_VERSIONS_DEV_XML_SHORT; if (Constant.isDailyBuild()) { url = ZAP_VERSIONS_DEV_XML_WEEKLY_SHORT; } logger.debug("Getting latest version info from " + url); try { latestVersionInfo = new AddOnCollection(getRemoteConfigurationUrl(url), getPlatform(), false); } catch (Exception e1) { logger.debug("Failed to access " + url, e1); logger.debug("Getting latest version info from " + ZAP_VERSIONS_DEV_XML_FULL); url = ZAP_VERSIONS_DEV_XML_FULL; try { latestVersionInfo = new AddOnCollection(getRemoteConfigurationUrl(url), getPlatform(), false); } catch (SSLHandshakeException e2) { if (callback != null) { callback.insecureUrl(url, e2); } } catch (InvalidCfuUrlException e2) { if (callback != null) { callback.insecureUrl(url, e2); } } catch (Exception e2) { logger.debug("Failed to access " + ZAP_VERSIONS_DEV_XML_FULL, e2); } } if (callback != null && latestVersionInfo != null) { logger.debug("Calling callback with " + latestVersionInfo); callback.gotLatestData(latestVersionInfo); } logger.debug("Done"); } }; this.remoteCallThread.start(); } if (callback == null) { // Synchronous, but include a 30 sec max anyway int i=0; while (latestVersionInfo == null && this.remoteCallThread.isAlive() && i < 30) { try { Thread.sleep(1000); i++; } catch (InterruptedException e) { // Ignore } } } } return latestVersionInfo; } private String getCurrentVersion() { // Put into local function to make it easy to manually test different scenarios;) return Constant.PROGRAM_VERSION; } private Platform getPlatform() { if (Constant.isDailyBuild()) { return Platform.daily; } else if (Constant.isWindows()) { return Platform.windows; } else if (Constant.isLinux()) { return Platform.linux; } else { return Platform.mac; } } protected void promptToLaunchReleaseAndClose(String version, File f) { int ans = View.getSingleton().showConfirmDialog( MessageFormat.format( Constant.messages.getString("cfu.confirm.launch"), version, f.getAbsolutePath())); if (ans == JOptionPane.OK_OPTION) { Control.getSingleton().exit(false, f); } } private void install(AddOn ao) { if (! ao.canLoadInCurrentVersion()) { throw new IllegalArgumentException("Cant load add-on " + ao.getName() + " Not before=" + ao.getNotBeforeVersion() + " Not from=" + ao.getNotFromVersion() + " Version=" + Constant.PROGRAM_VERSION); } AddOn installedAddOn = this.getLocalVersionInfo().getAddOn(ao.getId()); if (installedAddOn != null) { if ( ! uninstallAddOn(null, installedAddOn, true)) { // Cant uninstall the old version, so dont try to install the new one return; } } logger.debug("Installing new addon " + ao.getId() + " v" + ao.getFileVersion()); if (View.isInitialised()) { // Report info to the Output tab View.getSingleton().getOutputPanel().append( MessageFormat.format( Constant.messages.getString("cfu.output.installing") + "\n", ao.getName(), Integer.valueOf(ao.getFileVersion()))); } ExtensionFactory.getAddOnLoader().addAddon(ao); if (latestVersionInfo != null) { AddOn addOn = latestVersionInfo.getAddOn(ao.getId()); if (addOn != null && AddOn.InstallationStatus.DOWNLOADING == addOn.getInstallationStatus()) { addOn.setInstallationStatus(AddOn.InstallationStatus.INSTALLED); } } if (addonsDialog != null) { addonsDialog.notifyAddOnInstalled(ao); } } private boolean uninstall(AddOn addOn, boolean upgrading, AddOnUninstallationProgressCallback callback) { logger.debug("Trying to uninstall addon " + addOn.getId() + " v" + addOn.getFileVersion()); boolean removedDynamically = ExtensionFactory.getAddOnLoader().removeAddOn(addOn, upgrading, callback); if (removedDynamically) { logger.debug("Uninstalled add-on " + addOn.getName()); if (latestVersionInfo != null) { AddOn availableAddOn = latestVersionInfo.getAddOn(addOn.getId()); if (availableAddOn != null && availableAddOn.getInstallationStatus() != AddOn.InstallationStatus.AVAILABLE) { availableAddOn.setInstallationStatus(AddOn.InstallationStatus.AVAILABLE); } } } else { logger.debug("Failed to uninstall add-on " + addOn.getId() + " v" + addOn.getFileVersion()); } return removedDynamically; } @Override public void insecureUrl(String url, Exception cause) { logger.error("Failed to get check for updates on " + url, cause); if (View.isInitialised()) { View.getSingleton().showWarningDialog(Constant.messages.getString("cfu.warn.badurl")); } } @Override public void gotLatestData(AddOnCollection aoc) { if (aoc == null) { return; } try { ZapRelease rel = aoc.getZapRelease(); OptionsParamCheckForUpdates options = getModel().getOptionsParam().getCheckForUpdatesParam(); if (rel.isNewerThan(getCurrentVersion())) { logger.debug("There is a newer release: " + rel.getVersion()); // New ZAP release if (Constant.isKali()) { // Kali has its own package management system if (View.isInitialised()) { getAddOnsDialog().setVisible(true); } return; } File f = new File(Constant.FOLDER_LOCAL_PLUGIN, rel.getFileName()); if (f.exists() && f.length() >= rel.getSize()) { // Already downloaded, prompt to install and exit promptToLaunchReleaseAndClose(rel.getVersion(), f); } else if (options.isDownloadNewRelease()) { logger.debug("Auto-downloading release"); if (downloadLatestRelease() && addonsDialog != null) { addonsDialog.setDownloadingZap(); } } else if (addonsDialog != null) { // Just show the dialog addonsDialog.setVisible(true); } return; } boolean keepChecking = checkForAddOnUpdates(aoc, options); if (keepChecking && addonsDialog != null) { List<AddOn> newAddOns = getNewAddOns(); if (newAddOns.size() > 0) { boolean report = false; for (AddOn addon : newAddOns) { switch (addon.getStatus()) { case alpha: if (options.isReportAlphaAddons()) { report = true; } break; case beta: if (options.isReportBetaAddons()) { report = true; } break; case release: if (options.isReportReleaseAddons()) { report = true; } break; default: break; } } if (report) { getAddOnsDialog().setVisible(true); getAddOnsDialog().selectMarketplaceTab(); } } } } catch (Exception e) { // Ignore (well, debug;), will be already logged logger.debug(e.getMessage(), e); } } private boolean checkForAddOnUpdates(AddOnCollection aoc, OptionsParamCheckForUpdates options) { List<AddOn> updates = getUpdatedAddOns(); if (updates.isEmpty()) { return true; } logger.debug("There is/are " + updates.size() + " newer addons"); AddOnDependencyChecker addOnDependencyChecker = new AddOnDependencyChecker(localVersionInfo, aoc); Set<AddOn> addOns = new HashSet<>(updates); AddOnDependencyChecker.AddOnChangesResult result = addOnDependencyChecker.calculateUpdateChanges(addOns); if (!result.getUninstalls().isEmpty() || result.isNewerJavaVersionRequired()) { if (options.isCheckAddonUpdates()) { if (addonsDialog != null) { // Just show the dialog getAddOnsDialog().setVisible(true); } else { logger.info("Updates not installed some add-ons would be uninstalled or require newer java version: " + result.getUninstalls()); } } return true; } if (options.isInstallAddonUpdates()) { logger.debug("Auto-downloading addons"); processAddOnChanges(null, result); return false; } if (options.isInstallScannerRules()) { for (Iterator<AddOn> it = addOns.iterator(); it.hasNext();) { if (!it.next().getId().contains("scanrules")) { it.remove(); } } logger.debug("Auto-downloading scanner rules"); processAddOnChanges(null, addOnDependencyChecker.calculateUpdateChanges(addOns)); return false; } return true; } /** * Processes the given add-on changes. * * @param caller the caller to set as parent of shown dialogues * @param changes the changes that will be processed */ void processAddOnChanges(Window caller, AddOnDependencyChecker.AddOnChangesResult changes) { if (addonsDialog != null) { addonsDialog.setDownloadingUpdates(); } if (getView() != null) { Set<AddOn> addOns = new HashSet<>(changes.getUninstalls()); addOns.addAll(changes.getOldVersions()); Set<Extension> extensions = new HashSet<>(); extensions.addAll(changes.getUnloadExtensions()); extensions.addAll(changes.getSoftUnloadExtensions()); if (!warnUnsavedResourcesOrActiveActions(caller, addOns, extensions, true)) { return; } } uninstallAddOns(caller, changes.getUninstalls(), false); Set<AddOn> allAddons = new HashSet<>(changes.getNewVersions()); allAddons.addAll(changes.getInstalls()); for (AddOn addOn : allAddons) { if (addonsDialog != null) { addonsDialog.notifyAddOnDownloading(addOn); } downloadAddOn(addOn); } } boolean warnUnsavedResourcesOrActiveActions( Window caller, Collection<AddOn> addOns, Set<Extension> extensions, boolean updating) { Set<AddOn> allAddOns = new HashSet<>(addOns); addDependents(allAddOns); String baseMessagePrefix = updating ? "cfu.update." : "cfu.uninstall."; String unsavedResources = getExtensionsUnsavedResources(addOns, extensions); String activeActions = getExtensionsActiveActions(addOns, extensions); String message = null; if (!unsavedResources.isEmpty()) { if (activeActions.isEmpty()) { message = MessageFormat.format( Constant.messages.getString(baseMessagePrefix + "message.resourcesNotSaved"), unsavedResources); } else { message = MessageFormat.format( Constant.messages.getString(baseMessagePrefix + "message.resourcesNotSavedAndActiveActions"), unsavedResources, activeActions); } } else if (!activeActions.isEmpty()) { message = MessageFormat.format( Constant.messages.getString(baseMessagePrefix + "message.activeActions"), activeActions); } if (message != null && JOptionPane.showConfirmDialog( getWindowParent(caller), message, Constant.PROGRAM_NAME, JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { return false; } return true; } private void addDependents(Set<AddOn> addOns) { for (AddOn availableAddOn : localVersionInfo.getInstalledAddOns()) { if (availableAddOn.dependsOn(addOns) && !addOns.contains(availableAddOn)) { addOns.add(availableAddOn); addDependents(addOns); } } } private Window getWindowParent(Window caller) { if (caller != null) { return caller; } if (addonsDialog != null && addonsDialog.isFocused()) { return addonsDialog; } return getView().getMainFrame(); } /** * Returns all unsaved resources of the given {@code addOns} and {@code extensions} wrapped in {@code <li>} elements or an * empty {@code String} if there are no unsaved resources. * * @param addOns the add-ons that will be queried for unsaved resources * @param extensions the extensions that will be queried for unsaved resources * @return a {@code String} containing all unsaved resources or empty {@code String} if none * @since 2.4.0 * @see Extension#getUnsavedResources() */ private static String getExtensionsUnsavedResources(Collection<AddOn> addOns, Set<Extension> extensions) { List<String> unsavedResources = new ArrayList<>(); for (AddOn addOn : addOns) { for (Extension extension : addOn.getLoadedExtensions()) { List<String> resources = extension.getUnsavedResources(); if (resources != null) { unsavedResources.addAll(resources); } } } for (Extension extension : extensions) { List<String> resources = extension.getUnsavedResources(); if (resources != null) { unsavedResources.addAll(resources); } } return wrapEntriesInLiTags(unsavedResources); } private static String wrapEntriesInLiTags(List<String> entries) { if (entries.isEmpty()) { return ""; } StringBuilder strBuilder = new StringBuilder(entries.size() * 15); for (String entry : entries) { strBuilder.append("<li>"); strBuilder.append(entry); strBuilder.append("</li>"); } return strBuilder.toString(); } /** * Returns all active actions of the given {@code addOns} and {@code extensions} wrapped in {@code <li>} elements or an * empty {@code String} if there are no active actions. * * @param addOns the add-ons that will be queried for active actions * @param extensions the extensions that will be queried for active actions * @return a {@code String} containing all active actions or empty {@code String} if none * @since 2.4.0 * @see Extension#getActiveActions() */ private static String getExtensionsActiveActions(Collection<AddOn> addOns, Set<Extension> extensions) { List<String> activeActions = new ArrayList<>(); for (AddOn addOn : addOns) { for (Extension extension : addOn.getLoadedExtensions()) { List<String> actions = extension.getActiveActions(); if (actions != null) { activeActions.addAll(actions); } } } for (Extension extension : extensions) { List<String> resources = extension.getActiveActions(); if (resources != null) { activeActions.addAll(resources); } } return wrapEntriesInLiTags(activeActions); } private void downloadAddOn(AddOn addOn) { if (AddOn.InstallationStatus.DOWNLOADING == addOn.getInstallationStatus()) { return; } addOn.setInstallationStatus(AddOn.InstallationStatus.DOWNLOADING); downloadFile(addOn.getUrl(), addOn.getFile(), addOn.getSize(), addOn.getHash()); } private boolean uninstallAddOn(Window caller, AddOn addOn, boolean update) { Set<AddOn> addOns = new HashSet<>(); addOns.add(addOn); return uninstallAddOns(caller, addOns, update); } boolean uninstallAddOns(Window caller, Set<AddOn> addOns, boolean updates) { if (addOns == null || addOns.isEmpty()) { return true; } if (getView() != null) { return uninstallAddOnsWithView(caller, addOns, updates, new HashSet<AddOn>()); } final Set<AddOn> failedUninstallations = new HashSet<>(); for (AddOn addOn : addOns) { if (!uninstall(addOn, false, null)) { failedUninstallations.add(addOn); } } if (!failedUninstallations.isEmpty()) { logger.warn("It's recommended to restart ZAP. Not all add-ons were successfully uninstalled: " + failedUninstallations); return false; } return true; } boolean uninstallAddOnsWithView( final Window caller, final Set<AddOn> addOns, final boolean updates, final Set<AddOn> failedUninstallations) { if (addOns == null || addOns.isEmpty()) { return true; } if (!EventQueue.isDispatchThread()) { try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { uninstallAddOnsWithView(caller, addOns, updates, failedUninstallations); } }); } catch (InvocationTargetException | InterruptedException e) { logger.error("Failed to uninstall add-ons:", e); return false; } return failedUninstallations.isEmpty(); } final Window parent = getWindowParent(caller); final UninstallationProgressDialogue waitDialogue = new UninstallationProgressDialogue(parent, addOns); waitDialogue.addAddOnUninstallListener(new AddOnUninstallListener() { @Override public void uninstallingAddOn(AddOn addOn, boolean updating) { if (updating) { String message = MessageFormat.format( Constant.messages.getString("cfu.output.replacing") + "\n", addOn.getName(), Integer.valueOf(addOn.getFileVersion())); getView().getOutputPanel().append(message); } } @Override public void addOnUninstalled(AddOn addOn, boolean update, boolean uninstalled) { if (uninstalled) { if (!update && addonsDialog != null) { addonsDialog.notifyAddOnUninstalled(addOn); } String message = MessageFormat.format( Constant.messages.getString("cfu.output.uninstalled") + "\n", addOn.getName(), Integer.valueOf(addOn.getFileVersion())); getView().getOutputPanel().append(message); } else { if (addonsDialog != null) { addonsDialog.notifyAddOnFailedUninstallation(addOn); } String message; if (update) { message = MessageFormat.format( Constant.messages.getString("cfu.output.replace.failed") + "\n", addOn.getName(), Integer.valueOf(addOn.getFileVersion())); } else { message = MessageFormat.format( Constant.messages.getString("cfu.output.uninstall.failed") + "\n", addOn.getName(), Integer.valueOf(addOn.getFileVersion())); } getView().getOutputPanel().append(message); } } }); SwingWorker<Void, UninstallationProgressEvent> a = new SwingWorker<Void, UninstallationProgressEvent>() { @Override protected void process(List<UninstallationProgressEvent> events) { waitDialogue.update(events); } @Override protected Void doInBackground() { UninstallationProgressHandler progressHandler = new UninstallationProgressHandler() { @Override protected void publishEvent(UninstallationProgressEvent event) { publish(event); } }; for (AddOn addOn : addOns) { if (!uninstall(addOn, updates, progressHandler)) { failedUninstallations.add(addOn); } } if (!failedUninstallations.isEmpty()) { logger.warn("Not all add-ons were successfully uninstalled: " + failedUninstallations); } return null; } }; waitDialogue.bind(a); a.execute(); waitDialogue.setSynchronous(updates); waitDialogue.setVisible(true); return failedUninstallations.isEmpty(); } /** * No database tables used, so all supported */ @Override public boolean supportsDb(String type) { return true; } }
mario-areias/zaproxy
src/org/zaproxy/zap/extension/autoupdate/ExtensionAutoUpdate.java
Java
apache-2.0
45,112
package org.testfun.jee; import org.apache.commons.lang.exception.ExceptionUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.testfun.jee.runner.PersistenceXml; import org.testfun.jee.runner.SingletonDataSource; import static org.hamcrest.CoreMatchers.*; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.sql.*; import java.util.List; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.*; @RunWith(EjbWithMockitoRunner.class) public class EjbWithMockitoRunnerTransactionTest { private static boolean rowAdded; @PersistenceContext private EntityManager entityManager; @Rule public ExpectedException thrown = ExpectedException.none(); @BeforeClass public static void createTables() throws SQLException { dropTables(); try ( Connection connection = DriverManager.getConnection(PersistenceXml.getInstnace().getConnectionUrl()); Statement statement = connection.createStatement() ) { statement.execute("CREATE TABLE duplicates (id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, name VARCHAR(50) NOT NULL UNIQUE)"); } rowAdded = false; } @AfterClass public static void dropTables() throws SQLException { // Must rollback the connection used by the entity manager in order to avoid locks due to inserts done before (recall transactions are never committed). SingletonDataSource.getDataSource().getConnection().rollback(); try ( Connection connection = DriverManager.getConnection(PersistenceXml.getInstnace().getConnectionUrl()); Statement statement = connection.createStatement() ) { statement.execute("DROP TABLE IF EXISTS duplicates"); } } @Test public void test1() { firstAddRowNextVerify(); } @Test public void test2() { firstAddRowNextVerify(); } @Test public void dbThrowDuplicateKey() { entityManager.persist(new Duplicates("kuki")); try { entityManager.persist(new Duplicates("kuki")); } catch (Throwable t) { assertThat(ExceptionUtils.getRootCauseMessage(t), containsString("unique constraint or index violation")); } } @Test public void preUpdate() { Duplicates entity = new Duplicates("kuki"); entityManager.persist(entity); assertNull(entity.getDuplicateName()); entity.setName("puki"); entityManager.flush(); assertEquals(entity.getName(), entity.getDuplicateName()); } /** * This method is used for testing that a transaction is rolled back at the end of a test. * Because the rollback occurs after all @After methods are invoked, the test cannot be done using @After. * Also, there are no guarantees as for the order test methods are called. * This method solves the problem by performing "insert" on the first time it is called and "verify" on the second * time. */ private void firstAddRowNextVerify() { if (rowAdded) { // If a row was already added by a previous run, verify it was rolled back. List rows = entityManager.createQuery("FROM Duplicates AS dups").getResultList(); assertEquals(0, rows.size()); } else { // If no row was added so far (its the first call to this method) than add a row. Duplicates row = new Duplicates("kuki"); entityManager.persist(row); assertThat(row.getId(), not(0)); assertSame(row, entityManager.find(Duplicates.class, row.getId())); rowAdded = true; } } }
michaelyaakoby/testfun
src/test/java/org/testfun/jee/EjbWithMockitoRunnerTransactionTest.java
Java
apache-2.0
3,912
/* * #%L * mosaic-drivers-stubs-kv-common * %% * Copyright (C) 2010 - 2013 Institute e-Austria Timisoara (Romania) * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package eu.mosaic_cloud.drivers.kvstore.riak.interop; import eu.mosaic_cloud.drivers.interop.DriverConnectionData; /** * Generic class holding connection information about a key-value resource driver. * * @author Georgiana Macariu */ public class KvDriverConnectionData extends DriverConnectionData { /** * Creates a new data class * * @param host * the hostname or ip address of the machine running the resource * @param port * the port on which the resource is listening * @param driverName * driver name * @param bucket * bucket name */ public KvDriverConnectionData (final String host, final int port, final String driverName, final String bucket) { super (host, port, driverName); this.bucket = bucket; } /** * Creates a new data class * * @param host * the hostname or ip address of the machine running the resource * @param port * the port on which the resource is listening * @param driverName * driver name * @param user * username for connecting to resource * @param password * password for connecting to resource * @param bucket * bucket name */ public KvDriverConnectionData (final String host, final int port, final String driverName, final String user, final String password, final String bucket) { super (host, port, driverName, user, password); this.bucket = bucket; } @Override public boolean equals (final Object obj) { boolean isEqual = (this == obj); if (!isEqual) { isEqual = (!super.equals (obj)) || (this.getClass () != obj.getClass ()); if (!isEqual) { final KvDriverConnectionData other = (KvDriverConnectionData) obj; isEqual = ((this.bucket == null) && (other.bucket != null)) || ((this.bucket != null) && (!this.bucket.equals (other.bucket))); } isEqual ^= true; } return isEqual; } public String getBucket () { return this.bucket; } @Override public int hashCode () { final int prime = 31; int result = super.hashCode (); result = (prime * result) + ((this.bucket == null) ? 0 : this.bucket.hashCode ()); return result; } private final String bucket; }
mosaic-cloud/mosaic-java-platform
drivers-stubs/riak/src/main/java/eu/mosaic_cloud/drivers/kvstore/riak/interop/KvDriverConnectionData.java
Java
apache-2.0
2,924
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.registry.core.entities.workspacecatalog; import javax.persistence.*; import java.util.List; @Entity @Table(name = "WORKSPACE_NSF_DEMOGRAPHIC") public class NSFDemographicsEntity { private String airavataInternalUserId; private String gender; private List<String> ethnicities; private List<String> races; private List<String> disabilities; private UserProfileEntity userProfile; @Id @Column(name = "AIRAVATA_INTERNAL_USER_ID") public String getAiravataInternalUserId() { return airavataInternalUserId; } public void setAiravataInternalUserId(String userId) { this.airavataInternalUserId = userId; } @Column(name = "GENDER") public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @ElementCollection @CollectionTable(name="NSF_DEMOGRAPHIC_ETHNICITY", joinColumns = @JoinColumn(name="AIRAVATA_INTERNAL_USER_ID")) public List<String> getEthnicities() { return ethnicities; } public void setEthnicities(List<String> ethnicities) { this.ethnicities = ethnicities; } @ElementCollection @CollectionTable(name="NSF_DEMOGRAPHIC_RACE", joinColumns = @JoinColumn(name="AIRAVATA_INTERNAL_USER_ID")) public List<String> getRaces() { return races; } public void setRaces(List<String> races) { this.races = races; } @ElementCollection @CollectionTable(name="NSF_DEMOGRAPHIC_DISABILITY", joinColumns = @JoinColumn(name="AIRAVATA_INTERNAL_USER_ID")) public List<String> getDisabilities() { return disabilities; } public void setDisabilities(List<String> disabilities) { this.disabilities = disabilities; } @OneToOne(targetEntity = UserProfileEntity.class, cascade = CascadeType.ALL) @PrimaryKeyJoinColumn(name = "AIRAVATA_INTERNAL_USER_ID", referencedColumnName = "AIRAVATA_INTERNAL_USER_ID") public UserProfileEntity getUserProfile() { return userProfile; } public void setUserProfile(UserProfileEntity userProfile) { this.userProfile = userProfile; } }
machristie/airavata
modules/registry-refactoring/src/main/java/org/apache/airavata/registry/core/entities/workspacecatalog/NSFDemographicsEntity.java
Java
apache-2.0
3,003
package org.gradle.test.performance.mediummonolithicjavaproject.p380; import org.junit.Test; import static org.junit.Assert.*; public class Test7604 { Production7604 objectUnderTest = new Production7604(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p380/Test7604.java
Java
apache-2.0
2,111
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package opennlp.tools.ml.maxent.io; import java.io.IOException; import java.util.List; import opennlp.tools.ml.model.AbstractModel; import opennlp.tools.ml.model.ComparablePredicate; public abstract class QNModelWriter extends GISModelWriter { public QNModelWriter(AbstractModel model) { super(model); } @Override public void persist() throws IOException { // the type of model (QN) writeUTF("QN"); // the mapping from outcomes to their integer indexes writeInt(OUTCOME_LABELS.length); for (int i = 0; i < OUTCOME_LABELS.length; i++) writeUTF(OUTCOME_LABELS[i]); // the mapping from predicates to the outcomes they contributed to. // The sorting is done so that we actually can write this out more // compactly than as the entire list. ComparablePredicate[] sorted = sortValues(); List<List<ComparablePredicate>> compressed = compressOutcomes(sorted); writeInt(compressed.size()); for (int i = 0; i < compressed.size(); i++) { List<ComparablePredicate> a = compressed.get(i); writeUTF(a.size() + a.get(0).toString()); } // the mapping from predicate names to their integer indexes writeInt(PARAMS.length); for (int i = 0; i < sorted.length; i++) writeUTF(sorted[i].name); // write out the parameters for (int i = 0; i < sorted.length; i++) for (int j = 0; j < sorted[i].params.length; j++) writeDouble(sorted[i].params[j]); close(); } }
Groostav/CMPT880-term-project
intruder/benchs/opennlp/opennlp-tools/src/main/java/opennlp/tools/ml/maxent/io/QNModelWriter.java
Java
apache-2.0
2,310
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.clouddirectory.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.clouddirectory.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * PublishSchemaRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class PublishSchemaRequestProtocolMarshaller implements Marshaller<Request<PublishSchemaRequest>, PublishSchemaRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON) .requestUri("/amazonclouddirectory/2017-01-11/schema/publish").httpMethodName(HttpMethodName.PUT).hasExplicitPayloadMember(false) .hasPayloadMembers(true).serviceName("AmazonCloudDirectory").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public PublishSchemaRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<PublishSchemaRequest> marshall(PublishSchemaRequest publishSchemaRequest) { if (publishSchemaRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<PublishSchemaRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, publishSchemaRequest); protocolMarshaller.startMarshalling(); PublishSchemaRequestMarshaller.getInstance().marshall(publishSchemaRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-clouddirectory/src/main/java/com/amazonaws/services/clouddirectory/model/transform/PublishSchemaRequestProtocolMarshaller.java
Java
apache-2.0
2,681
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.personalize.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.personalize.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * HPOResourceConfigMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class HPOResourceConfigMarshaller { private static final MarshallingInfo<String> MAXNUMBEROFTRAININGJOBS_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("maxNumberOfTrainingJobs").build(); private static final MarshallingInfo<String> MAXPARALLELTRAININGJOBS_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("maxParallelTrainingJobs").build(); private static final HPOResourceConfigMarshaller instance = new HPOResourceConfigMarshaller(); public static HPOResourceConfigMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(HPOResourceConfig hPOResourceConfig, ProtocolMarshaller protocolMarshaller) { if (hPOResourceConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(hPOResourceConfig.getMaxNumberOfTrainingJobs(), MAXNUMBEROFTRAININGJOBS_BINDING); protocolMarshaller.marshall(hPOResourceConfig.getMaxParallelTrainingJobs(), MAXPARALLELTRAININGJOBS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/transform/HPOResourceConfigMarshaller.java
Java
apache-2.0
2,404
package _219_Contains_Duplicate_2; import java.util.HashSet; import java.util.Set; /* Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k. */ public class Solution { public static boolean containsNearbyDuplicate(int[] nums, int k) { Set<Integer> set = new HashSet<>(); for (int i = 0; i < nums.length; i++) { if (i > k) set.remove(nums[i - k - 1]); if (!set.add(nums[i])) return true; } return false; } public static void main(String[] args) { int[] nums = { 1, 2, 3, 1, 5, 6, 7 }; System.out.println(containsNearbyDuplicate(nums, 3)); // true System.out.println(containsNearbyDuplicate(nums, 2)); // false } }
elenore233/LeetCode
LeetCode/src/_219_Contains_Duplicate_2/Solution.java
Java
apache-2.0
821
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.uaa.identityproviders; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** * The file to be used for configuring the LDAP authentication. */ public enum LdapProfileFile { SEARCH_AND_BIND("ldap/ldap-search-and-bind.xml"), SEARCH_AND_COMPARE("ldap/ldap-search-and-compare.xml"), SIMPLE_BIND("ldap/ldap-simple-bind.xml"); private final String value; LdapProfileFile(String value) { this.value = value; } @JsonCreator public static LdapProfileFile from(String s) { switch (s.toLowerCase()) { case "ldap/ldap-search-and-bind.xml": return SEARCH_AND_BIND; case "ldap/ldap-search-and-compare.xml": return SEARCH_AND_COMPARE; case "ldap/ldap-simple-bind.xml": return SIMPLE_BIND; default: throw new IllegalArgumentException(String.format("Unknown ldap profile file: %s", s)); } } @JsonValue public String getValue() { return this.value; } @Override public String toString() { return getValue(); } }
alexander071/cf-java-client
cloudfoundry-client/src/main/java/org/cloudfoundry/uaa/identityproviders/LdapProfileFile.java
Java
apache-2.0
1,819
/** * Copyright (c) 2011-2015, James Zhan 詹波 (jfinal@126.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.iteye.weimingtom.sharuru; import java.io.Serializable; import java.util.List; /** * Page is the result of Model.paginate(......) or Db.paginate(......) */ public class Page<T> implements Serializable { private static final long serialVersionUID = -5395997221963176643L; private List<T> list; // list result of this page private int pageNumber; // page number private int pageSize; // result amount of this page private int totalPage; // total page private int totalRow; // total row /** * Constructor. * @param list the list of paginate result * @param pageNumber the page number * @param pageSize the page size * @param totalPage the total page of paginate * @param totalRow the total row of paginate */ public Page(List<T> list, int pageNumber, int pageSize, int totalPage, int totalRow) { this.list = list; this.pageNumber = pageNumber; this.pageSize = pageSize; this.totalPage = totalPage; this.totalRow = totalRow; } /** * Return list of this page. */ public List<T> getList() { return list; } /** * Return page number. */ public int getPageNumber() { return pageNumber; } /** * Return page size. */ public int getPageSize() { return pageSize; } /** * Return total page. */ public int getTotalPage() { return totalPage; } /** * Return total row. */ public int getTotalRow() { return totalRow; } }
weimingtom/sharuru
src/com/iteye/weimingtom/sharuru/Page.java
Java
apache-2.0
2,061
package org.cucina.engine.config; import org.cucina.engine.event.TransitionEventListener; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; import org.w3c.dom.Element; /** * JAVADOC for Class Level * * @author $Author: $ * @version $Revision: $ */ public class TransitionEventListenerDefinitionParser extends AbstractSingleBeanDefinitionParser { /** * JAVADOC Method Level Comments * * @param element JAVADOC. * @return JAVADOC. */ @Override protected Class<?> getBeanClass(Element element) { return TransitionEventListener.class; } /** * JAVADOC Method Level Comments * * @param element JAVADOC. * @param builder JAVADOC. */ @Override protected void doParse(Element element, BeanDefinitionBuilder builder) { builder.addConstructorArgReference(element.getAttribute("workflowEnvironment")) .addConstructorArgReference(element.getAttribute("tokenRepository")) .addConstructorArgReference(element.getAttribute("domainRepository")); } }
cucina/opencucina
engine/src/main/java/org/cucina/engine/config/TransitionEventListenerDefinitionParser.java
Java
apache-2.0
1,087
package hr.fer.zemris.jcms.web.actions2.course.assessments; import hr.fer.zemris.jcms.service2.course.assessments.SummaryViewService; import hr.fer.zemris.jcms.web.actions.Ext2ActionSupport; import hr.fer.zemris.jcms.web.actions.annotations.WebClass; import hr.fer.zemris.jcms.web.actions.annotations.WebMethodInfo; import hr.fer.zemris.jcms.web.actions.data.AdminAssessmentSummaryViewData; /** * Akcija koja renderira prikaz svih rezultata provjera na kolegiju. * * @author marcupic * */ @WebClass(dataClass=AdminAssessmentSummaryViewData.class) public class AdminAssessmentSummaryView extends Ext2ActionSupport<AdminAssessmentSummaryViewData> { private static final long serialVersionUID = 2L; @WebMethodInfo public String execute() throws Exception { SummaryViewService.showAdminAssessmentSummaryView(getEntityManager(), data); return null; } public String getCourseInstanceID() { return data.getCourseInstanceID(); } public void setCourseInstanceID(String courseInstanceID) { data.setCourseInstanceID(courseInstanceID); } public String getSortKey() { return data.getSortKey(); } public void setSortKey(String sortKey) { data.setSortKey(sortKey); } public Long getSelectedGroup() { return data.getSelectedGroupID(); } public void setSelectedGroup(Long selectedGroup) { data.setSelectedGroupID(selectedGroup); } }
KarloKnezevic/Ferko
src/java/hr/fer/zemris/jcms/web/actions2/course/assessments/AdminAssessmentSummaryView.java
Java
apache-2.0
1,392
/** * generated by Xtext 2.17.1 */ package com.specmate.cause_effect_patterns.internal.specDSL.impl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; import com.specmate.cause_effect_patterns.internal.specDSL.ExplicitNode; import com.specmate.cause_effect_patterns.internal.specDSL.OptionNode; import com.specmate.cause_effect_patterns.internal.specDSL.SpecDSLPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Option Node</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link com.specmate.cause_effect_patterns.specDSL.impl.OptionNodeImpl#getLeftNode <em>Left Node</em>}</li> * <li>{@link com.specmate.cause_effect_patterns.specDSL.impl.OptionNodeImpl#getRightNodes <em>Right Nodes</em>}</li> * </ul> * * @generated */ public class OptionNodeImpl extends NodeImpl implements OptionNode { /** * The cached value of the '{@link #getLeftNode() <em>Left Node</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLeftNode() * @generated * @ordered */ protected ExplicitNode leftNode; /** * The cached value of the '{@link #getRightNodes() <em>Right Nodes</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRightNodes() * @generated * @ordered */ protected EList<ExplicitNode> rightNodes; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected OptionNodeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return SpecDSLPackage.Literals.OPTION_NODE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ExplicitNode getLeftNode() { return leftNode; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetLeftNode(ExplicitNode newLeftNode, NotificationChain msgs) { ExplicitNode oldLeftNode = leftNode; leftNode = newLeftNode; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, SpecDSLPackage.OPTION_NODE__LEFT_NODE, oldLeftNode, newLeftNode); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLeftNode(ExplicitNode newLeftNode) { if (newLeftNode != leftNode) { NotificationChain msgs = null; if (leftNode != null) msgs = ((InternalEObject)leftNode).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - SpecDSLPackage.OPTION_NODE__LEFT_NODE, null, msgs); if (newLeftNode != null) msgs = ((InternalEObject)newLeftNode).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - SpecDSLPackage.OPTION_NODE__LEFT_NODE, null, msgs); msgs = basicSetLeftNode(newLeftNode, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SpecDSLPackage.OPTION_NODE__LEFT_NODE, newLeftNode, newLeftNode)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ExplicitNode> getRightNodes() { if (rightNodes == null) { rightNodes = new EObjectContainmentEList<ExplicitNode>(ExplicitNode.class, this, SpecDSLPackage.OPTION_NODE__RIGHT_NODES); } return rightNodes; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case SpecDSLPackage.OPTION_NODE__LEFT_NODE: return basicSetLeftNode(null, msgs); case SpecDSLPackage.OPTION_NODE__RIGHT_NODES: return ((InternalEList<?>)getRightNodes()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SpecDSLPackage.OPTION_NODE__LEFT_NODE: return getLeftNode(); case SpecDSLPackage.OPTION_NODE__RIGHT_NODES: return getRightNodes(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SpecDSLPackage.OPTION_NODE__LEFT_NODE: setLeftNode((ExplicitNode)newValue); return; case SpecDSLPackage.OPTION_NODE__RIGHT_NODES: getRightNodes().clear(); getRightNodes().addAll((Collection<? extends ExplicitNode>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SpecDSLPackage.OPTION_NODE__LEFT_NODE: setLeftNode((ExplicitNode)null); return; case SpecDSLPackage.OPTION_NODE__RIGHT_NODES: getRightNodes().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SpecDSLPackage.OPTION_NODE__LEFT_NODE: return leftNode != null; case SpecDSLPackage.OPTION_NODE__RIGHT_NODES: return rightNodes != null && !rightNodes.isEmpty(); } return super.eIsSet(featureID); } } //OptionNodeImpl
junkerm/specmate
bundles/specmate-cause-effect-patterns/src/com/specmate/cause_effect_patterns/internal/specDSL/impl/OptionNodeImpl.java
Java
apache-2.0
6,335
package org.estatio.module.budget.dom.api; import java.math.BigDecimal; import org.estatio.module.budget.dom.budgetcalculation.BudgetCalculationType; import org.estatio.module.budget.dom.keytable.PartitioningTable; import org.estatio.module.budget.dom.partioning.PartitionItem; import org.estatio.module.charge.dom.Charge; public interface PartitionItemCreator { PartitionItem updateOrCreatePartitionItem( final BudgetCalculationType budgetCalculationType, final Charge allocationCharge, final PartitioningTable partitioningTable, final BigDecimal percentage, final BigDecimal fixedBudgetedValue, final BigDecimal fixedAuditedValue ); }
estatio/estatio
estatioapp/app/src/main/java/org/estatio/module/budget/dom/api/PartitionItemCreator.java
Java
apache-2.0
722
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.util; import java.util.Collection; import java.util.Collections; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.transforms.GroupByKey; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.transforms.windowing.InvalidWindows; import org.apache.beam.sdk.transforms.windowing.NonMergingWindowFn; import org.apache.beam.sdk.transforms.windowing.Window; import org.apache.beam.sdk.transforms.windowing.WindowFn; import org.apache.beam.sdk.values.PCollection; import org.joda.time.Instant; /** * A {@link WindowFn} that leaves all associations between elements and windows unchanged. * * <p>This {@link WindowFn} is applied when elements must be passed through a {@link GroupByKey}, * but should maintain their existing {@link Window} assignments. Because windows may have been * merged, the earlier {@link WindowFn} may not appropriately maintain the existing window * assignments. For example, if the earlier {@link WindowFn} merges windows, after a * {@link GroupByKey} the {@link WindowingStrategy} uses {@link InvalidWindows}, and no further * {@link GroupByKey} can be applied without applying a new {@link WindowFn}. This {@link WindowFn} * allows existing window assignments to be maintained across a single group by key, at which point * the earlier {@link WindowingStrategy} should be restored. * * <p>This {@link WindowFn} is an internal implementation detail of sdk-provided utilities, and * should not be used by {@link Pipeline} writers. */ class IdentityWindowFn<T> extends NonMergingWindowFn<T, BoundedWindow> { /** * The coder of the type of windows of the input {@link PCollection}. This is not an arbitrary * {@link BoundedWindow} {@link Coder}, but is safe to use for all windows assigned by this * transform, as it should be the same coder used by the {@link WindowFn} that initially assigned * these windows. */ private final Coder<BoundedWindow> coder; public IdentityWindowFn(Coder<? extends BoundedWindow> coder) { // Safe because it is only used privately here. // At every point where a window is returned or accepted, it has been provided // by the prior WindowFn, so it is of the expected type. @SuppressWarnings("unchecked") Coder<BoundedWindow> windowCoder = (Coder<BoundedWindow>) coder; this.coder = windowCoder; } @Override public Collection<BoundedWindow> assignWindows(WindowFn<T, BoundedWindow>.AssignContext c) throws Exception { // The window is provided by the prior WindowFn, which also provides the coder for them return Collections.singleton(c.window()); } @Override public boolean isCompatible(WindowFn<?, ?> other) { throw new UnsupportedOperationException( String.format( "%s.isCompatible() should never be called." + " It is a private implementation detail of sdk utilities." + " This message indicates a bug in the Beam SDK.", getClass().getCanonicalName())); } @Override public Coder<BoundedWindow> windowCoder() { // Safe because the prior WindowFn provides both the windows and the coder. // The Coder is _not_ actually a coder for an arbitrary BoundedWindow. return coder; } @Override public BoundedWindow getSideInputWindow(BoundedWindow window) { throw new UnsupportedOperationException( String.format( "%s.getSideInputWindow() should never be called." + " It is a private implementation detail of sdk utilities." + " This message indicates a bug in the Beam SDK.", getClass().getCanonicalName())); } @Deprecated @Override public Instant getOutputTime(Instant inputTimestamp, BoundedWindow window) { return inputTimestamp; } }
yafengguo/Apache-beam
sdks/java/core/src/main/java/org/apache/beam/sdk/util/IdentityWindowFn.java
Java
apache-2.0
4,672
package com.fsck.k9.backend.pop3; import com.fsck.k9.backend.api.BackendFolder; import com.fsck.k9.backend.api.BackendFolder.MoreMessages; import com.fsck.k9.backend.api.BackendStorage; import com.fsck.k9.backend.api.SyncConfig; import com.fsck.k9.backend.api.SyncListener; import com.fsck.k9.helper.ExceptionHelper; import com.fsck.k9.mail.AuthenticationFailedException; import com.fsck.k9.mail.FetchProfile; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.MessageDownloadState; import com.fsck.k9.mail.MessageRetrievalListener; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.store.pop3.Pop3Folder; import com.fsck.k9.mail.store.pop3.Pop3Message; import com.fsck.k9.mail.store.pop3.Pop3Store; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import timber.log.Timber; class Pop3Sync { private static final String EXTRA_LATEST_OLD_MESSAGE_SEEN_TIME = "latestOldMessageSeenTime"; private final String accountName; private final BackendStorage backendStorage; private final Pop3Store remoteStore; Pop3Sync(String accountName, BackendStorage backendStorage, Pop3Store pop3Store) { this.accountName = accountName; this.backendStorage = backendStorage; this.remoteStore = pop3Store; } void sync(String folder, SyncConfig syncConfig, SyncListener listener) { synchronizeMailboxSynchronous(folder, syncConfig, listener); } void synchronizeMailboxSynchronous(String folder, SyncConfig syncConfig, SyncListener listener) { Pop3Folder remoteFolder = null; Timber.i("Synchronizing folder %s:%s", accountName, folder); BackendFolder backendFolder = null; try { Timber.d("SYNC: About to process pending commands for account %s", accountName); Timber.v("SYNC: About to get local folder %s", folder); backendFolder = backendStorage.getFolder(folder); listener.syncStarted(folder); /* * Get the message list from the local store and create an index of * the uids within the list. */ Map<String, Long> localUidMap = backendFolder.getAllMessagesAndEffectiveDates(); Timber.v("SYNC: About to get remote folder %s", folder); remoteFolder = remoteStore.getFolder(folder); /* * Synchronization process: * Open the folder Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash) Get the message count Get the list of the newest K9.DEFAULT_VISIBLE_LIMIT messages getMessages(messageCount - K9.DEFAULT_VISIBLE_LIMIT, messageCount) See if we have each message locally, if not fetch it's flags and envelope Get and update the unread count for the folder Update the remote flags of any messages we have locally with an internal date newer than the remote message. Get the current flags for any messages we have locally but did not just download Update local flags For any message we have locally but not remotely, delete the local message to keep cache clean. Download larger parts of any new messages. (Optional) Download small attachments in the background. */ /* * Open the remote folder. This pre-loads certain metadata like message count. */ Timber.v("SYNC: About to open remote folder %s", folder); remoteFolder.open(); listener.syncAuthenticationSuccess(); /* * Get the remote message count. */ int remoteMessageCount = remoteFolder.getMessageCount(); int visibleLimit = backendFolder.getVisibleLimit(); if (visibleLimit < 0) { visibleLimit = syncConfig.getDefaultVisibleLimit(); } final List<Pop3Message> remoteMessages = new ArrayList<>(); Map<String, Pop3Message> remoteUidMap = new HashMap<>(); Timber.v("SYNC: Remote message count for folder %s is %d", folder, remoteMessageCount); final Date earliestDate = syncConfig.getEarliestPollDate(); long earliestTimestamp = earliestDate != null ? earliestDate.getTime() : 0L; int remoteStart = 1; if (remoteMessageCount > 0) { /* Message numbers start at 1. */ if (visibleLimit > 0) { remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; } else { remoteStart = 1; } Timber.v("SYNC: About to get messages %d through %d for folder %s", remoteStart, remoteMessageCount, folder); final AtomicInteger headerProgress = new AtomicInteger(0); listener.syncHeadersStarted(folder); List<Pop3Message> remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteMessageCount, null); int messageCount = remoteMessageArray.size(); for (Pop3Message thisMess : remoteMessageArray) { headerProgress.incrementAndGet(); listener.syncHeadersProgress(folder, headerProgress.get(), messageCount); Long localMessageTimestamp = localUidMap.get(thisMess.getUid()); if (localMessageTimestamp == null || localMessageTimestamp >= earliestTimestamp) { remoteMessages.add(thisMess); remoteUidMap.put(thisMess.getUid(), thisMess); } } Timber.v("SYNC: Got %d messages for folder %s", remoteUidMap.size(), folder); listener.syncHeadersFinished(folder, headerProgress.get(), remoteUidMap.size()); } else if (remoteMessageCount < 0) { throw new Exception("Message count " + remoteMessageCount + " for folder " + folder); } /* * Remove any messages that are in the local store but no longer on the remote store or are too old */ MoreMessages moreMessages = backendFolder.getMoreMessages(); if (syncConfig.getSyncRemoteDeletions()) { List<String> destroyMessageUids = new ArrayList<>(); for (String localMessageUid : localUidMap.keySet()) { if (remoteUidMap.get(localMessageUid) == null) { destroyMessageUids.add(localMessageUid); } } if (!destroyMessageUids.isEmpty()) { moreMessages = MoreMessages.UNKNOWN; backendFolder.destroyMessages(destroyMessageUids); for (String uid : destroyMessageUids) { listener.syncRemovedMessage(folder, uid); } } } // noinspection UnusedAssignment, free memory early? (better break up the method!) localUidMap = null; if (moreMessages == MoreMessages.UNKNOWN) { updateMoreMessages(remoteFolder, backendFolder, remoteStart); } /* * Now we download the actual content of messages. */ int newMessages = downloadMessages(syncConfig, remoteFolder, backendFolder, remoteMessages, listener); listener.folderStatusChanged(folder); /* Notify listeners that we're finally done. */ backendFolder.setLastChecked(System.currentTimeMillis()); backendFolder.setStatus(null); Timber.d("Done synchronizing folder %s:%s @ %tc with %d new messages", accountName, folder, System.currentTimeMillis(), newMessages); listener.syncFinished(folder); Timber.i("Done synchronizing folder %s:%s", accountName, folder); } catch (AuthenticationFailedException e) { listener.syncFailed(folder, "Authentication failure", e); } catch (Exception e) { Timber.e(e, "synchronizeMailbox"); // If we don't set the last checked, it can try too often during // failure conditions String rootMessage = ExceptionHelper.getRootCauseMessage(e); if (backendFolder != null) { try { backendFolder.setStatus(rootMessage); backendFolder.setLastChecked(System.currentTimeMillis()); } catch (Exception e1) { Timber.e(e1, "Could not set last checked on folder %s:%s", accountName, folder); } } listener.syncFailed(folder, rootMessage, e); Timber.e("Failed synchronizing folder %s:%s @ %tc", accountName, folder, System.currentTimeMillis()); } finally { if (remoteFolder != null) { remoteFolder.close(); } } } private void updateMoreMessages(Pop3Folder remoteFolder, BackendFolder backendFolder, int remoteStart) { if (remoteStart == 1) { backendFolder.setMoreMessages(MoreMessages.FALSE); } else { boolean moreMessagesAvailable = remoteFolder.areMoreMessagesAvailable(remoteStart); MoreMessages newMoreMessages = (moreMessagesAvailable) ? MoreMessages.TRUE : MoreMessages.FALSE; backendFolder.setMoreMessages(newMoreMessages); } } private int downloadMessages(final SyncConfig syncConfig, final Pop3Folder remoteFolder, final BackendFolder backendFolder, List<Pop3Message> inputMessages, final SyncListener listener) throws MessagingException { final Date earliestDate = syncConfig.getEarliestPollDate(); Date downloadStarted = new Date(); // now if (earliestDate != null) { Timber.d("Only syncing messages after %s", earliestDate); } final String folder = remoteFolder.getServerId(); List<Pop3Message> syncFlagMessages = new ArrayList<>(); List<Pop3Message> unsyncedMessages = new ArrayList<>(); final AtomicInteger newMessages = new AtomicInteger(0); List<Pop3Message> messages = new ArrayList<>(inputMessages); for (Pop3Message message : messages) { evaluateMessageForDownload(message, folder, backendFolder, unsyncedMessages, syncFlagMessages, listener); } final AtomicInteger progress = new AtomicInteger(0); final int todo = unsyncedMessages.size() + syncFlagMessages.size(); listener.syncProgress(folder, progress.get(), todo); Timber.d("SYNC: Have %d unsynced messages", unsyncedMessages.size()); messages.clear(); final List<Pop3Message> largeMessages = new ArrayList<>(); final List<Pop3Message> smallMessages = new ArrayList<>(); if (!unsyncedMessages.isEmpty()) { int visibleLimit = backendFolder.getVisibleLimit(); int listSize = unsyncedMessages.size(); if ((visibleLimit > 0) && (listSize > visibleLimit)) { unsyncedMessages = unsyncedMessages.subList(0, visibleLimit); } FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); Timber.d("SYNC: About to fetch %d unsynced messages for folder %s", unsyncedMessages.size(), folder); fetchUnsyncedMessages(syncConfig, remoteFolder, unsyncedMessages, smallMessages, largeMessages, progress, todo, fp, listener); Timber.d("SYNC: Synced unsynced messages for folder %s", folder); } Timber.d("SYNC: Have %d large messages and %d small messages out of %d unsynced messages", largeMessages.size(), smallMessages.size(), unsyncedMessages.size()); unsyncedMessages.clear(); /* * Grab the content of the small messages first. This is going to * be very fast and at very worst will be a single up of a few bytes and a single * download of 625k. */ FetchProfile fp = new FetchProfile(); //TODO: Only fetch small and large messages if we have some fp.add(FetchProfile.Item.BODY); // fp.add(FetchProfile.Item.FLAGS); // fp.add(FetchProfile.Item.ENVELOPE); downloadSmallMessages(remoteFolder, backendFolder, smallMessages, progress, newMessages, todo, fp, listener); smallMessages.clear(); /* * Now do the large messages that require more round trips. */ fp = new FetchProfile(); fp.add(FetchProfile.Item.STRUCTURE); downloadLargeMessages(syncConfig, remoteFolder, backendFolder, largeMessages, progress, newMessages, todo, fp, listener); largeMessages.clear(); Timber.d("SYNC: Synced remote messages for folder %s, %d new messages", folder, newMessages.get()); // If the oldest message seen on this sync is newer than the oldest message seen on the previous sync, then // we want to move our high-water mark forward. Date oldestMessageTime = backendFolder.getOldestMessageDate(); if (oldestMessageTime != null) { if (oldestMessageTime.before(downloadStarted) && oldestMessageTime.after(getLatestOldMessageSeenTime(backendFolder))) { setLatestOldMessageSeenTime(backendFolder, oldestMessageTime); } } return newMessages.get(); } private Date getLatestOldMessageSeenTime(BackendFolder backendFolder) { Long latestOldMessageSeenTime = backendFolder.getFolderExtraNumber(EXTRA_LATEST_OLD_MESSAGE_SEEN_TIME); long timestamp = latestOldMessageSeenTime != null ? latestOldMessageSeenTime : 0L; return new Date(timestamp); } private void setLatestOldMessageSeenTime(BackendFolder backendFolder, Date oldestMessageTime) { backendFolder.setFolderExtraNumber(EXTRA_LATEST_OLD_MESSAGE_SEEN_TIME, oldestMessageTime.getTime()); } private void evaluateMessageForDownload( final Pop3Message message, final String folder, final BackendFolder backendFolder, final List<Pop3Message> unsyncedMessages, final List<Pop3Message> syncFlagMessages, SyncListener listener) { String messageServerId = message.getUid(); if (message.isSet(Flag.DELETED)) { Timber.v("Message with uid %s is marked as deleted", messageServerId); syncFlagMessages.add(message); return; } boolean messagePresentLocally = backendFolder.isMessagePresent(messageServerId); if (!messagePresentLocally) { if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { Timber.v("Message with uid %s has not yet been downloaded", messageServerId); unsyncedMessages.add(message); } else { Timber.v("Message with uid %s is partially or fully downloaded", messageServerId); // Store the updated message locally boolean completeMessage = message.isSet(Flag.X_DOWNLOADED_FULL); if (completeMessage) { backendFolder.saveMessage(message, MessageDownloadState.FULL); } else { backendFolder.saveMessage(message, MessageDownloadState.PARTIAL); } boolean isOldMessage = isOldMessage(backendFolder, message); listener.syncNewMessage(folder, messageServerId, isOldMessage); } return; } Set<Flag> messageFlags = backendFolder.getMessageFlags(messageServerId); if (!messageFlags.contains(Flag.DELETED)) { Timber.v("Message with uid %s is present in the local store", messageServerId); if (!messageFlags.contains(Flag.X_DOWNLOADED_FULL) && !messageFlags.contains(Flag.X_DOWNLOADED_PARTIAL)) { Timber.v("Message with uid %s is not downloaded, even partially; trying again", messageServerId); unsyncedMessages.add(message); } else { syncFlagMessages.add(message); } } else { Timber.v("Local copy of message with uid %s is marked as deleted", messageServerId); } } private void fetchUnsyncedMessages(final SyncConfig syncConfig, final Pop3Folder remoteFolder, List<Pop3Message> unsyncedMessages, final List<Pop3Message> smallMessages, final List<Pop3Message> largeMessages, final AtomicInteger progress, final int todo, FetchProfile fp, final SyncListener listener) throws MessagingException { final String folder = remoteFolder.getServerId(); final Date earliestDate = syncConfig.getEarliestPollDate(); remoteFolder.fetch(unsyncedMessages, fp, new MessageRetrievalListener<Pop3Message>() { @Override public void messageFinished(Pop3Message message) { try { if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) { if (message.isSet(Flag.DELETED)) { Timber.v("Newly downloaded message %s:%s:%s was marked deleted on server, " + "skipping", accountName, folder, message.getUid()); } else { Timber.d("Newly downloaded message %s is older than %s, skipping", message.getUid(), earliestDate); } progress.incrementAndGet(); //TODO: This might be the source of poll count errors in the UI. Is todo always the same as ofTotal listener.syncProgress(folder, progress.get(), todo); return; } if (syncConfig.getMaximumAutoDownloadMessageSize() > 0 && message.getSize() > syncConfig.getMaximumAutoDownloadMessageSize()) { largeMessages.add(message); } else { smallMessages.add(message); } } catch (Exception e) { Timber.e(e, "Error while storing downloaded message."); } } }, syncConfig.getMaximumAutoDownloadMessageSize()); } private void downloadSmallMessages( final Pop3Folder remoteFolder, final BackendFolder backendFolder, List<Pop3Message> smallMessages, final AtomicInteger progress, final AtomicInteger newMessages, final int todo, FetchProfile fp, final SyncListener listener) throws MessagingException { final String folder = remoteFolder.getServerId(); Timber.d("SYNC: Fetching %d small messages for folder %s", smallMessages.size(), folder); remoteFolder.fetch(smallMessages, fp, new MessageRetrievalListener<Pop3Message>() { @Override public void messageFinished(final Pop3Message message) { try { // Store the updated message locally backendFolder.saveMessage(message, MessageDownloadState.FULL); progress.incrementAndGet(); // Increment the number of "new messages" if the newly downloaded message is // not marked as read. if (!message.isSet(Flag.SEEN)) { newMessages.incrementAndGet(); } String messageServerId = message.getUid(); Timber.v("About to notify listeners that we got a new small message %s:%s:%s", accountName, folder, messageServerId); // Update the listener with what we've found listener.syncProgress(folder, progress.get(), todo); boolean isOldMessage = isOldMessage(backendFolder, message); listener.syncNewMessage(folder, messageServerId, isOldMessage); } catch (Exception e) { Timber.e(e, "SYNC: fetch small messages"); } } }, -1); Timber.d("SYNC: Done fetching small messages for folder %s", folder); } private boolean isOldMessage(BackendFolder backendFolder, Pop3Message message) { return message.olderThan(getLatestOldMessageSeenTime(backendFolder)); } private void downloadLargeMessages( final SyncConfig syncConfig, final Pop3Folder remoteFolder, final BackendFolder backendFolder, List<Pop3Message> largeMessages, final AtomicInteger progress, final AtomicInteger newMessages, final int todo, FetchProfile fp, SyncListener listener) throws MessagingException { final String folder = remoteFolder.getServerId(); Timber.d("SYNC: Fetching large messages for folder %s", folder); int maxDownloadSize = syncConfig.getMaximumAutoDownloadMessageSize(); remoteFolder.fetch(largeMessages, fp, null, maxDownloadSize); for (Pop3Message message : largeMessages) { downloadSaneBody(syncConfig, remoteFolder, backendFolder, message); String messageServerId = message.getUid(); Timber.v("About to notify listeners that we got a new large message %s:%s:%s", accountName, folder, messageServerId); // Update the listener with what we've found progress.incrementAndGet(); // TODO do we need to re-fetch this here? Set<Flag> flags = backendFolder.getMessageFlags(messageServerId); // Increment the number of "new messages" if the newly downloaded message is // not marked as read. if (!flags.contains(Flag.SEEN)) { newMessages.incrementAndGet(); } listener.syncProgress(folder, progress.get(), todo); boolean isOldMessage = isOldMessage(backendFolder, message); listener.syncNewMessage(folder, messageServerId, isOldMessage); } Timber.d("SYNC: Done fetching large messages for folder %s", folder); } private void downloadSaneBody(SyncConfig syncConfig, Pop3Folder remoteFolder, BackendFolder backendFolder, Pop3Message message) throws MessagingException { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ int maxDownloadSize = syncConfig.getMaximumAutoDownloadMessageSize(); remoteFolder.fetch(Collections.singletonList(message), fp, null, maxDownloadSize); boolean completeMessage = false; // Certain (POP3) servers give you the whole message even when you ask for only the first x Kb if (!message.isSet(Flag.X_DOWNLOADED_FULL)) { /* * Mark the message as fully downloaded if the message size is smaller than * the account's autodownload size limit, otherwise mark as only a partial * download. This will prevent the system from downloading the same message * twice. * * If there is no limit on autodownload size, that's the same as the message * being smaller than the max size */ if (syncConfig.getMaximumAutoDownloadMessageSize() == 0 || message.getSize() < syncConfig.getMaximumAutoDownloadMessageSize()) { completeMessage = true; } } // Store the updated message locally if (completeMessage) { backendFolder.saveMessage(message, MessageDownloadState.FULL); } else { backendFolder.saveMessage(message, MessageDownloadState.PARTIAL); } } }
k9mail/k-9
backend/pop3/src/main/java/com/fsck/k9/backend/pop3/Pop3Sync.java
Java
apache-2.0
25,663
package com.android.busolo.apps.wardrobe.engine; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.android.busolo.apps.wardrobe.sync.SyncHelper; import com.android.busolo.apps.wardrobe.utils.AccountUtils; import com.android.busolo.apps.wardrobe.utils.LogUtils; import com.android.busolo.apps.wardrobe.utils.PrefUtils; import com.android.busolo.apps.wardrobe.utils.UIUtils; import static com.android.busolo.apps.wardrobe.utils.LogUtils.makeLogTag; public class BaseActivity extends ActionBarActivity { private static final String TAG = makeLogTag(BaseActivity.class); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //TODO check logged-in status if (!AccountUtils.isAuthenticated(this) || !PrefUtils.isSetupDone(this)) { LogUtils.LOGE(TAG, "exiting:" + " isAuthenticated=" + AccountUtils.isAuthenticated(this) + " isSetupDone=" + PrefUtils.isSetupDone(this)); AccountUtils.startAuthenticationFlow(this, getIntent());//IF NO auth DO finish(); } } protected void setHasTabs() { if (!UIUtils.isTablet(this) && getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) { // Only show the tab bar's shadow getSupportActionBar().setBackgroundDrawable( new ColorDrawable(getResources().getColor(R.color.accent_1))); } } @Override protected void onResume() { super.onResume(); } @Override public void onStart() { super.onStart(); } @Override public void onStop() { super.onStop(); } }
BitCypher2014/Wardrobe_app
wardrobe/src/main/java/com/android/busolo/apps/wardrobe/engine/BaseActivity.java
Java
apache-2.0
2,074
/* * Copyright 2008 - 2016 Arne Limburg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions * and limitations under the License. */ package org.jpasecurity.collection; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.RollbackException; import org.jpasecurity.model.ChildTestBean; import org.jpasecurity.model.FieldAccessAnnotationTestBean; import org.jpasecurity.model.MethodAccessAnnotationTestBean; import org.jpasecurity.model.ParentTestBean; import org.jpasecurity.model.SimpleEmbeddable; import org.jpasecurity.security.authentication.TestSecurityContext; import org.jpasecurity.util.ReflectionUtils; import org.junit.After; import org.junit.Ignore; import org.junit.Test; /** * @author Arne Limburg */ public class PropertyAccessTest { public static final String USER1 = "user1"; public static final String USER2 = "user2"; private static final String ADMIN = "admin"; @Test public void queryWithEmbeddedResult() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("annotation-based-field-access"); EntityManager entityManager = factory.createEntityManager(); TestSecurityContext.authenticate(ADMIN, ADMIN); entityManager.getTransaction().begin(); FieldAccessAnnotationTestBean bean = new FieldAccessAnnotationTestBean(USER1); bean.setSimpleEmbeddable(new SimpleEmbeddable(USER1)); bean.getChildBeans().add(new FieldAccessAnnotationTestBean(USER1, bean)); bean.getChildBeans().add(new FieldAccessAnnotationTestBean(USER2, bean)); entityManager.persist(bean); FieldAccessAnnotationTestBean inaccessibleBean = new FieldAccessAnnotationTestBean(USER2); inaccessibleBean.setSimpleEmbeddable(new SimpleEmbeddable(USER2)); entityManager.persist(inaccessibleBean); entityManager.getTransaction().commit(); entityManager.close(); entityManager = factory.createEntityManager(); TestSecurityContext.authenticate(USER1); SimpleEmbeddable result = entityManager.createNamedQuery("findEmbeddableById", SimpleEmbeddable.class) .setParameter("id", bean.getIdentifier()) .getSingleResult(); assertThat(result.getName(), is(USER1)); List<SimpleEmbeddable> emptyResult = entityManager.createNamedQuery("findEmbeddableById", SimpleEmbeddable.class) .setParameter("id", inaccessibleBean.getIdentifier()) .getResultList(); assertThat(emptyResult, hasSize(0)); entityManager.close(); factory.close(); } @Ignore @Test public void navigateOneToMany() { TestSecurityContext.authenticate(ADMIN, ADMIN); EntityManagerFactory factory = Persistence.createEntityManagerFactory("annotation-based-field-access"); EntityManager entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); FieldAccessAnnotationTestBean bean = new FieldAccessAnnotationTestBean(USER1); bean.getChildBeans().add(new FieldAccessAnnotationTestBean(USER1, bean)); bean.getChildBeans().add(new FieldAccessAnnotationTestBean(USER2, bean)); entityManager.persist(bean); entityManager.getTransaction().commit(); entityManager.close(); entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); TestSecurityContext.authenticate(USER1); bean = entityManager.find(FieldAccessAnnotationTestBean.class, bean.getIdentifier()); assertEquals(1, bean.getChildBeans().size()); assertEquals(USER1, bean.getChildBeans().get(0).getBeanName()); assertEquals(2, ((SecureList<FieldAccessAnnotationTestBean>)bean.getChildBeans()).getOriginal().size()); entityManager.getTransaction().commit(); entityManager.close(); factory.close(); } @Ignore @Test public void methodBasedMapping() { TestSecurityContext.authenticate(ADMIN, ADMIN); EntityManagerFactory factory = Persistence.createEntityManagerFactory("annotation-based-method-access"); EntityManager entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); MethodAccessAnnotationTestBean bean = new MethodAccessAnnotationTestBean(); bean.getChildren().add(new MethodAccessAnnotationTestBean()); bean.getChildren().add(new MethodAccessAnnotationTestBean()); entityManager.persist(bean); entityManager.getTransaction().commit(); entityManager.close(); EntityManager entityManager2 = factory.createEntityManager(); entityManager2.getTransaction().begin(); final MethodAccessAnnotationTestBean bean2 = entityManager2.find(MethodAccessAnnotationTestBean.class, bean.getId()); for (MethodAccessAnnotationTestBean methodAccessAnnotationTestBean: bean2.getChildren()) { methodAccessAnnotationTestBean.getId(); } entityManager2.getTransaction().commit(); } @Test public void oneToManyMapping() { TestSecurityContext.authenticate(ADMIN, ADMIN); EntityManagerFactory factory = Persistence.createEntityManagerFactory("parent-child"); EntityManager entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); ParentTestBean bean = new ParentTestBean(USER1); bean.getChildren().add(new ChildTestBean(USER1)); bean.getChildren().add(new ChildTestBean(USER2)); bean = entityManager.merge(bean); entityManager.getTransaction().commit(); entityManager.close(); entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); TestSecurityContext.authenticate(USER1); bean = entityManager.find(ParentTestBean.class, bean.getId()); assertEquals(1, bean.getChildren().size()); assertEquals(USER1, bean.getChildren().get(0).getName()); entityManager.getTransaction().commit(); entityManager.close(); } @Test public void identityMapping() { TestSecurityContext.authenticate(ADMIN, ADMIN); EntityManagerFactory factory = Persistence.createEntityManagerFactory("parent-child"); EntityManager entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); ParentTestBean bean = new ParentTestBean(USER1); bean.getChildren().add(new ChildTestBean(USER1)); bean.getChildren().add(new ChildTestBean(USER2)); entityManager.persist(bean); entityManager.getTransaction().commit(); entityManager.close(); final EntityManager entityManager2 = factory.createEntityManager(); entityManager2.getTransaction().begin(); final ParentTestBean bean2 = entityManager2.find(ParentTestBean.class, bean.getId()); bean2.setId(bean2.getId()); bean2.setName(bean2.getName()); bean2.setChildren(bean2.getChildren()); for (ChildTestBean child: bean2.getChildren()) { child.setName(child.getName()); } entityManager2.getTransaction().commit(); entityManager2.close(); EntityManager entityManager3 = factory.createEntityManager(); entityManager3.getTransaction().begin(); ParentTestBean bean3 = entityManager3.find(ParentTestBean.class, bean.getId()); assertEquals(1, bean3.getVersion()); entityManager3.getTransaction().commit(); entityManager3.close(); } @Ignore @Test public void update() { TestSecurityContext.authenticate(USER1); EntityManagerFactory factory = Persistence.createEntityManagerFactory("annotation-based-field-access"); EntityManager entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); FieldAccessAnnotationTestBean bean = new FieldAccessAnnotationTestBean(USER1); entityManager.persist(bean); entityManager.getTransaction().commit(); entityManager.close(); try { try { entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); bean = entityManager.find(FieldAccessAnnotationTestBean.class, bean.getIdentifier()); bean.setBeanName(USER2); entityManager.getTransaction().commit(); entityManager.close(); fail("should have thrown exception, since we are not allowed to see beans with name " + USER2); } catch (RollbackException e) { ReflectionUtils.throwThrowable(e.getCause()); } } catch (SecurityException e) { //expected } entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); bean = entityManager.find(FieldAccessAnnotationTestBean.class, bean.getIdentifier()); TestSecurityContext.authenticate(USER2); bean.setBeanName(USER2); entityManager.getTransaction().commit(); entityManager.close(); TestSecurityContext.authenticate(USER1); entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); try { entityManager.find(FieldAccessAnnotationTestBean.class, bean.getIdentifier()); } catch (SecurityException e) { //expected } entityManager.getTransaction().rollback(); entityManager.close(); TestSecurityContext.authenticate(USER2); entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); bean = entityManager.find(FieldAccessAnnotationTestBean.class, bean.getIdentifier()); entityManager.getTransaction().commit(); entityManager.close(); assertEquals(USER2, bean.getBeanName()); } @Ignore @Test public void fieldBasedPropertyAccessCount() { TestSecurityContext.authenticate(USER1); EntityManagerFactory factory = Persistence.createEntityManagerFactory("annotation-based-field-access"); EntityManager entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); FieldAccessAnnotationTestBean bean = new FieldAccessAnnotationTestBean(USER1); entityManager.persist(bean); entityManager.getTransaction().commit(); entityManager.close(); entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); bean = entityManager.find(FieldAccessAnnotationTestBean.class, bean.getIdentifier()); assertEquals(0, bean.getNamePropertyReadCount()); assertEquals(0, bean.getNamePropertyWriteCount()); bean.getBeanName(); assertEquals(1, bean.getNamePropertyReadCount()); assertEquals(0, bean.getNamePropertyWriteCount()); bean.setBeanName(USER1); assertEquals(1, bean.getNamePropertyReadCount()); assertEquals(1, bean.getNamePropertyWriteCount()); bean.aBusinessMethodThatDoesNothing(); assertEquals(1, bean.getNamePropertyReadCount()); assertEquals(1, bean.getNamePropertyWriteCount()); entityManager.getTransaction().commit(); assertEquals(1, bean.getNamePropertyReadCount()); assertEquals(1, bean.getNamePropertyWriteCount()); entityManager.close(); } @Ignore @Test public void methodBasedPropertyAccessCount() { TestSecurityContext.authenticate(USER1); EntityManagerFactory factory = Persistence.createEntityManagerFactory("annotation-based-method-access"); EntityManager entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); MethodAccessAnnotationTestBean bean = new MethodAccessAnnotationTestBean(); bean.setName(USER1); entityManager.persist(bean); entityManager.getTransaction().commit(); entityManager.close(); entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); bean = entityManager.find(MethodAccessAnnotationTestBean.class, bean.getId()); assertTrue(bean.getNamePropertyReadCount() < 2); assertEquals(1, bean.getNamePropertyWriteCount()); bean.getName(); assertTrue(bean.getNamePropertyReadCount() < 3); assertEquals(1, bean.getNamePropertyWriteCount()); bean.setName(USER1); assertTrue(bean.getNamePropertyReadCount() < 3); assertEquals(2, bean.getNamePropertyWriteCount()); bean.aBusinessMethodThatDoesNothing(); assertTrue(bean.getNamePropertyReadCount() < 3); assertEquals(2, bean.getNamePropertyWriteCount()); bean.setParent(null); assertTrue(bean.getNamePropertyReadCount() < 3); assertEquals(2, bean.getNamePropertyWriteCount()); entityManager.getTransaction().commit(); entityManager.close(); } @After public void logout() { TestSecurityContext.authenticate(null); } }
ArneLimburg/jpasecurity
src/test/java/org/jpasecurity/collection/PropertyAccessTest.java
Java
apache-2.0
14,013
package com.fc.platform.mybatis.page; import com.fc.platform.commons.page.PageRequest; import com.fc.platform.commons.page.Pageable; import com.fc.platform.mybatis.page.dialect.MysqlDialect; import com.fc.platform.mybatis.page.util.PageUtils; import com.fc.platform.mybatis.page.dialect.Dialect; import com.fc.platform.mybatis.page.dialect.OracleDialect; import com.fc.platform.mybatis.page.util.ReflectUtil; import org.apache.ibatis.executor.ErrorContext; import org.apache.ibatis.executor.ExecutorException; import org.apache.ibatis.executor.statement.RoutingStatementHandler; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.mapping.ParameterMode; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.property.PropertyTokenizer; import org.apache.ibatis.scripting.xmltags.ForEachSqlNode; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.type.TypeHandler; import org.apache.ibatis.type.TypeHandlerRegistry; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Properties; @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})}) public class PaginationInterception implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget(); StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handler, "delegate"); BoundSql boundSql = delegate.getBoundSql(); PageUtils.Param pageMap = PageUtils.getPageMap(boundSql); if (pageMap != null) { Pageable pageable = (Pageable) pageMap.getEntry().getValue(); Configuration configuration = (Configuration) ReflectUtil.getFieldValue(delegate, "configuration"); MappedStatement mappedStatement = (MappedStatement) ReflectUtil.getFieldValue(delegate, "mappedStatement"); Connection connection = (Connection) invocation.getArgs()[0]; totalCount(connection, boundSql, configuration, mappedStatement, pageable); ReflectUtil.setFieldValue(boundSql, "sql", searchDialectByDbTypeEnum(configuration, pageable).spellPageSql(boundSql.getSql(), pageable.getOffset(), pageable.getPageSize())); } return invocation.proceed(); } /** * 获取总页数 * * @param conn * @param orgBoundSql * @param configuration * @param mappedStatement * @return * @throws java.sql.SQLException */ private void totalCount(Connection conn, BoundSql orgBoundSql, Configuration configuration, MappedStatement mappedStatement, Pageable pageable) throws SQLException { int totalCount = 0; String countSpellSql = searchDialectByDbTypeEnum(configuration, pageable).getCountSql(orgBoundSql.getSql()); PreparedStatement preparedStatement = conn.prepareStatement(countSpellSql); Object parameterObject = orgBoundSql.getParameterObject(); BoundSql boundSql = new BoundSql(configuration, countSpellSql, orgBoundSql.getParameterMappings(), parameterObject); setParameters(preparedStatement, mappedStatement, boundSql, parameterObject); ResultSet rs = preparedStatement.executeQuery(); if (rs != null) { if (rs.next()) { totalCount = rs.getInt(1); PageRequest pageRequest = (PageRequest) pageable; pageRequest.setTotalElements(totalCount); } } } @SuppressWarnings({"rawtypes", "unchecked"}) private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException { ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId()); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); if (parameterMappings != null) { Configuration configuration = mappedStatement.getConfiguration(); TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject); for (int i = 0; i < parameterMappings.size(); i++) { ParameterMapping parameterMapping = parameterMappings.get(i); if (parameterMapping.getMode() != ParameterMode.OUT) { Object value; String propertyName = parameterMapping.getProperty(); PropertyTokenizer prop = new PropertyTokenizer(propertyName); if (parameterObject == null) { value = null; } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { value = parameterObject; } else if (boundSql.hasAdditionalParameter(propertyName)) { value = boundSql.getAdditionalParameter(propertyName); } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX) && boundSql.hasAdditionalParameter(prop.getName())) { value = boundSql.getAdditionalParameter(prop.getName()); if (value != null) { value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length())); } } else { value = metaObject == null ? null : metaObject.getValue(propertyName); } TypeHandler typeHandler = parameterMapping.getTypeHandler(); if (typeHandler == null) { throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId()); } typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType()); } } } } /** * 获取方言对象 * * @param pageable * @return */ private Dialect searchDialectByDbTypeEnum(Configuration configuration, Pageable pageable) { Dialect dialect = null; switch (searchDbTypeByConfig(configuration)) { case MYSQL: dialect = new MysqlDialect(pageable.getSort()); break; case SQLSERVER: break; case DB2: //TODO break; default: dialect = new OracleDialect(pageable.getSort()); break; } return dialect; } /** * 获取数据库类型 * * @return 返回数据库类型的枚举对象 */ private Dialect.Type searchDbTypeByConfig(Configuration configuration) { String dialectConfig = configuration.getVariables().getProperty("sqlType"); if (dialectConfig != null && !"".equals(dialectConfig)) { return Dialect.Type.valueOf(dialectConfig.toUpperCase()); } else { throw new RuntimeException( "databaseType is null , please check your mybatis configuration!"); } } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties properties) { } }
tryndamere/platform
platform-config/src/main/java/com/fc/platform/mybatis/page/PaginationInterception.java
Java
apache-2.0
7,811
package com.fenfei.she.pethospital.beans.manager; import com.fenfei.she.pethospital.beans.BaseEntity; import javax.persistence.*; /** * author shefenfei * description 角色 * time 2015年6月12日 14:24:14 */ @Entity @Table(name = "tb_role") public class Role extends BaseEntity { /** * 角色id */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int roleId; /** * 角色名 */ @Column(name = "roleName",length = 25,nullable = true) private String roleName; public int getRoleId() { return roleId; } public void setRoleId(int roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } }
shefenfei/PetHospital
src/main/java/com/fenfei/she/pethospital/beans/manager/Role.java
Java
apache-2.0
822
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/datalabeling/v1beta1/operations.proto package com.google.cloud.datalabeling.v1beta1; /** * * * <pre> * Details of a LabelImageOrientedBoundingBox operation metadata. * </pre> * * Protobuf type {@code * google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata} */ public final class LabelImageOrientedBoundingBoxOperationMetadata extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata) LabelImageOrientedBoundingBoxOperationMetadataOrBuilder { private static final long serialVersionUID = 0L; // Use LabelImageOrientedBoundingBoxOperationMetadata.newBuilder() to construct. private LabelImageOrientedBoundingBoxOperationMetadata( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private LabelImageOrientedBoundingBoxOperationMetadata() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new LabelImageOrientedBoundingBoxOperationMetadata(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private LabelImageOrientedBoundingBoxOperationMetadata( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig.Builder subBuilder = null; if (basicConfig_ != null) { subBuilder = basicConfig_.toBuilder(); } basicConfig_ = input.readMessage( com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(basicConfig_); basicConfig_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.Operations .internal_static_google_cloud_datalabeling_v1beta1_LabelImageOrientedBoundingBoxOperationMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.Operations .internal_static_google_cloud_datalabeling_v1beta1_LabelImageOrientedBoundingBoxOperationMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata .class, com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata .Builder.class); } public static final int BASIC_CONFIG_FIELD_NUMBER = 1; private com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basicConfig_; /** * * * <pre> * Basic human annotation config. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code> * * @return Whether the basicConfig field is set. */ @java.lang.Override public boolean hasBasicConfig() { return basicConfig_ != null; } /** * * * <pre> * Basic human annotation config. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code> * * @return The basicConfig. */ @java.lang.Override public com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig getBasicConfig() { return basicConfig_ == null ? com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig.getDefaultInstance() : basicConfig_; } /** * * * <pre> * Basic human annotation config. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code> */ @java.lang.Override public com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfigOrBuilder getBasicConfigOrBuilder() { return getBasicConfig(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (basicConfig_ != null) { output.writeMessage(1, getBasicConfig()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (basicConfig_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getBasicConfig()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata)) { return super.equals(obj); } com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata other = (com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata) obj; if (hasBasicConfig() != other.hasBasicConfig()) return false; if (hasBasicConfig()) { if (!getBasicConfig().equals(other.getBasicConfig())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasBasicConfig()) { hash = (37 * hash) + BASIC_CONFIG_FIELD_NUMBER; hash = (53 * hash) + getBasicConfig().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Details of a LabelImageOrientedBoundingBox operation metadata. * </pre> * * Protobuf type {@code * google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata) com.google.cloud.datalabeling.v1beta1 .LabelImageOrientedBoundingBoxOperationMetadataOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.Operations .internal_static_google_cloud_datalabeling_v1beta1_LabelImageOrientedBoundingBoxOperationMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.Operations .internal_static_google_cloud_datalabeling_v1beta1_LabelImageOrientedBoundingBoxOperationMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata .class, com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata .Builder.class); } // Construct using // com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); if (basicConfigBuilder_ == null) { basicConfig_ = null; } else { basicConfig_ = null; basicConfigBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.datalabeling.v1beta1.Operations .internal_static_google_cloud_datalabeling_v1beta1_LabelImageOrientedBoundingBoxOperationMetadata_descriptor; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata getDefaultInstanceForType() { return com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata .getDefaultInstance(); } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata build() { com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata buildPartial() { com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata result = new com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata( this); if (basicConfigBuilder_ == null) { result.basicConfig_ = basicConfig_; } else { result.basicConfig_ = basicConfigBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata) { return mergeFrom( (com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata other) { if (other == com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata .getDefaultInstance()) return this; if (other.hasBasicConfig()) { mergeBasicConfig(other.getBasicConfig()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basicConfig_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig, com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig.Builder, com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfigOrBuilder> basicConfigBuilder_; /** * * * <pre> * Basic human annotation config. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code> * * @return Whether the basicConfig field is set. */ public boolean hasBasicConfig() { return basicConfigBuilder_ != null || basicConfig_ != null; } /** * * * <pre> * Basic human annotation config. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code> * * @return The basicConfig. */ public com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig getBasicConfig() { if (basicConfigBuilder_ == null) { return basicConfig_ == null ? com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig.getDefaultInstance() : basicConfig_; } else { return basicConfigBuilder_.getMessage(); } } /** * * * <pre> * Basic human annotation config. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code> */ public Builder setBasicConfig( com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig value) { if (basicConfigBuilder_ == null) { if (value == null) { throw new NullPointerException(); } basicConfig_ = value; onChanged(); } else { basicConfigBuilder_.setMessage(value); } return this; } /** * * * <pre> * Basic human annotation config. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code> */ public Builder setBasicConfig( com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig.Builder builderForValue) { if (basicConfigBuilder_ == null) { basicConfig_ = builderForValue.build(); onChanged(); } else { basicConfigBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Basic human annotation config. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code> */ public Builder mergeBasicConfig( com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig value) { if (basicConfigBuilder_ == null) { if (basicConfig_ != null) { basicConfig_ = com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig.newBuilder(basicConfig_) .mergeFrom(value) .buildPartial(); } else { basicConfig_ = value; } onChanged(); } else { basicConfigBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Basic human annotation config. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code> */ public Builder clearBasicConfig() { if (basicConfigBuilder_ == null) { basicConfig_ = null; onChanged(); } else { basicConfig_ = null; basicConfigBuilder_ = null; } return this; } /** * * * <pre> * Basic human annotation config. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig.Builder getBasicConfigBuilder() { onChanged(); return getBasicConfigFieldBuilder().getBuilder(); } /** * * * <pre> * Basic human annotation config. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfigOrBuilder getBasicConfigOrBuilder() { if (basicConfigBuilder_ != null) { return basicConfigBuilder_.getMessageOrBuilder(); } else { return basicConfig_ == null ? com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig.getDefaultInstance() : basicConfig_; } } /** * * * <pre> * Basic human annotation config. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig, com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig.Builder, com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfigOrBuilder> getBasicConfigFieldBuilder() { if (basicConfigBuilder_ == null) { basicConfigBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig, com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig.Builder, com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfigOrBuilder>( getBasicConfig(), getParentForChildren(), isClean()); basicConfig_ = null; } return basicConfigBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata) } // @@protoc_insertion_point(class_scope:google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata) private static final com.google.cloud.datalabeling.v1beta1 .LabelImageOrientedBoundingBoxOperationMetadata DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata(); } public static com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<LabelImageOrientedBoundingBoxOperationMetadata> PARSER = new com.google.protobuf.AbstractParser<LabelImageOrientedBoundingBoxOperationMetadata>() { @java.lang.Override public LabelImageOrientedBoundingBoxOperationMetadata parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new LabelImageOrientedBoundingBoxOperationMetadata(input, extensionRegistry); } }; public static com.google.protobuf.Parser<LabelImageOrientedBoundingBoxOperationMetadata> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<LabelImageOrientedBoundingBoxOperationMetadata> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.LabelImageOrientedBoundingBoxOperationMetadata getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/java-datalabeling
proto-google-cloud-datalabeling-v1beta1/src/main/java/com/google/cloud/datalabeling/v1beta1/LabelImageOrientedBoundingBoxOperationMetadata.java
Java
apache-2.0
27,309
/** * ClassName: ServiceException * CopyRight: TalkWeb * Date: 12-11-21 * Version: 1.0 */ package com.titian.cms.exception; import com.titian.cms.common.ErrorCode; /** * Description : 服务异常 * User : 康维 */ public class ServiceException extends RuntimeException { private ErrorCode errorCode; public ErrorCode getErrorCode() { return errorCode; } public void setErrorCode(ErrorCode errorCode) { this.errorCode = errorCode; } public ServiceException() { super(); } public ServiceException(String message) { super(message); } public ServiceException(ErrorCode code) { super(); setErrorCode(code); } public ServiceException(ErrorCode code, String message) { super(message); setErrorCode(code); } public ServiceException(ErrorCode code, Throwable cause) { super(cause); setErrorCode(code); } public ServiceException(String message, Throwable cause) { super(message, cause); } public ServiceException(Throwable cause) { super(cause); } }
kangwei/kindergarten
kindergarten/cms_server/src/main/java/com/titian/cms/exception/ServiceException.java
Java
apache-2.0
1,189
/* * Copyright 2016 Kamil Becmer <kamil.becmer at maisica.pl>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.maisica.time.span; import java.time.Duration; import java.time.LocalDate; import java.time.Period; import java.time.format.DateTimeParseException; import java.util.Objects; import net.maisica.time.interval.DateInterval; public final class DateSpan extends AbstractSpan<LocalDate, DateSpan> implements TemporalSpan<LocalDate> { public static DateSpan parse(final CharSequence text) { Objects.requireNonNull(text, "text"); for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '/') { final LocalDate start = LocalDate.parse(text.subSequence(0, i++).toString()); final Duration duration = Duration.parse(text.subSequence(i, text.length()).toString()); return of(start, duration); } } throw new DateTimeParseException("Span cannot be parsed, no forward slash found", text, 0); } public static DateSpan of(final Span<LocalDate, Duration> span) { Objects.requireNonNull(span, "span"); if (span instanceof DateSpan) { return (DateSpan) span; } return of(span.getStart(), span.getDuration()); } public static DateSpan of(final LocalDate start, final Duration duration) { Objects.requireNonNull(start, "start"); Objects.requireNonNull(duration, "duration"); if (duration.isNegative()) { throw new IllegalArgumentException("duration is negative"); } return new DateSpan(start, duration); } private DateSpan(final LocalDate start, final Duration duration) { super(start, duration); } @Override protected SpanFactory<LocalDate, Duration, DateSpan> getFactory() { return DateSpan::new; } @Override public DateInterval toInterval() { return DateInterval.of(getStart(), Period.from(getDuration())); } }
kbec/maisica-time
src/main/java/net/maisica/time/span/DateSpan.java
Java
apache-2.0
2,526
package cn.edu.hhu.reg.activity; import java.util.ArrayList; import cn.edu.hhu.reg.AppConfig; import cn.edu.hhu.reg.R; import cn.edu.hhu.reg.adapter.RegistrationListAdapter; import cn.edu.hhu.reg.api.ApiClient; import cn.edu.hhu.reg.api.ResponseUtils; import cn.edu.hhu.reg.api.SimpleResponse; import cn.edu.hhu.reg.common.CustomProgressDialog; import cn.edu.hhu.reg.common.ToastShow; import cn.edu.hhu.reg.common.http.HttpException; import cn.edu.hhu.reg.common.http.async.HttpAsync; import cn.edu.hhu.reg.entity.Registration; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; public class RegistrationMineActivity extends BaseActivity { ListView lv; CustomProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_listview); ((TextView)findViewById(R.id.listview_tv_title)).setText("我的预约"); UiHelper.goBack(this); lv = (ListView) findViewById(R.id.listview_lv); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { RegistrationListAdapter adapter = (RegistrationListAdapter) parent.getAdapter(); Registration registration = adapter.getItem(position); UiHelper.registrationDetail(RegistrationMineActivity.this, registration); } }); } @Override protected void onStart() { super.onStart(); getMyRegistrationList(); } private void getMyRegistrationList() { String uid = AppConfig.getAppConfig().getLoginInfo(this).getUid(); if(TextUtils.isEmpty(uid)){ ToastShow.shortT("请重新登录!"); finish(); return; } HttpAsync httpAsync = new HttpAsync() { @Override protected void onSuccess(String json) { progressDialog.dismiss(); try { SimpleResponse<ArrayList<Registration>> response = ResponseUtils.registrationListResponse(json); if(response.isSuccess()){ ArrayList<Registration> list = response.getData(); lv.setAdapter(new RegistrationListAdapter(list, RegistrationMineActivity.this)); }else{ String msg = response.getMessage(); if(msg==null) msg=""; ToastShow.shortT("获取列表失败!"+msg); } } catch (Exception e) { ToastShow.shortT(e.getMessage()); } } @Override public void onError(HttpException exception) { progressDialog.dismiss(); ToastShow.shortT("获取列表失败!"+exception.getMessage()); } }; if(progressDialog==null)progressDialog = new CustomProgressDialog(this, "正在获取列表!"); progressDialog.show(); ApiClient.myRegistrationList(uid, httpAsync); } @Override protected void onDestroy() { super.onDestroy(); if(progressDialog!=null){ progressDialog.dismiss(); } } }
pqpo/registration_android
src/cn/edu/hhu/reg/activity/RegistrationMineActivity.java
Java
apache-2.0
2,994
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.domain.materials.svn; import java.util.List; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; public class SvnExternalParserTest { @Test public void shouldParseOneLineSvnExternalOnCurrentFolderForSvn14() { String svnExternals = "http://10.18.3.171:8080/svn/connect4/trunk - CSharp http://10.18.3.171:8080/svn/CSharpProject/trunk\n"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/connect4/trunk", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("CSharp", "http://10.18.3.171:8080/svn/CSharpProject/trunk"))); } @Test public void shouldParseOneLineSvnExternalOnMultipleLevelFolderForSvn14() { String svnExternals = "http://10.18.3.171:8080/svn/connect4/trunk/dir1/dir2 - externals-2 http://10.18.3.171:8080/svn/CSharpProject/trunk/\n"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/connect4/trunk", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("dir1/dir2/externals-2", "http://10.18.3.171:8080/svn/CSharpProject/trunk/"))); } @Test public void shouldParseMultipleLineSvnExternalForSvn14() { String svnExternals = "http://10.18.3.171:8080/svn/connect4/trunk - externals-2 http://10.18.3.171:8080/svn/CSharpProject/trunk/\n" + "dir1 http://10.18.3.171:8080/svn/CSharpProject/trunk"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/connect4/trunk", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("externals-2", "http://10.18.3.171:8080/svn/CSharpProject/trunk/"))); assertThat(externals.get(1), is(new SvnExternal("dir1", "http://10.18.3.171:8080/svn/CSharpProject/trunk"))); } @Test public void shouldParseMultipleSvnExternalsForSvn14() { String svnExternals = "http://10.18.3.171:8080/svn/connect4/trunk - externals-2 http://10.18.3.171:8080/svn/CSharpProject/trunk\n" + "dir1 http://10.18.3.171:8080/svn/CSharpProject/trunk\n" + "\n" + "http://10.18.3.171:8080/svn/connect4/trunk/dir2 - externals-2 http://10.18.3.171:8080/svn/CSharpProject/trunk\n" + "dir3 http://10.18.3.171:8080/svn/CSharpProject/trunk\n"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/connect4/trunk", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("externals-2", "http://10.18.3.171:8080/svn/CSharpProject/trunk"))); assertThat(externals.get(1), is(new SvnExternal("dir1", "http://10.18.3.171:8080/svn/CSharpProject/trunk"))); assertThat(externals.get(2), is(new SvnExternal("dir2/externals-2", "http://10.18.3.171:8080/svn/CSharpProject/trunk"))); assertThat(externals.get(3), is(new SvnExternal("dir2/dir3", "http://10.18.3.171:8080/svn/CSharpProject/trunk"))); } @Test public void shouldParseOneLineSvnExternalOnCurrentFolderForSvn15() { String svnExternals = "http://10.18.3.171:8080/svn/connect4/trunk - http://10.18.3.171:8080/svn/CSharpProject/trunk externals-2 \n"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/connect4/trunk", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("externals-2", "http://10.18.3.171:8080/svn/CSharpProject/trunk"))); } @Test public void shouldParseOneLineSvnExternalOnMultipleLevelFolderForSvn15() { String svnExternals = "http://10.18.3.171:8080/svn/connect4/trunk/dir1/dir2 - http://10.18.3.171:8080/svn/CSharpProject/trunk externals-2 \n"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/connect4/trunk", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("dir1/dir2/externals-2", "http://10.18.3.171:8080/svn/CSharpProject/trunk"))); } @Test public void shouldParseMultipleLineSvnExternalForSvn15() { String svnExternals = "http://10.18.3.171:8080/svn/connect4/trunk - http://10.18.3.171:8080/svn/CSharpProject/trunk/ externals-2 \n" + "http://10.18.3.171:8080/svn/CSharpProject/trunk dir1 "; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/connect4/trunk", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("externals-2", "http://10.18.3.171:8080/svn/CSharpProject/trunk/"))); assertThat(externals.get(1), is(new SvnExternal("dir1", "http://10.18.3.171:8080/svn/CSharpProject/trunk"))); } @Test public void shouldParseMultipleSvnExternalsForSvn15() { String svnExternals = "http://10.18.3.171:8080/svn/connect4/trunk - http://10.18.3.171:8080/svn/CSharpProject/trunk externals-2 \n" + "http://10.18.3.171:8080/svn/CSharpProject/trunk dir1 \n" + "\n" + "http://10.18.3.171:8080/svn/connect4/trunk/dir2 - svn://10.18.3.171:8080/svn/CSharpProject/trunk externals-2 \n" + "svn://10.18.3.171:8080/svn/CSharpProject/trunk dir3 \n"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/connect4/trunk", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("externals-2", "http://10.18.3.171:8080/svn/CSharpProject/trunk"))); assertThat(externals.get(1), is(new SvnExternal("dir1", "http://10.18.3.171:8080/svn/CSharpProject/trunk"))); assertThat(externals.get(2), is(new SvnExternal("dir2/externals-2", "svn://10.18.3.171:8080/svn/CSharpProject/trunk"))); assertThat(externals.get(3), is(new SvnExternal("dir2/dir3", "svn://10.18.3.171:8080/svn/CSharpProject/trunk"))); } @Test public void shouldSupportFileProtocal() throws Exception { String svnExternals = "file:///tmp/repo/project/trunk - end2end file:///tmp/testSvnRepo-1246619674077/end2end"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "file:///tmp/repo/project", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("trunk/end2end", "file:///tmp/testSvnRepo-1246619674077/end2end"))); } @Test public void shouldSupportUrlWithEncodedSpaces() throws Exception { String svnExternals = "file:///C:/Program%20Files/trunk - end2end file:///C:/Program%20Files/testSvnRepo-1246619674077/end2end"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "file:///C:/Program%20Files", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("trunk/end2end", "file:///C:/Program%20Files/testSvnRepo-1246619674077/end2end"))); } @Test public void shouldParseMultipleSvnExternalsWithMixedFormat() { String svnExternals = "http://10.18.3.171:8080/svn/connect4/trunk/lib - http://10.18.3.171:8080/svn/CSharpProject/trunk/ externals-2 \n" + "\n" + "http://10.18.3.171:8080/svn/connect4/trunk - svn://10.18.3.171:8080/svn/CSharpProject/trunk/ externals-6\n" + "externals-x svn://10.18.3.171:8080/svn/CSharpProject/trunk/\n"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/connect4/trunk", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("lib/externals-2", "http://10.18.3.171:8080/svn/CSharpProject/trunk/"))); assertThat(externals.get(1), is(new SvnExternal("externals-6", "svn://10.18.3.171:8080/svn/CSharpProject/trunk/"))); assertThat(externals.get(2), is(new SvnExternal("externals-x", "svn://10.18.3.171:8080/svn/CSharpProject/trunk/"))); } @Test public void shouldParseMultipleSvnExternalsWithSpace() { String svnExternals = "http://10.18.3.171:8080/svn/connect4/trunk/lib - http://10.18.3.171:8080/svn/CSharpProject/trunk/ externals-2 \n" + "\n" + "http://10.18.3.171:8080/svn/connect4/trunk - svn://10.18.3.171:8080/svn/CSharpProject/trunk/ externals-6\n" + " externals-x svn://10.18.3.171:8080/svn/CSharpProject/trunk/\n" + " svn://10.18.3.171:8080/svn/CSharpProject/trunk/ externals-y\n"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/connect4/trunk", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("lib/externals-2", "http://10.18.3.171:8080/svn/CSharpProject/trunk/"))); assertThat(externals.get(1), is(new SvnExternal("externals-6", "svn://10.18.3.171:8080/svn/CSharpProject/trunk/"))); assertThat(externals.get(2), is(new SvnExternal("externals-x", "svn://10.18.3.171:8080/svn/CSharpProject/trunk/"))); assertThat(externals.get(3), is(new SvnExternal("externals-y", "svn://10.18.3.171:8080/svn/CSharpProject/trunk/"))); } @Test public void shouldParseSvnExternalWithOperativeRevisionForSvn14() { String svnExternals = "http://10.18.3.171:8080/svn/connect4/trunk/lib - externals-2 -r 2 http://10.18.3.171:8080/svn/CSharpProject/trunk/ \n" + "externals-6 -r3 svn://10.18.3.171:8080/svn/CSharpProject/trunk/ \n"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/connect4/trunk", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("lib/externals-2", "http://10.18.3.171:8080/svn/CSharpProject/trunk/"))); assertThat(externals.get(1), is(new SvnExternal("lib/externals-6", "svn://10.18.3.171:8080/svn/CSharpProject/trunk/"))); } @Test public void shouldParseSvnExternalWithOperativeRevisionForSvn15() { String svnExternals = "http://10.18.3.171:8080/svn/connect4/trunk/lib - -r 2 http://10.18.3.171:8080/svn/CSharpProject/trunk/ externals-2 \n" + "-r3 svn://10.18.3.171:8080/svn/CSharpProject/trunk/ externals-6\n"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/connect4/trunk", "http://10.18.3.171:8080/svn"); assertThat(externals.get(0), is(new SvnExternal("lib/externals-2", "http://10.18.3.171:8080/svn/CSharpProject/trunk/"))); assertThat(externals.get(1), is(new SvnExternal("lib/externals-6", "svn://10.18.3.171:8080/svn/CSharpProject/trunk/"))); } @Test public void shouldParseSvnExternalsWithRootSvn15AndAboveWithRootMatcherRelativePathsForSvn15() { String svnExternals = "http://10.18.3.171:8080/svn/externalstest - ^/repo1/trunk lib/repo1\n" + "^/repo2/trunk repo2\n" + "^/repo3/trunk app/repo3\n" + "^/repo4/trunk app/repo4"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/externalstest", "http://10.18.3.171:8080/svn"); assertThat(externals.size(), is(4)); assertThat(externals.get(0), is(new SvnExternal("lib/repo1", "http://10.18.3.171:8080/svn/repo1/trunk"))); assertThat(externals.get(3), is(new SvnExternal("app/repo4", "http://10.18.3.171:8080/svn/repo4/trunk"))); } @Test public void shouldLeaveCaretsUntouchedUnlessAtFront() { String svnExternals = "http://10.18.3.171:8080/svn/externalstest - http://10.18.3.171:8080/svn/^/repo1/trunk lib/repo1\n" + "http://10.18.3.171:8080/svn/a^/repo1/trunk lib/repo1\n" + "http://10.18.3.171:8080/svn/^/repo2/trunk repo2\n"; List<SvnExternal> externals = new SvnExternalParser().parse(svnExternals, "http://10.18.3.171:8080/svn/externalstest", "http://10.18.3.171:8080/svn"); assertThat(externals.size(), is(3)); assertThat(externals.get(0), is(new SvnExternal("lib/repo1", "http://10.18.3.171:8080/svn/^/repo1/trunk"))); assertThat(externals.get(2), is(new SvnExternal("repo2", "http://10.18.3.171:8080/svn/^/repo2/trunk"))); } }
marques-work/gocd
common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnExternalParserTest.java
Java
apache-2.0
13,320
/* * Copyright 2021 jimv. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qvcsos.server.archivemigration; /** * * @author jimv */ class LegacyQVCSConstants { /** * Archive temp file suffix. */ public static final String QVCS_ARCHIVE_TEMPFILE_SUFFIX = ".temp"; /** * Archive old file suffix. */ public static final String QVCS_ARCHIVE_OLDFILE_SUFFIX = ".old"; /** * The standard QVCS path separator byte. */ public static final byte QVCS_STANDARD_PATH_SEPARATOR = '/'; public static final int QVCS_MAXIMUM_BRANCH_DEPTH = 20; public static final int BYTES_TO_XFER = 2 * 1048576; private static final int MAX_PATH_BASE = 260; private static final int MAX_PATH_SUPPLEMENT = 256; /** * The size of the supplemental information in the QVCS Header. */ public static final int QVCS_SUPPLEMENTAL_SIZE = MAX_PATH_BASE + MAX_PATH_SUPPLEMENT; }
jimv39/qvcsos
qvcse-server/src/test/java/com/qvcsos/server/archivemigration/LegacyQVCSConstants.java
Java
apache-2.0
1,454
package com.bq.corbel.webfs.ioc; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.env.Environment; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.bq.corbel.webfs.api.WebResource; import com.bq.corbel.webfs.service.AmazonS3Service; import com.bq.corbel.webfs.service.DefaultAmazonS3Service; import com.bq.corbel.lib.config.ConfigurationIoC; import com.bq.corbel.lib.ws.auth.ioc.AuthorizationIoc; import com.bq.corbel.lib.ws.cors.ioc.CorsIoc; import com.bq.corbel.lib.ws.dw.ioc.CommonFiltersIoc; import com.bq.corbel.lib.ws.dw.ioc.DropwizardIoc; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JSR310Module; /** * @author Rubén Carrasco * */ @Configuration @Import({ConfigurationIoC.class, CommonFiltersIoc.class, DropwizardIoc.class, CorsIoc.class, AuthorizationIoc.class}) public class WebfsIoc { @Autowired private Environment env; @Bean public WebResource getWebResource() { return new WebResource(getAmazonS3Service()); } @Bean public AmazonS3Service getAmazonS3Service() { return new DefaultAmazonS3Service(getAmazonS3Client(), env.getProperty("webfs.s3.bucket")); } @Bean public AmazonS3 getAmazonS3Client() { AmazonS3Client amazonS3Client = new AmazonS3Client(new BasicAWSCredentials(env.getProperty("webfs.s3.key"), env.getProperty("webfs.s3.secret"))); amazonS3Client.setRegion(Region.getRegion(Regions.fromName(env.getProperty("webfs.s3.region")))); return amazonS3Client; } @Bean public ObjectMapper getObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.registerModule(new JSR310Module()); return mapper; } }
bq/corbel
webfs/src/main/java/com/bq/corbel/webfs/ioc/WebfsIoc.java
Java
apache-2.0
2,266
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.alexaforbusiness.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.alexaforbusiness.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * GetNetworkProfileRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class GetNetworkProfileRequestProtocolMarshaller implements Marshaller<Request<GetNetworkProfileRequest>, GetNetworkProfileRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("AlexaForBusiness.GetNetworkProfile").serviceName("AmazonAlexaForBusiness").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public GetNetworkProfileRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<GetNetworkProfileRequest> marshall(GetNetworkProfileRequest getNetworkProfileRequest) { if (getNetworkProfileRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<GetNetworkProfileRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, getNetworkProfileRequest); protocolMarshaller.startMarshalling(); GetNetworkProfileRequestMarshaller.getInstance().marshall(getNetworkProfileRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-alexaforbusiness/src/main/java/com/amazonaws/services/alexaforbusiness/model/transform/GetNetworkProfileRequestProtocolMarshaller.java
Java
apache-2.0
2,751
/* * * * Copyright (C) 2016 Track & Talk Ltd * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.trackandtalk.pafos17.ui.settings; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceActivity; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatDelegate; import android.support.v7.widget.Toolbar; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; /** * A {@link android.preference.PreferenceActivity} which implements and proxies the necessary calls * to be used with AppCompat. * * * Created by Konstantinos Papageorgiou and Charalambos Xinaris * */ public abstract class AppCompatPreferenceActivity extends PreferenceActivity { private AppCompatDelegate mDelegate; @Override protected void onCreate(Bundle savedInstanceState) { getDelegate().installViewFactory(); getDelegate().onCreate(savedInstanceState); super.onCreate(savedInstanceState); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getDelegate().onPostCreate(savedInstanceState); } public ActionBar getSupportActionBar() { return getDelegate().getSupportActionBar(); } public void setSupportActionBar(@Nullable Toolbar toolbar) { getDelegate().setSupportActionBar(toolbar); } @Override public MenuInflater getMenuInflater() { return getDelegate().getMenuInflater(); } @Override public void setContentView(@LayoutRes int layoutResID) { getDelegate().setContentView(layoutResID); } @Override public void setContentView(View view) { getDelegate().setContentView(view); } @Override public void setContentView(View view, ViewGroup.LayoutParams params) { getDelegate().setContentView(view, params); } @Override public void addContentView(View view, ViewGroup.LayoutParams params) { getDelegate().addContentView(view, params); } @Override protected void onPostResume() { super.onPostResume(); getDelegate().onPostResume(); } @Override protected void onTitleChanged(CharSequence title, int color) { super.onTitleChanged(title, color); getDelegate().setTitle(title); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); getDelegate().onConfigurationChanged(newConfig); } @Override protected void onStop() { super.onStop(); getDelegate().onStop(); } @Override protected void onDestroy() { super.onDestroy(); getDelegate().onDestroy(); } public void invalidateOptionsMenu() { getDelegate().invalidateOptionsMenu(); } private AppCompatDelegate getDelegate() { if (mDelegate == null) { mDelegate = AppCompatDelegate.create(this, null); } return mDelegate; } }
papageorgiouk/pafos2017
app/src/main/java/com/trackandtalk/pafos17/ui/settings/AppCompatPreferenceActivity.java
Java
apache-2.0
3,734
/* * Copyright 2017 Johannes Donath <johannesd@torchmind.com> * and other copyright owners as documented in the project's IP log. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.torchmind.observable.primitive; import com.torchmind.observable.Observable; /** * Provides a observable implementation which simplifies access to char values. * * @author <a href="mailto:johannesd@torchmind.com">Johannes Donath</a> */ public interface CharacterObservable extends Observable<Character>, ReadOnlyCharacterObservable { /** * @see #set(Object) for a wrapped version of the value. */ void setValue(char value); }
Torchmind/Observables
src/main/java/com/torchmind/observable/primitive/CharacterObservable.java
Java
apache-2.0
1,149
/* * Copyright (C) 2018 the original author or authors. * * This file is part of jBB Application Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 */ package org.jbb.security.impl.oauth.search; import org.apache.commons.lang3.StringUtils; import org.jbb.security.impl.oauth.model.OAuthClientEntity; import org.jbb.security.impl.oauth.model.OAuthClientEntity_; import org.springframework.data.jpa.domain.Specification; import lombok.experimental.UtilityClass; @UtilityClass public final class OAuthClientSpecifications { public static Specification<OAuthClientEntity> withClientId(String clientId) { if (StringUtils.isNotBlank(clientId)) { return (root, cq, cb) -> cb.like(cb.upper(root.get(OAuthClientEntity_.clientId)), "%" + clientId.toUpperCase() + "%"); } else { return null; } } public static Specification<OAuthClientEntity> withDisplayedName(String displayedName) { if (StringUtils.isNotBlank(displayedName)) { return (root, cq, cb) -> cb.like(cb.upper(root.get(OAuthClientEntity_.displayedName)), "%" + displayedName.toUpperCase() + "%"); } else { return null; } } }
jbb-project/jbb
domain-services/jbb-security/src/main/java/org/jbb/security/impl/oauth/search/OAuthClientSpecifications.java
Java
apache-2.0
1,421
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.websocket.jsr356; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.CountDownLatch; import javax.enterprise.context.Dependent; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import org.apache.camel.Produce; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.junit4.CamelTestSupport; import org.apache.meecrowave.Meecrowave; import org.apache.meecrowave.junit.MeecrowaveRule; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import static java.util.Collections.singletonList; public class JSR356ProducerTest extends CamelTestSupport { @Rule public final MeecrowaveRule servlet = new MeecrowaveRule(new Meecrowave.Builder() { { randomHttpPort(); setScanningPackageIncludes("org.apache.camel.websocket.jsr356.JSR356ProducerTest$"); } }, ""); @Rule public final TestName testName = new TestName(); @Produce("direct:ensureServerModeSendsProperly") private ProducerTemplate serverProducer; @Ignore @Test public void ensureServerModeSendsProperly() throws Exception { final String body = getClass().getName() + "#" + testName.getMethodName(); serverProducer.sendBody(body); ExistingServerEndpoint.self.latch.await(); assertEquals(singletonList(body), ExistingServerEndpoint.self.messages); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:ensureServerModeSendsProperly").id("camel_consumer_acts_as_client").convertBodyTo(String.class) .to("websocket-jsr356://ws://localhost:" + servlet.getConfiguration().getHttpPort() + "/existingserver"); } }; } @Dependent @ServerEndpoint("/existingserver") public static class ExistingServerEndpoint { private static ExistingServerEndpoint self; private final Collection<String> messages = new ArrayList<>(); private final CountDownLatch latch = new CountDownLatch(1); @OnOpen public void onOpen(final Session session) { self = this; } @OnMessage public synchronized void onMessage(final String message) { messages.add(message); latch.countDown(); } } }
objectiser/camel
components/camel-websocket-jsr356/src/test/java/org/apache/camel/websocket/jsr356/JSR356ProducerTest.java
Java
apache-2.0
3,382
package org.geotools.tutorial.graph; import org.geotools.swing.JMapFrame; /** * This is a quick visual example of how to use the graph module using the TIGER roads data. * <p> * The gt-graph module builds ontop of core GeoTools concepts (so you should be familiar with DataStore, FeatureCollection, Query, Geometry, * MapContent prior to starting this tutorial). * <p> * This example consists of a *simple* JMapFrame with a number of actions allowing you to load a shapefile; convert it to an internal graph; select * "waypoints"; and use the way points to calculate a route; use the route to create a FeatureCollection; and display that FeatureCollection as a new * layer. * </p> * * @author Jody Garnett */ public class Tiger extends JMapFrame { public Tiger() { } public static void main(String args[]){ Tiger tiger = new Tiger(); tiger.setVisible(true); } }
ianturton/geotools-cookbook
modules/quickstart/src/main/main/java/org/geotools/tutorial/graph/Tiger.java
Java
apache-2.0
920
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.builder.component.dsl; import javax.annotation.Generated; import org.apache.camel.Component; import org.apache.camel.builder.component.AbstractComponentBuilder; import org.apache.camel.builder.component.ComponentBuilder; import org.apache.camel.component.wordpress.WordpressComponent; /** * Manage posts and users using Wordpress API. * * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.ComponentDslMojo") public interface WordpressComponentBuilderFactory { /** * Wordpress (camel-wordpress) * Manage posts and users using Wordpress API. * * Category: cloud,api,cms * Since: 2.21 * Maven coordinates: org.apache.camel:camel-wordpress */ static WordpressComponentBuilder wordpress() { return new WordpressComponentBuilderImpl(); } /** * Builder for the Wordpress component. */ interface WordpressComponentBuilder extends ComponentBuilder<WordpressComponent> { /** * The Wordpress REST API version. * * The option is a: <code>java.lang.String</code> type. * * Default: 2 * Group: common */ default WordpressComponentBuilder apiVersion(java.lang.String apiVersion) { doSetProperty("apiVersion", apiVersion); return this; } /** * Wordpress configuration. * * The option is a: * <code>org.apache.camel.component.wordpress.WordpressConfiguration</code> type. * * Group: common */ default WordpressComponentBuilder configuration( org.apache.camel.component.wordpress.WordpressConfiguration configuration) { doSetProperty("configuration", configuration); return this; } /** * The criteria to use with complex searches. * * The option is a: <code>java.util.Map<java.lang.String, * java.lang.Object></code> type. * * Group: common */ default WordpressComponentBuilder criteria( java.util.Map<java.lang.String, java.lang.Object> criteria) { doSetProperty("criteria", criteria); return this; } /** * Whether to bypass trash and force deletion. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common */ default WordpressComponentBuilder force(boolean force) { doSetProperty("force", force); return this; } /** * The entity ID. Should be passed when the operation performed requires * a specific entity, e.g. deleting a post. * * The option is a: <code>java.lang.Integer</code> type. * * Group: common */ default WordpressComponentBuilder id(java.lang.Integer id) { doSetProperty("id", id); return this; } /** * Password from authorized user. * * The option is a: <code>java.lang.String</code> type. * * Group: common */ default WordpressComponentBuilder password(java.lang.String password) { doSetProperty("password", password); return this; } /** * Search criteria. * * The option is a: * <code>org.apache.camel.component.wordpress.api.model.SearchCriteria</code> type. * * Group: common */ default WordpressComponentBuilder searchCriteria( org.apache.camel.component.wordpress.api.model.SearchCriteria searchCriteria) { doSetProperty("searchCriteria", searchCriteria); return this; } /** * The Wordpress API URL from your site, e.g. * http://myblog.com/wp-json/. * * The option is a: <code>java.lang.String</code> type. * * Group: common */ default WordpressComponentBuilder url(java.lang.String url) { doSetProperty("url", url); return this; } /** * Authorized user to perform writing operations. * * The option is a: <code>java.lang.String</code> type. * * Group: common */ default WordpressComponentBuilder user(java.lang.String user) { doSetProperty("user", user); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions occurred while the consumer is trying to * pickup incoming messages, or the likes, will now be processed as a * message and handled by the routing Error Handler. By default the * consumer will use the org.apache.camel.spi.ExceptionHandler to deal * with exceptions, that will be logged at WARN or ERROR level and * ignored. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer */ default WordpressComponentBuilder bridgeErrorHandler( boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer */ default WordpressComponentBuilder lazyStartProducer( boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: <code>boolean</code> type. * * Default: true * Group: advanced */ default WordpressComponentBuilder autowiredEnabled( boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } } class WordpressComponentBuilderImpl extends AbstractComponentBuilder<WordpressComponent> implements WordpressComponentBuilder { @Override protected WordpressComponent buildConcreteComponent() { return new WordpressComponent(); } private org.apache.camel.component.wordpress.WordpressConfiguration getOrCreateConfiguration( org.apache.camel.component.wordpress.WordpressComponent component) { if (component.getConfiguration() == null) { component.setConfiguration(new org.apache.camel.component.wordpress.WordpressConfiguration()); } return component.getConfiguration(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "apiVersion": getOrCreateConfiguration((WordpressComponent) component).setApiVersion((java.lang.String) value); return true; case "configuration": ((WordpressComponent) component).setConfiguration((org.apache.camel.component.wordpress.WordpressConfiguration) value); return true; case "criteria": getOrCreateConfiguration((WordpressComponent) component).setCriteria((java.util.Map) value); return true; case "force": getOrCreateConfiguration((WordpressComponent) component).setForce((boolean) value); return true; case "id": getOrCreateConfiguration((WordpressComponent) component).setId((java.lang.Integer) value); return true; case "password": getOrCreateConfiguration((WordpressComponent) component).setPassword((java.lang.String) value); return true; case "searchCriteria": getOrCreateConfiguration((WordpressComponent) component).setSearchCriteria((org.apache.camel.component.wordpress.api.model.SearchCriteria) value); return true; case "url": getOrCreateConfiguration((WordpressComponent) component).setUrl((java.lang.String) value); return true; case "user": getOrCreateConfiguration((WordpressComponent) component).setUser((java.lang.String) value); return true; case "bridgeErrorHandler": ((WordpressComponent) component).setBridgeErrorHandler((boolean) value); return true; case "lazyStartProducer": ((WordpressComponent) component).setLazyStartProducer((boolean) value); return true; case "autowiredEnabled": ((WordpressComponent) component).setAutowiredEnabled((boolean) value); return true; default: return false; } } } }
nicolaferraro/camel
core/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/WordpressComponentBuilderFactory.java
Java
apache-2.0
10,782
package com.cherokeelessons.cll1.models; public class Settings { public String name = ""; public boolean muted = false; public Settings() { } public Settings(final Settings settings) { this.muted = settings.muted; this.name = settings.name; } }
CherokeeLanguage/cll1-gdx
core/src/com/cherokeelessons/cll1/models/Settings.java
Java
apache-2.0
257
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.elasticmapreduce.model.transform; import static com.amazonaws.util.StringUtils.UTF8; import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.regex.Pattern; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.elasticmapreduce.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.util.json.*; /** * ListStepsRequest Marshaller */ public class ListStepsRequestMarshaller implements Marshaller<Request<ListStepsRequest>, ListStepsRequest> { public Request<ListStepsRequest> marshall(ListStepsRequest listStepsRequest) { if (listStepsRequest == null) { throw new AmazonClientException( "Invalid argument passed to marshall(...)"); } Request<ListStepsRequest> request = new DefaultRequest<ListStepsRequest>( listStepsRequest, "AmazonElasticMapReduce"); request.addHeader("X-Amz-Target", "ElasticMapReduce.ListSteps"); request.setHttpMethod(HttpMethodName.POST); request.setResourcePath(""); try { StringWriter stringWriter = new StringWriter(); JSONWriter jsonWriter = new JSONWriter(stringWriter); jsonWriter.object(); if (listStepsRequest.getClusterId() != null) { jsonWriter.key("ClusterId").value( listStepsRequest.getClusterId()); } com.amazonaws.internal.SdkInternalList<String> stepStatesList = (com.amazonaws.internal.SdkInternalList<String>) listStepsRequest .getStepStates(); if (!stepStatesList.isEmpty() || !stepStatesList.isAutoConstruct()) { jsonWriter.key("StepStates"); jsonWriter.array(); for (String stepStatesListValue : stepStatesList) { if (stepStatesListValue != null) { jsonWriter.value(stepStatesListValue); } } jsonWriter.endArray(); } com.amazonaws.internal.SdkInternalList<String> stepIdsList = (com.amazonaws.internal.SdkInternalList<String>) listStepsRequest .getStepIds(); if (!stepIdsList.isEmpty() || !stepIdsList.isAutoConstruct()) { jsonWriter.key("StepIds"); jsonWriter.array(); for (String stepIdsListValue : stepIdsList) { if (stepIdsListValue != null) { jsonWriter.value(stepIdsListValue); } } jsonWriter.endArray(); } if (listStepsRequest.getMarker() != null) { jsonWriter.key("Marker").value(listStepsRequest.getMarker()); } jsonWriter.endObject(); String snippet = stringWriter.toString(); byte[] content = snippet.getBytes(UTF8); request.setContent(new StringInputStream(snippet)); request.addHeader("Content-Length", Integer.toString(content.length)); request.addHeader("Content-Type", "application/x-amz-json-1.1"); } catch (Throwable t) { throw new AmazonClientException( "Unable to marshall request to JSON: " + t.getMessage(), t); } return request; } }
trasa/aws-sdk-java
aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/model/transform/ListStepsRequestMarshaller.java
Java
apache-2.0
4,499
/* * Copyright 2001-2009 Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ package org.quartz.impl.jdbcjobstore; import org.quartz.JobPersistenceException; import org.quartz.SchedulerConfigException; import org.quartz.spi.ClassLoadHelper; import org.quartz.spi.SchedulerSignaler; import java.sql.Connection; /** * <p> * <code>JobStoreTX</code> is meant to be used in a standalone environment. * Both commit and rollback will be handled by this class. * </p> * * <p> * If you need a <code>{@link org.quartz.spi.JobStore}</code> class to use * within an application-server environment, use <code>{@link * org.quartz.impl.jdbcjobstore.JobStoreCMT}</code> * instead. * </p> * * @author <a href="mailto:jeff@binaryfeed.org">Jeffrey Wescott</a> * @author James House */ public class JobStoreTX extends JobStoreSupport { /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * Interface. * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ @Override public void initialize(ClassLoadHelper classLoadHelper, SchedulerSignaler schedSignaler) throws SchedulerConfigException { super.initialize(classLoadHelper, schedSignaler); getLog().info("JobStoreTX initialized."); } /** * For <code>JobStoreTX</code>, the non-managed TX connection is just * the normal connection because it is not CMT. * * @see JobStoreSupport#getConnection() */ @Override protected Connection getNonManagedTXConnection() throws JobPersistenceException { return getConnection(); } /** * Execute the given callback having optionally aquired the given lock. * For <code>JobStoreTX</code>, because it manages its own transactions * and only has the one datasource, this is the same behavior as * executeInNonManagedTXLock(). * * @param lockName The name of the lock to aquire, for example * "TRIGGER_ACCESS". If null, then no lock is aquired, but the * lockCallback is still executed in a transaction. * * @see JobStoreSupport#executeInNonManagedTXLock(String, TransactionCallback) * @see JobStoreCMT#executeInLock(String, TransactionCallback) * @see JobStoreSupport#getNonManagedTXConnection() * @see JobStoreSupport#getConnection() */ @Override protected Object executeInLock( String lockName, TransactionCallback txCallback) throws JobPersistenceException { return executeInNonManagedTXLock(lockName, txCallback, null); } } // EOF
AsuraTeam/asura
asura-quartz/src/main/java/org/quartz/impl/jdbcjobstore/JobStoreTX.java
Java
apache-2.0
3,185
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0, (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tle.web.sections.jquery.libraries.effects; import com.tle.common.i18n.CurrentLocale; import com.tle.core.javascript.JavascriptModule; import com.tle.web.sections.jquery.JQueryLibraryInclude; import com.tle.web.sections.jquery.libraries.JQueryCore; import com.tle.web.sections.js.generic.expression.FunctionCallExpression; import com.tle.web.sections.js.generic.function.ExternallyDefinedFunction; import com.tle.web.sections.render.CombinedRenderer; import com.tle.web.sections.render.PreRenderable; import java.util.HashMap; import java.util.Map; @SuppressWarnings("nls") public class JQueryUIEffects implements JavascriptModule { private static final long serialVersionUID = 1L; private static final PreRenderable PRERENDER = new JQueryLibraryInclude("jquery.ui.effect.js", JQueryCore.PRERENDER).hasMin(); private static final Map<String, PreRenderable> effectLibraries = new HashMap<String, PreRenderable>(); public static PreRenderable getEffectLibrary(String effect) { return effectLibraries.get(effect); } public static PreRenderable addEffect(String effect, PreRenderable prerender) { effectLibraries.put(effect, prerender); return prerender; } public static JQueryUIEffectsLibrary addStdEffect(String effect) { JQueryUIEffectsLibrary lib = new JQueryUIEffectsLibrary(effect, "jquery.ui.effect-" + effect + ".js"); effectLibraries.put(effect, lib); return lib; } public static final JQueryUIEffectsLibrary FADE = addStdEffect("fade"); public static final JQueryUIEffectsLibrary BLIND = addStdEffect("blind"); public static final JQueryUIEffectsLibrary SLIDE = addStdEffect("slide"); public static final JQueryUIEffectsLibrary EXPLODE = addStdEffect("explode"); public static final JQueryUIEffectsLibrary PULSATE = addStdEffect("pulsate"); public static final JQueryUIEffectsLibrary SHAKE = addStdEffect("shake"); public static final JQueryUIEffectsLibrary SCALE = addStdEffect("scale"); public static final JQueryUIEffectsLibrary BOUNCE = addStdEffect("bounce"); public static final JQueryUIEffectsLibrary CLIP = addStdEffect("clip"); public static final JQueryUIEffectsLibrary DROP = addStdEffect("drop"); public static final JQueryUIEffectsLibrary FOLD = addStdEffect("fold"); public static final JQueryUIEffectsLibrary HIGHLIGHT = addStdEffect("highlight"); public static final JQueryUIEffectsLibrary TRANSFER = addStdEffect("transfer"); public static final PreRenderable PRERENDER_ALL = new CombinedRenderer(effectLibraries.values()); @Override public String getDisplayName() { return CurrentLocale.get("com.tle.web.sections.jquery.modules.effects.core"); } @Override public String getId() { return "ui-effects-core"; } @Override public Object getPreRenderer() { return PRERENDER_ALL; } public static class JQueryUIEffectsLibrary extends JQueryLibraryInclude { private final String effectName; public JQueryUIEffectsLibrary(String effectName, String filename) { super(filename, JQueryUIEffects.PRERENDER); this.effectName = effectName; hasMin(); } public String getEffectName() { return effectName; } public FunctionCallExpression show() { return new FunctionCallExpression( new ExternallyDefinedFunction("show", this), getEffectName()); } public FunctionCallExpression hide() { return new FunctionCallExpression( new ExternallyDefinedFunction("hide", this), getEffectName()); } } }
equella/Equella
Source/Plugins/Core/com.equella.core/src/com/tle/web/sections/jquery/libraries/effects/JQueryUIEffects.java
Java
apache-2.0
4,355
package com.Voxce.DAO; import java.sql.Date; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.HibernateTemplate; import com.Voxce.model.CaseReportForms; import com.Voxce.model.PatientCRF; import com.Voxce.model.PatientVisits; import com.Voxce.model.Users; import com.Voxce.model.VisitCrfs; import com.Voxce.model.VisitNameTexts; import com.Voxce.model.Visits; public class PatientVisitDAO { private HibernateTemplate hibernateTemplate; List<?> data; public void setSessionFactory(SessionFactory sessionFactory) { this.hibernateTemplate = new HibernateTemplate(sessionFactory); } @SuppressWarnings("unchecked") public List<PatientVisits> listpatientvisits(Users user) { List<PatientVisits> list=(List<PatientVisits>) hibernateTemplate.find("FROM PatientVisits WHERE subscriber_id='"+user.getSubscription_id()+"'"); if(list==null) return new ArrayList<PatientVisits>(); return list; } @SuppressWarnings("unchecked") public List<Visits> listvisits(int study_id) { try{ List<Visits> list=(List<Visits>) hibernateTemplate.find("FROM Visits WHERE study_id='"+study_id+"'"); if(list==null) return new ArrayList<Visits>(); return list; } catch(Exception e) { e.printStackTrace(); System.out.print("exception..."); return null; } } public int getPatientId(int p_no){ try{ System.out.println("id hey: "); data = hibernateTemplate.find("SELECT patient_id FROM Patients WHERE patient_number ='"+p_no+"'"); System.out.println("id hey: " + data.toString()); String[] temp; String res = data.toString(); String del = "]"; temp = res.split(del); res = temp[0]; res = res.substring(1); temp = res.split(","); return Integer.parseInt(temp[0]); } catch(Exception e) { e.printStackTrace(); System.out.print("exception..."); return 0; } } public int deleteVisits(List<Integer> notExisit){ try{ for(int i = 0 ; i < notExisit.size() ; i ++ ){ hibernateTemplate.bulkUpdate("DELETE FROM PatientVisits WHERE visit_id='"+notExisit.get(i)+"'"); } return 1; }catch(Exception e) { e.printStackTrace(); return 0; } } public int deleteAll(int patientId){ try{ hibernateTemplate.bulkUpdate("DELETE FROM PatientVisits WHERE patient_id='"+patientId+"'"); return 1; }catch(Exception e) { e.printStackTrace(); return 0; } } public String getVisitDate(int visit_id){ try{ data = hibernateTemplate.find("SELECT visit_date FROM Visits WHERE visit_id ='"+visit_id+"'"); String[] temp; String res = data.toString(); String del = "]"; temp = res.split(del); res = temp[0]; res = res.substring(1); return res; } catch(Exception e) { e.printStackTrace(); System.out.print("exception..."); return null; } } public String[] getvisit_id(int visit_name_id){ try{ data = hibernateTemplate.find("SELECT visit_id FROM Visits WHERE visit_name_text_id ='"+visit_name_id+"'"); String[] temp; String res = data.toString(); String del = "]"; temp = res.split(del); res = temp[0]; res = res.substring(1); temp = res.split(","); return temp; } catch(Exception e) { e.printStackTrace(); System.out.print("exception..."); return null; } } public int assignVisit(PatientVisits patientvisit) { Calendar cal = Calendar.getInstance(); Date oneDate =new java.sql.Date(cal.getTime().getTime() ); patientvisit.setDate_created(oneDate); // patientvisit.setDate_modified(oneDate); try{ hibernateTemplate.saveOrUpdate(patientvisit); List<VisitCrfs> visitCrf = (List <VisitCrfs>) hibernateTemplate.find("FROM VisitCrfs WHERE visit_id='"+patientvisit.getVisit_id()+"'"); for(int i = 0 ; i < visitCrf.size() ; i++){ List<CaseReportForms> Crf = (List <CaseReportForms>) hibernateTemplate.find("FROM CaseReportForms WHERE crf_id='"+visitCrf.get(i).getCase_report_form_id()+"'"); for(int k = 0 ; k < Crf.size() ; k++){ PatientCRF patientCrf = new PatientCRF(); patientCrf.setCrf_html(Crf.get(k).getCrf_html()); patientCrf.setCrf_id(Crf.get(k).getCrf_id()); patientCrf.setCrf_status("Unfilled"); patientCrf.setPatient_id(patientvisit.getPatient_id()); patientCrf.setVisit_id(patientvisit.getVisit_id()); hibernateTemplate.saveOrUpdate(patientCrf); } } return 1; }catch(Exception e) { e.printStackTrace(); return 0; } } @SuppressWarnings("unchecked") public boolean findPatientVisitByIds(int patientId, int visitId){ List<PatientVisits> patVisLis = (List <PatientVisits>) hibernateTemplate.find("FROM PatientVisits WHERE patient_id='"+patientId+"' AND visit_id='"+visitId+"'"); if(patVisLis.size()>0){ return true; }else{ return false; } } @SuppressWarnings("unchecked") public List<VisitNameTexts> listvisitsname(Users user) { try{ List<VisitNameTexts> list=(List<VisitNameTexts>) hibernateTemplate.find("FROM VisitNameTexts WHERE subscriber_id = "+user.getSubscription_id()+" ORDER BY visit_name ASC"); if(list==null) return new ArrayList<VisitNameTexts>(); return list; } catch(Exception e) { e.printStackTrace(); System.out.print("exception..."); return null; } } }
trialmanager/voxce
src/com/Voxce/DAO/PatientVisitDAO.java
Java
apache-2.0
5,371
package com.vmware.vim25; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "UpdatePassthruConfigResponse") public class UpdatePassthruConfigResponse { }
jdgwartney/vsphere-ws
java/JAXWS/samples/com/vmware/vim25/UpdatePassthruConfigResponse.java
Java
apache-2.0
786
/* ******************************************************************* * * Copyright 2015 Intel Corporation. * *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */ package org.iotivity.base; import org.iotivity.ca.CaInterface; import java.util.EnumSet; import java.util.Iterator; import java.util.List; /** * This class contains the main entrance/functionality of the product. To set a custom * configuration, the implementer must make a call to OcPlatform.Configure before the first usage * of a method in this class. */ public final class OcPlatform { static { System.loadLibrary("oc_logger"); System.loadLibrary("octbstack"); System.loadLibrary("connectivity_abstraction"); System.loadLibrary("oc"); System.loadLibrary("ocstack-jni"); } /** * Default interface */ public static final String DEFAULT_INTERFACE = "oic.if.baseline"; /** * Used in discovering (GET) links to other resources of a collection */ public static final String LINK_INTERFACE = "oic.if.ll"; /** * Used in GET, PUT, POST, DELETE methods on links to other resources of a collection */ public static final String BATCH_INTERFACE = "oic.if.b"; /** * Used in GET, PUT, POST methods on links to other remote resources of a group */ public static final String GROUP_INTERFACE = "oic.mi.grp"; public static final String WELL_KNOWN_QUERY = "/oic/res"; public static final String WELL_KNOWN_DEVICE_QUERY = "/oic/d"; public static final String WELL_KNOWN_PLATFORM_QUERY = "/oic/p"; public static final int DEFAULT_PRESENCE_TTL = 60; public static final String PRESENCE_URI = "/oic/ad"; private static volatile boolean sIsPlatformInitialized = false; private static QualityOfService sPlatformQualityOfService = QualityOfService.NA; private OcPlatform() { } /** * API for setting the configuration of the OcPlatform. * <p> * Note: Any calls made to this AFTER the first call to OcPlatform.Configure will have no affect * </p> * * @param platformConfig platform configuration */ public synchronized static void Configure(PlatformConfig platformConfig) { if (!sIsPlatformInitialized) { CaInterface.initialize(platformConfig.getActivity(), platformConfig.getContext()); sPlatformQualityOfService = platformConfig.getQualityOfService(); OcPlatform.configure( platformConfig.getServiceType().getValue(), platformConfig.getModeType().getValue(), platformConfig.getIpAddress(), platformConfig.getPort(), platformConfig.getQualityOfService().getValue(), platformConfig.getSvrDbPath() ); sIsPlatformInitialized = true; } } private static native void configure(int serviceType, int modeType, String ipAddress, int port, int qualityOfService, String dbPath); /** * API for notifying base that resource's attributes have changed. * <p> * Note: This API is for server side only. * </p> * * @param ocResourceHandle resource handle of the resource * @throws OcException if failure */ public static void notifyAllObservers( OcResourceHandle ocResourceHandle) throws OcException { OcPlatform.initCheck(); OcPlatform.notifyAllObservers0(ocResourceHandle); } private static native void notifyAllObservers0( OcResourceHandle ocResourceHandle) throws OcException; /** * API for notifying base that resource's attributes have changed. * <p> * Note: This API is for server side only. * </p> * * @param ocResourceHandle resource handle of the resource * @param qualityOfService the quality of communication * @throws OcException if failure */ public static void notifyAllObservers( OcResourceHandle ocResourceHandle, QualityOfService qualityOfService) throws OcException { OcPlatform.initCheck(); OcPlatform.notifyAllObservers1(ocResourceHandle, qualityOfService.getValue()); } private static native void notifyAllObservers1( OcResourceHandle ocResourceHandle, int qualityOfService) throws OcException; /** * API for notifying only specific clients that resource's attributes have changed. * <p> * Note: This API is for server side only. * </p> * * @param ocResourceHandle resource handle of the resource * @param ocObservationIdList These set of ids are ones which which will be notified upon * resource change. * @param ocResourceResponse OcResourceResponse object used by app to fill the response for * this resource change * @throws OcException if failure */ public static void notifyListOfObservers( OcResourceHandle ocResourceHandle, List<Byte> ocObservationIdList, OcResourceResponse ocResourceResponse) throws OcException { OcPlatform.initCheck(); byte[] idArr = new byte[ocObservationIdList.size()]; Iterator<Byte> it = ocObservationIdList.iterator(); int i = 0; while (it.hasNext()) { idArr[i++] = (byte) it.next(); } OcPlatform.notifyListOfObservers2( ocResourceHandle, idArr, ocResourceResponse); } private static native void notifyListOfObservers2( OcResourceHandle ocResourceHandle, byte[] ocObservationIdArray, OcResourceResponse ocResourceResponse) throws OcException; /** * API for notifying only specific clients that resource's attributes have changed. * <p> * Note: This API is for server side only. * </p> * * @param ocResourceHandle resource handle of the resource * @param ocObservationIdList These set of ids are ones which which will be notified upon * resource change. * @param ocResourceResponse OcResourceResponse object used by app to fill the response for * this resource change * @param qualityOfService the quality of communication * @throws OcException if failure */ public static void notifyListOfObservers( OcResourceHandle ocResourceHandle, List<Byte> ocObservationIdList, OcResourceResponse ocResourceResponse, QualityOfService qualityOfService) throws OcException { OcPlatform.initCheck(); byte[] idArr = new byte[ocObservationIdList.size()]; Iterator<Byte> it = ocObservationIdList.iterator(); int i = 0; while (it.hasNext()) { idArr[i++] = (byte) it.next(); } OcPlatform.notifyListOfObservers3( ocResourceHandle, idArr, ocResourceResponse, qualityOfService.getValue() ); } private static native void notifyListOfObservers3( OcResourceHandle ocResourceHandle, byte[] ocObservationIdArray, OcResourceResponse ocResourceResponse, int qualityOfService) throws OcException; /** * API for Service and Resource Discovery * <p> * Note: This API is for client side only. * </p> * * @param host Host Address of a service to direct resource discovery query. * If empty, performs multicast resource discovery query * @param resourceUri name of the resource. If null or empty, performs search for all * resource names * @param connectivityTypeSet Set of types of connectivity. Example: IP * @param onResourceFoundListener Handles events, success states and failure states. * @throws OcException if failure */ public static void findResource( String host, String resourceUri, EnumSet<OcConnectivityType> connectivityTypeSet, OnResourceFoundListener onResourceFoundListener) throws OcException { OcPlatform.initCheck(); int connTypeInt = 0; for (OcConnectivityType connType : OcConnectivityType.values()) { if (connectivityTypeSet.contains(connType)) connTypeInt |= connType.getValue(); } OcPlatform.findResource0( host, resourceUri, connTypeInt, onResourceFoundListener ); } private static native void findResource0( String host, String resourceUri, int connectivityType, OnResourceFoundListener onResourceFoundListener) throws OcException; /** * API for Service and Resource Discovery. * <p> * Note: This API is for client side only. * </p> * * @param host Host IP Address of a service to direct resource discovery query. * If empty, performs multicast resource discovery query * @param resourceUri name of the resource. If null or empty, performs search for all * resource names * @param connectivityTypeSet Set of types of connectivity. Example: IP * @param onResourceFoundListener Handles events, success states and failure states. * @param qualityOfService the quality of communication * @throws OcException if failure */ public static void findResource( String host, String resourceUri, EnumSet<OcConnectivityType> connectivityTypeSet, OnResourceFoundListener onResourceFoundListener, QualityOfService qualityOfService) throws OcException { OcPlatform.initCheck(); int connTypeInt = 0; for (OcConnectivityType connType : OcConnectivityType.values()) { if (connectivityTypeSet.contains(connType)) connTypeInt |= connType.getValue(); } OcPlatform.findResource1(host, resourceUri, connTypeInt, onResourceFoundListener, qualityOfService.getValue() ); } private static native void findResource1( String host, String resourceUri, int connectivityType, OnResourceFoundListener onResourceFoundListener, int qualityOfService) throws OcException; /** * API for Device Discovery * * @param host Host IP Address. If null or empty, Multicast is performed. * @param deviceUri Uri containing address to the virtual device * @param connectivityTypeSet Set of types of connectivity. Example: IP * @param onDeviceFoundListener Handles events, success states and failure states. * @throws OcException if failure */ public static void getDeviceInfo( String host, String deviceUri, EnumSet<OcConnectivityType> connectivityTypeSet, OnDeviceFoundListener onDeviceFoundListener) throws OcException { OcPlatform.initCheck(); int connTypeInt = 0; for (OcConnectivityType connType : OcConnectivityType.values()) { if (connectivityTypeSet.contains(connType)) connTypeInt |= connType.getValue(); } OcPlatform.getDeviceInfo0( host, deviceUri, connTypeInt, onDeviceFoundListener ); } private static native void getDeviceInfo0( String host, String deviceUri, int connectivityType, OnDeviceFoundListener onDeviceFoundListener) throws OcException; /** * API for Device Discovery * * @param host Host IP Address. If null or empty, Multicast is performed. * @param deviceUri Uri containing address to the virtual device * @param connectivityTypeSet Set of types of connectivity. Example: IP * @param onDeviceFoundListener Handles events, success states and failure states. * @param qualityOfService the quality of communication * @throws OcException if failure */ public static void getDeviceInfo( String host, String deviceUri, EnumSet<OcConnectivityType> connectivityTypeSet, OnDeviceFoundListener onDeviceFoundListener, QualityOfService qualityOfService) throws OcException { OcPlatform.initCheck(); int connTypeInt = 0; for (OcConnectivityType connType : OcConnectivityType.values()) { if (connectivityTypeSet.contains(connType)) connTypeInt |= connType.getValue(); } OcPlatform.getDeviceInfo1( host, deviceUri, connTypeInt, onDeviceFoundListener, qualityOfService.getValue() ); } private static native void getDeviceInfo1( String host, String deviceUri, int connectivityType, OnDeviceFoundListener onDeviceFoundListener, int qualityOfService) throws OcException; /** * API for Platform Discovery * * @param host Host IP Address. If null or empty, Multicast is performed. * @param platformUri Uri containing address to the platform * @param connectivityTypeSet Set of types of connectivity. Example: IP * @param onPlatformFoundListener Handles events, success states and failure states. * @throws OcException if failure */ public static void getPlatformInfo( String host, String platformUri, EnumSet<OcConnectivityType> connectivityTypeSet, OnPlatformFoundListener onPlatformFoundListener) throws OcException { OcPlatform.initCheck(); int connTypeInt = 0; for (OcConnectivityType connType : OcConnectivityType.values()) { if (connectivityTypeSet.contains(connType)) connTypeInt |= connType.getValue(); } OcPlatform.getPlatformInfo0( host, platformUri, connTypeInt, onPlatformFoundListener ); } private static native void getPlatformInfo0( String host, String platformUri, int connectivityType, OnPlatformFoundListener onPlatformInfoFoundListener) throws OcException; /** * API for Platform Discovery * * @param host Host IP Address. If null or empty, Multicast is performed. * @param platformUri Uri containing address to the platform * @param connectivityTypeSet Set of types of connectivity. Example: IP * @param onPlatformFoundListener Handles events, success states and failure states. * @param qualityOfService the quality of communication * @throws OcException if failure */ public static void getPlatformInfo( String host, String platformUri, EnumSet<OcConnectivityType> connectivityTypeSet, OnPlatformFoundListener onPlatformFoundListener, QualityOfService qualityOfService) throws OcException { OcPlatform.initCheck(); int connTypeInt = 0; for (OcConnectivityType connType : OcConnectivityType.values()) { if (connectivityTypeSet.contains(connType)) connTypeInt |= connType.getValue(); } OcPlatform.getPlatformInfo1( host, platformUri, connTypeInt, onPlatformFoundListener, qualityOfService.getValue() ); } private static native void getPlatformInfo1( String host, String platformUri, int connectivityType, OnPlatformFoundListener onPlatformFoundListener, int qualityOfService) throws OcException; /** * This API registers a resource with the server * <p/> * Note: This API applies to server & client side. * </P> * * @param ocResource The instance of OcResource with all data filled * @return resource handle * @throws OcException if failure */ public static OcResourceHandle registerResource( OcResource ocResource) throws OcException { OcPlatform.initCheck(); return OcPlatform.registerResource0(ocResource); } private static native OcResourceHandle registerResource0( OcResource ocResource) throws OcException; /** * This API registers a resource with the server NOTE: This API applies to server side only. * <p/> * Note: This API applies to server side only. * </P> * * @param resourceUri The URI of the resource. Example: "a/light" * @param resourceTypeName The resource type. Example: "light" * @param resourceInterface The resource interface (whether it is collection etc). * @param entityHandler entity handler. * @param resourcePropertySet indicates the property of the resource * @return resource handle * @throws OcException if failure */ public static OcResourceHandle registerResource( String resourceUri, String resourceTypeName, String resourceInterface, EntityHandler entityHandler, EnumSet<ResourceProperty> resourcePropertySet) throws OcException { OcPlatform.initCheck(); int resProperty = 0; for (ResourceProperty prop : ResourceProperty.values()) { if (resourcePropertySet.contains(prop)) resProperty |= prop.getValue(); } return OcPlatform.registerResource1(resourceUri, resourceTypeName, resourceInterface, entityHandler, resProperty); } private static native OcResourceHandle registerResource1( String resourceUri, String resourceTypeName, String resourceInterface, EntityHandler entityHandler, int resourceProperty) throws OcException; /** * Register Device Info * * @param ocDeviceInfo object containing all the device specific information * @throws OcException if failure */ public static void registerDeviceInfo( OcDeviceInfo ocDeviceInfo) throws OcException { OcPlatform.initCheck(); OcPlatform.registerDeviceInfo0( ocDeviceInfo.getDeviceName() ); } private static native void registerDeviceInfo0( String deviceName ) throws OcException; /** * Register Platform Info * * @param ocPlatformInfo object containing all the platform specific information * @throws OcException if failure */ public static void registerPlatformInfo( OcPlatformInfo ocPlatformInfo) throws OcException { OcPlatform.initCheck(); OcPlatform.registerPlatformInfo0( ocPlatformInfo.getPlatformId(), ocPlatformInfo.getManufacturerName(), ocPlatformInfo.getManufacturerUrl(), ocPlatformInfo.getModelNumber(), ocPlatformInfo.getDateOfManufacture(), ocPlatformInfo.getPlatformVersion(), ocPlatformInfo.getOperatingSystemVersion(), ocPlatformInfo.getHardwareVersion(), ocPlatformInfo.getFirmwareVersion(), ocPlatformInfo.getSupportUrl(), ocPlatformInfo.getSystemTime() ); } private static native void registerPlatformInfo0( String platformId, String manufacturerName, String manufacturerUrl, String modelNumber, String dateOfManufacture, String platformVersion, String operatingSystemVersion, String hardwareVersion, String firmwareVersion, String supportUrl, String systemTime ) throws OcException; /** * This API unregisters a resource with the server NOTE: This API applies to server side only. * * @param ocResourceHandle This is the resource handle which we which to unregister from the * server * @throws OcException if failure */ public static void unregisterResource( OcResourceHandle ocResourceHandle) throws OcException { OcPlatform.initCheck(); OcPlatform.unregisterResource0(ocResourceHandle); } private static native void unregisterResource0( OcResourceHandle ocResourceHandle) throws OcException; /** * Add a resource to a collection resource * * @param ocResourceCollectionHandle handle to the collection resource * @param ocResourceHandle handle to resource to be added to the collection resource * @throws OcException if failure */ public static void bindResource( OcResourceHandle ocResourceCollectionHandle, OcResourceHandle ocResourceHandle) throws OcException { OcPlatform.initCheck(); OcPlatform.bindResource0(ocResourceCollectionHandle, ocResourceHandle); } private static native void bindResource0( OcResourceHandle ocResourceCollectionHandle, OcResourceHandle ocResourceHandle) throws OcException; /** * Add multiple resources to a collection resource. * * @param ocResourceCollectionHandle handle to the collection resource * @param ocResourceHandleList reference to list of resource handles to be added to the * collection resource * @throws OcException if failure */ public static void bindResources( OcResourceHandle ocResourceCollectionHandle, List<OcResourceHandle> ocResourceHandleList) throws OcException { OcPlatform.initCheck(); OcPlatform.bindResources0( ocResourceCollectionHandle, ocResourceHandleList.toArray( new OcResourceHandle[ocResourceHandleList.size()]) ); } private static native void bindResources0( OcResourceHandle ocResourceCollectionHandle, OcResourceHandle[] ocResourceHandleArray) throws OcException; /** * Unbind a resource from a collection resource. * * @param ocResourceCollectionHandle handle to the collection resource * @param ocResourceHandle resource handle to be unbound from the collection resource * @throws OcException if failure */ public static void unbindResource( OcResourceHandle ocResourceCollectionHandle, OcResourceHandle ocResourceHandle) throws OcException { OcPlatform.initCheck(); OcPlatform.unbindResource0(ocResourceCollectionHandle, ocResourceHandle); } private static native void unbindResource0( OcResourceHandle ocResourceCollectionHandle, OcResourceHandle ocResourceHandle) throws OcException; /** * Unbind resources from a collection resource. * * @param ocResourceCollectionHandle Handle to the collection resource * @param ocResourceHandleList List of resource handles to be unbound from the collection * resource * @throws OcException if failure */ public static void unbindResources( OcResourceHandle ocResourceCollectionHandle, List<OcResourceHandle> ocResourceHandleList) throws OcException { OcPlatform.initCheck(); OcPlatform.unbindResources0( ocResourceCollectionHandle, ocResourceHandleList.toArray( new OcResourceHandle[ocResourceHandleList.size()]) ); } private static native void unbindResources0( OcResourceHandle ocResourceCollectionHandle, OcResourceHandle[] ocResourceHandleArray) throws OcException; /** * Binds a type to a particular resource * * @param ocResourceHandle handle to the resource * @param resourceTypeName new typename to bind to the resource * @throws OcException if failure */ public static void bindTypeToResource( OcResourceHandle ocResourceHandle, String resourceTypeName) throws OcException { OcPlatform.initCheck(); OcPlatform.bindTypeToResource0(ocResourceHandle, resourceTypeName); } private static native void bindTypeToResource0( OcResourceHandle ocResourceHandle, String resourceTypeName) throws OcException; /** * Binds an interface to a particular resource * * @param ocResourceHandle handle to the resource * @param resourceInterfaceName new interface to bind to the resource * @throws OcException if failure */ public static void bindInterfaceToResource( OcResourceHandle ocResourceHandle, String resourceInterfaceName) throws OcException { OcPlatform.initCheck(); OcPlatform.bindInterfaceToResource0(ocResourceHandle, resourceInterfaceName); } private static native void bindInterfaceToResource0( OcResourceHandle ocResourceHandle, String resourceInterfaceName) throws OcException; /** * Start Presence announcements. * * @param ttl time to live in seconds * @throws OcException if failure */ public static void startPresence(int ttl) throws OcException { OcPlatform.initCheck(); OcPlatform.startPresence0(ttl); } private static native void startPresence0(int ttl) throws OcException; /** * Stop Presence announcements. * * @throws OcException if failure */ public static void stopPresence() throws OcException { OcPlatform.initCheck(); OcPlatform.stopPresence0(); } private static native void stopPresence0() throws OcException; /** * Subscribes to a server's presence change events. By making this subscription, every time a * server adds/removes/alters a resource, starts or is intentionally stopped * * @param host The IP address/addressable name of the server to subscribe to * @param connectivityTypeSet Set of types of connectivity. Example: IP * @param onPresenceListener listener that will receive notifications/subscription events * @return a handle object that can be used to identify this subscription request. It can be * used to unsubscribe from these events in the future * @throws OcException if failure */ public static OcPresenceHandle subscribePresence( String host, EnumSet<OcConnectivityType> connectivityTypeSet, OnPresenceListener onPresenceListener) throws OcException { OcPlatform.initCheck(); int connTypeInt = 0; for (OcConnectivityType connType : OcConnectivityType.values()) { if (connectivityTypeSet.contains(connType)) connTypeInt |= connType.getValue(); } return OcPlatform.subscribePresence0( host, connTypeInt, onPresenceListener ); } private static native OcPresenceHandle subscribePresence0( String host, int connectivityType, OnPresenceListener onPresenceListener) throws OcException; /** * Subscribes to a server's presence change events. By making this subscription, every time a * server adds/removes/alters a resource, starts or is intentionally stopped * * @param host The IP address/addressable name of the server to subscribe to * @param resourceType a resource type specified as a filter for subscription events. * @param connectivityTypeSet Set of types of connectivity. Example: IP * @param onPresenceListener listener that will receive notifications/subscription events * @return a handle object that can be used to identify this subscription request. It can be * used to unsubscribe from these events in the future * @throws OcException if failure */ public static OcPresenceHandle subscribePresence( String host, String resourceType, EnumSet<OcConnectivityType> connectivityTypeSet, OnPresenceListener onPresenceListener) throws OcException { OcPlatform.initCheck(); int connTypeInt = 0; for (OcConnectivityType connType : OcConnectivityType.values()) { if (connectivityTypeSet.contains(connType)) connTypeInt |= connType.getValue(); } return OcPlatform.subscribePresence1( host, resourceType, connTypeInt, onPresenceListener); } private static native OcPresenceHandle subscribePresence1( String host, String resourceType, int connectivityType, OnPresenceListener onPresenceListener) throws OcException; /** * Unsubscribes from a previously subscribed server's presence events. Note that you may for * a short time still receive events from the server since it may take time for the * unsubscribe to take effect. * * @param ocPresenceHandle the handle object provided by the subscribePresence call that * identifies this subscription * @throws OcException if failure */ public static void unsubscribePresence( OcPresenceHandle ocPresenceHandle) throws OcException { OcPlatform.initCheck(); OcPlatform.unsubscribePresence0(ocPresenceHandle); } private static native void unsubscribePresence0( OcPresenceHandle ocPresenceHandle) throws OcException; /** * Creates a resource proxy object so that get/put/observe functionality can be used without * discovering the object in advance. Note that the consumer of this method needs to provide * all of the details required to correctly contact and observe the object. If the consumer * lacks any of this information, they should discover the resource object normally. * Additionally, you can only create this object if OcPlatform was initialized to be a Client * or Client/Server. * * @param host a string containing a resolvable host address of the server holding * the resource * @param uri the rest of the resource's URI that will permit messages to be * properly routed. * Example: /a/light * @param connectivityTypeSet Set of types of connectivity. Example: IP * @param isObservable a boolean containing whether the resource supports observation * @param resourceTypeList a collection of resource types implemented by the resource * @param interfaceList a collection of interfaces that the resource supports/implements * @return new resource object * @throws OcException if failure */ public static OcResource constructResourceObject( String host, String uri, EnumSet<OcConnectivityType> connectivityTypeSet, boolean isObservable, List<String> resourceTypeList, List<String> interfaceList) throws OcException { OcPlatform.initCheck(); int connTypeInt = 0; for (OcConnectivityType connType : OcConnectivityType.values()) { if (connectivityTypeSet.contains(connType)) connTypeInt |= connType.getValue(); } return OcPlatform.constructResourceObject0( host, uri, connTypeInt, isObservable, resourceTypeList.toArray(new String[resourceTypeList.size()]), interfaceList.toArray(new String[interfaceList.size()]) ); } private static native OcResource constructResourceObject0( String host, String uri, int connectivityType, boolean isObservable, String[] resourceTypes, String[] interfaces) throws OcException; /** * Allows application entity handler to send response to an incoming request. * * @param ocResourceResponse resource response * @throws OcException if failure */ public static void sendResponse(OcResourceResponse ocResourceResponse) throws OcException { OcPlatform.initCheck(); OcPlatform.sendResponse0(ocResourceResponse); } private static native void sendResponse0(OcResourceResponse ocResourceResponse) throws OcException; /** * An OnResourceFoundListener can be registered via the OcPlatform.findResource call. * Event listeners are notified asynchronously */ public interface OnResourceFoundListener { public void onResourceFound(OcResource resource); } /** * An OnDeviceFoundListener can be registered via the OcPlatform.getDeviceInfo call. * Event listeners are notified asynchronously */ public interface OnDeviceFoundListener { public void onDeviceFound(OcRepresentation ocRepresentation); } /** * An OnPlatformFoundListener can be registered via the OcPlatform.getPlatformInfo call. * Event listeners are notified asynchronously */ public interface OnPlatformFoundListener { public void onPlatformFound(OcRepresentation ocRepresentation); } /** * An OnPresenceListener can be registered via the OcPlatform.subscribePresence call. * Event listeners are notified asynchronously */ public interface OnPresenceListener { public void onPresence(OcPresenceStatus ocPresenceStatus, int nonce, String hostAddress); } /** * An EntityHandler can be registered via the OcPlatform.registerResource call. * Event listeners are notified asynchronously */ public interface EntityHandler { public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest); } private static void initCheck() { if (!sIsPlatformInitialized) { throw new IllegalStateException("OcPlatform must be configured by making a call to " + "OcPlatform.Configure before any other API calls are permitted"); } } /** * Gets platform quality of service * * @return quality of service */ public static QualityOfService getPlatformQualityOfService() { OcPlatform.initCheck(); return sPlatformQualityOfService; } }
santais/iotivity_1.1.0
android/android_api/base/src/main/java/org/iotivity/base/OcPlatform.java
Java
apache-2.0
36,142
/* * Copyright (c) 2012. Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yammer.metrics.reporting.jmx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.management.*; import java.util.Map; final class MetadataMBean implements DynamicMBean { private static final Logger LOGGER = LoggerFactory.getLogger(MetadataMBean.class); private final ObjectName name; private final MBeanInfo beanInfo; private final Map<String,PublishedAttribute> attrs; MetadataMBean( ObjectName name, MBeanInfo beanInfo, Map<String, PublishedAttribute> attrs) { this.name = name; this.beanInfo = beanInfo; this.attrs = attrs; } public ObjectName getObjectName() { return name; } public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException { PublishedAttribute attr = attrs.get(attribute); if (attr == null) { throw new AttributeNotFoundException(attribute); } try { return attr.getMetadata(); } catch (Exception e) { throw new MBeanException(e); } } public AttributeList getAttributes(String[] attributes) { AttributeList list = new AttributeList(); for (String a : attributes) { try { list.add(new Attribute(a, getAttribute(a))); } catch (Exception e) { LOGGER.warn("getAttribute() failed for " + a, e); } } return list; } public MBeanInfo getMBeanInfo() { return beanInfo; } public Object invoke( String actionName, Object[] params, String[] signature) { throw new UnsupportedOperationException( "invoke(...) is not supported on this mbean"); } public void setAttribute(Attribute attribute) { throw new UnsupportedOperationException( "setAttribute(...) is not supported on this mbean"); } public AttributeList setAttributes(AttributeList attributes) { throw new UnsupportedOperationException( "setAttributes(...) is not supported on this mbean"); } }
gorzell/metrics
metrics-core/src/main/java/com/yammer/metrics/reporting/jmx/MetadataMBean.java
Java
apache-2.0
2,805
// ================================================================================================= // Copyright 2011 Twitter, Inc. // ------------------------------------------------------------------------------------------------- // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this work except in compliance with the License. // You may obtain a copy of the License in the LICENSE file, or at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ================================================================================================= package com.twitter.common.zookeeper; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import org.apache.zookeeper.KeeperException; import com.twitter.common.base.Command; import com.twitter.common.base.ExceptionalCommand; import com.twitter.common.zookeeper.Group.GroupChangeListener; import com.twitter.common.zookeeper.Group.JoinException; import com.twitter.common.zookeeper.Group.Membership; import com.twitter.common.zookeeper.Group.WatchException; import com.twitter.common.zookeeper.ZooKeeperClient.ZooKeeperConnectionException; /** * Implements leader election for small groups of candidates. This implementation is subject to the * <a href="http://hadoop.apache.org/zookeeper/docs/r3.2.1/recipes.html#sc_leaderElection"> * herd effect</a> for a given group and should only be used for small (~10 member) candidate pools. * * @author John Sirois */ public class CandidateImpl implements Candidate { private static final Logger LOG = Logger.getLogger(CandidateImpl.class.getName()); private final Group group; private final Function<Iterable<String>, String> judge; private final Supplier<byte[]> dataSupplier; static final Supplier<byte[]> IP_ADDRESS_DATA_SUPPLIER = new Supplier<byte[]>() { @Override public byte[] get() { try { return InetAddress.getLocalHost().getAddress(); } catch (UnknownHostException e) { LOG.log(Level.WARNING, "Failed to determine local address!", e); return new byte[0]; } } }; public static final Function<Iterable<String>, String> MOST_RECENT_JUDGE = new Function<Iterable<String>, String>() { @Override public String apply(Iterable<String> candidates) { return Ordering.natural().min(candidates); } }; /** * Equivalent to {@link #CandidateImpl(Group, com.google.common.base.Function, Supplier)} using a judge that * always picks the lowest numbered candidate ephemeral node - by proxy the oldest or 1st * candidate and a default supplier that populates the data in the underlying znode with the byte representation * of the ip address according to {@link java.net.InetAddress#getLocalHost()}. */ public CandidateImpl(Group group) { this(group, MOST_RECENT_JUDGE, IP_ADDRESS_DATA_SUPPLIER); } /** * Creates a candidate that can be used to offer leadership for the given {@code group} using * a judge that always picks the lowest numbered candidate ephemeral node - by proxy the oldest * or 1st. The dataSupplier is the source of the data that will be stored in the leader-znode * and which is available to all participants via the getLeaderData method. */ public CandidateImpl(Group group, Supplier<byte[]> dataSupplier) { this(group, MOST_RECENT_JUDGE, dataSupplier); } /** * Creates a candidate that can be used to offer leadership for the given {@code group}. The * {@code judge} is used to pick the current leader from all group members whenever the group * membership changes. To form a well-behaved election group with one leader, all candidates * should use the same judge. The dataSupplier is the source of the data that will be stored * in the leader-znode and which is available to all participants via the getLeaderData method. */ public CandidateImpl(Group group, Function<Iterable<String>, String> judge, Supplier<byte[]> dataSupplier) { this.group = Preconditions.checkNotNull(group); this.judge = Preconditions.checkNotNull(judge); this.dataSupplier = Preconditions.checkNotNull(dataSupplier); } @Override public byte[] getLeaderData() throws ZooKeeperConnectionException, KeeperException, InterruptedException { String leaderId = getLeader(group.getMemberIds()); if (leaderId == null) { return null; } byte[] data = group.getMemberData(leaderId); return data == null ? new byte[0] : data; } @Override public Supplier<Boolean> offerLeadership(final Leader leader) throws JoinException, WatchException, InterruptedException { final Membership membership = group.join(dataSupplier, new Command() { @Override public void execute() { leader.onDefeated(); } }); final AtomicBoolean elected = new AtomicBoolean(false); final AtomicBoolean abdicated = new AtomicBoolean(false); group.watch(new GroupChangeListener() { @Override public void onGroupChange(Iterable<String> memberIds) { boolean noCandidates = Iterables.isEmpty(memberIds); String memberId = membership.getMemberId(); if (noCandidates) { LOG.warning("All candidates have temporarily left the group: " + group); } else if (!Iterables.contains(memberIds, memberId)) { LOG.severe(String.format( "Current member ID %s is not a candidate for leader, current voting: %s", memberId, memberIds)); } else { boolean electedLeader = memberId.equals(getLeader(memberIds)); boolean previouslyElected = elected.getAndSet(electedLeader); if (!previouslyElected && electedLeader) { LOG.info(String.format("Candidate %s is now leader of group: %s", membership.getMemberPath(), memberIds)); leader.onElected(new ExceptionalCommand<JoinException>() { @Override public void execute() throws JoinException { membership.cancel(); abdicated.set(true); } }); } else if (!electedLeader) { if (previouslyElected) { leader.onDefeated(); } LOG.info(String.format( "Candidate %s waiting for the next leader election, current voting: %s", membership.getMemberPath(), memberIds)); } } } }); return new Supplier<Boolean>() { @Override public Boolean get() { return !abdicated.get() && elected.get(); } }; } private String getLeader(Iterable<String> memberIds) { return judge.apply(memberIds); } }
imsut/commons
src/java/com/twitter/common/zookeeper/CandidateImpl.java
Java
apache-2.0
7,498
package com.springtraining.testscan; import java.util.Date; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.springframework.stereotype.Controller; import com.springtraining.SetterInj.Account; @Controller public class CurrentAccount implements Account{ private int accountNumber; private String accountName; private Date dob; public CurrentAccount() { super(); System.out.println("CurrentAccount() called"); } public String getDetails() { return this.accountNumber+" - "+this.accountName+" - "+this.dob ; } public int getAccountNumber() { return accountNumber; } public void setAccountNumber(int accountNumber) { this.accountNumber = accountNumber; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; System.out.println("setAccountName(String accountName)"); } public Date getDob() { return dob; } public void setDob(Date dob) { this.dob = dob; } @PostConstruct public void customInit(){ System.out.println("customInit() called"); } @PreDestroy public void cleanup(){ System.out.println("cleanup() called"); } }
Illusionist80/SpringTutorial
SpringChapter1-CorePartB-Annotation/src/com/springtraining/testscan/CurrentAccount.java
Java
apache-2.0
1,302
package jp.co.ctc_g.springbatch_sample.item_processor; import static org.junit.Assert.assertEquals; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mortbay.jetty.Server; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/jp/co/ctc_g/springbatch_sample/item_processor/item-enrichment-job.xml") public class ItemEnrichmentJobTest { private static final Server server = new Server(8085); @BeforeClass public static void init() throws Exception { server.setHandler(new WebServiceHandler()); server.start(); } @AfterClass public static void tearDown() throws Exception { server.stop(); } @Autowired private Job itemEnrichmentJob; @Autowired private Job asyncItemEnrichmentJob; @Autowired private JobLauncher jobLauncher; @Autowired private JdbcTemplate jdbcTemplate; @Before public void setUp() { jdbcTemplate.update("delete from contact"); } @Test public void warmingUp() throws Exception { for(int i=0;i<5;i++) { jobLauncher.run(itemEnrichmentJob, new JobParametersBuilder().addLong("time", System.currentTimeMillis()).toJobParameters()); } } @Test public void itemEnrichment() throws Exception { long start = System.currentTimeMillis(); JobExecution execution = jobLauncher.run(itemEnrichmentJob, new JobParametersBuilder().addLong("time", System.currentTimeMillis()).toJobParameters()); assertEquals(ExitStatus.COMPLETED, execution.getExitStatus()); System.out.println("sync job executed in "+(System.currentTimeMillis()-start)+" ms"); assertEquals(5,jdbcTemplate.queryForInt("select count(1) from contact")); List<Map<String,Object>> contacts = jdbcTemplate.queryForList("select * from contact"); for(Map<String,Object> item : contacts) { Assert.assertTrue(item.get("ssn").toString().length() == 9 + 2); Assert.assertTrue(item.get("ssn").toString().endsWith(item.get("id").toString())); } } @Test public void asyncItemEnrichment() throws Exception { long start = System.currentTimeMillis(); JobExecution execution = jobLauncher.run(asyncItemEnrichmentJob, new JobParametersBuilder().addLong("time", System.currentTimeMillis()).toJobParameters()); assertEquals(ExitStatus.COMPLETED, execution.getExitStatus()); System.out.println("async job executed in "+(System.currentTimeMillis()-start)+" ms"); assertEquals(5,jdbcTemplate.queryForInt("select count(1) from contact")); List<Map<String,Object>> contacts = jdbcTemplate.queryForList("select * from contact"); for(Map<String,Object> item : contacts) { Assert.assertTrue(item.get("ssn").toString().length() == 9 + 2); Assert.assertTrue(item.get("ssn").toString().endsWith(item.get("id").toString())); } } }
chiroru/spring-batch-sample
src/test/java/jp/co/ctc_g/springbatch_sample/item_processor/ItemEnrichmentJobTest.java
Java
apache-2.0
3,384
// // ======================================================================== // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.websocket.jsr356.server; import java.net.URI; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.websocket.ClientEndpointConfig; import javax.websocket.ContainerProvider; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.Extension; import javax.websocket.MessageHandler; import javax.websocket.SendHandler; import javax.websocket.SendResult; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import javax.websocket.server.ServerEndpointConfig; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.websocket.api.extensions.ExtensionFactory; import org.eclipse.jetty.websocket.api.extensions.OutgoingFrames; import org.eclipse.jetty.websocket.client.io.WebSocketClientConnection; import org.eclipse.jetty.websocket.common.extensions.ExtensionStack; import org.eclipse.jetty.websocket.common.extensions.compress.DeflateFrameExtension; import org.eclipse.jetty.websocket.jsr356.JsrExtension; import org.eclipse.jetty.websocket.jsr356.JsrSession; import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer; import org.eclipse.jetty.websocket.jsr356.server.samples.echo.BasicEchoEndpoint; import org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter; import org.junit.After; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.Test; public class ExtensionStackProcessingTest { private Server server; private ServerConnector connector; private ExtensionFactory serverExtensionFactory; private WebSocketContainer client; @Before public void prepare() throws Exception { server = new Server(); connector = new ServerConnector(server); server.addConnector(connector); ServletContextHandler context = new ServletContextHandler(server, "/", true, false); ServerContainer container = WebSocketServerContainerInitializer.configureContext(context); WebSocketUpgradeFilter filter = (WebSocketUpgradeFilter)context.getAttribute(WebSocketUpgradeFilter.class.getName()); serverExtensionFactory = filter.getFactory().getExtensionFactory(); ServerEndpointConfig config = ServerEndpointConfig.Builder.create(BasicEchoEndpoint.class, "/").build(); container.addEndpoint(config); client = ContainerProvider.getWebSocketContainer(); server.addBean(client, true); server.start(); } @After public void dispose() throws Exception { server.stop(); } @Test public void testDeflateFrameExtension() throws Exception { Assume.assumeTrue("Server has deflate-frame extension registered",serverExtensionFactory.isAvailable("deflate-frame")); ClientEndpointConfig config = ClientEndpointConfig.Builder.create() .extensions(Arrays.<Extension>asList(new JsrExtension("deflate-frame"))) .build(); final String content = "deflate_me"; final CountDownLatch messageLatch = new CountDownLatch(1); URI uri = URI.create("ws://localhost:" + connector.getLocalPort()); Session session = client.connectToServer(new EndpointAdapter() { @Override public void onMessage(String message) { Assert.assertEquals(content, message); messageLatch.countDown(); } }, config, uri); // Make sure everything is wired properly. OutgoingFrames firstOut = ((JsrSession)session).getOutgoingHandler(); Assert.assertTrue(firstOut instanceof ExtensionStack); ExtensionStack extensionStack = (ExtensionStack)firstOut; Assert.assertTrue(extensionStack.isRunning()); OutgoingFrames secondOut = extensionStack.getNextOutgoing(); Assert.assertTrue(secondOut instanceof DeflateFrameExtension); DeflateFrameExtension deflateExtension = (DeflateFrameExtension)secondOut; Assert.assertTrue(deflateExtension.isRunning()); OutgoingFrames thirdOut = deflateExtension.getNextOutgoing(); Assert.assertTrue(thirdOut instanceof WebSocketClientConnection); final CountDownLatch latch = new CountDownLatch(1); session.getAsyncRemote().sendText(content, new SendHandler() { @Override public void onResult(SendResult result) { latch.countDown(); } }); Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); Assert.assertTrue(messageLatch.await(5, TimeUnit.SECONDS)); } @Test public void testPerMessageDeflateExtension() throws Exception { Assume.assumeTrue("Server has permessage-deflate extension registered",serverExtensionFactory.isAvailable("permessage-deflate")); ClientEndpointConfig config = ClientEndpointConfig.Builder.create() .extensions(Arrays.<Extension>asList(new JsrExtension("permessage-deflate"))) .build(); final String content = "deflate_me"; final CountDownLatch messageLatch = new CountDownLatch(1); URI uri = URI.create("ws://localhost:" + connector.getLocalPort()); Session session = client.connectToServer(new EndpointAdapter() { @Override public void onMessage(String message) { Assert.assertEquals(content, message); messageLatch.countDown(); } }, config, uri); final CountDownLatch latch = new CountDownLatch(1); session.getAsyncRemote().sendText(content, new SendHandler() { @Override public void onResult(SendResult result) { latch.countDown(); } }); Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); Assert.assertTrue(messageLatch.await(5, TimeUnit.SECONDS)); } private static abstract class EndpointAdapter extends Endpoint implements MessageHandler.Whole<String> { @Override public void onOpen(Session session, EndpointConfig config) { session.addMessageHandler(this); } } }
sdw2330976/Research-jetty-9.2.5
jetty-websocket/javax-websocket-server-impl/src/test/java/org/eclipse/jetty/websocket/jsr356/server/ExtensionStackProcessingTest.java
Java
apache-2.0
7,238
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.skywalking.apm.plugin.jdbc; public class PreparedStatementParameterBuilder { private static final String EMPTY_LIST = "[]"; private Object[] parameters; private Integer maxIndex; private int maxLength = 0; public PreparedStatementParameterBuilder setParameters(Object[] parameters) { this.parameters = parameters; return this; } public PreparedStatementParameterBuilder setMaxIndex(int maxIndex) { this.maxIndex = maxIndex; return this; } public PreparedStatementParameterBuilder setMaxLength(int maxLength) { this.maxLength = maxLength; return this; } public String build() { if (parameters == null) { return EMPTY_LIST; } return getParameterString(); } private String getParameterString() { StringBuilder stringBuilder = new StringBuilder(); boolean first = true; for (int i = 0; i < getMaxIndex(); i++) { Object parameter = parameters[i]; if (!first) { stringBuilder.append(","); } stringBuilder.append(parameter); first = false; // cut the string as soon as it reached the length limitation if (maxLength > 0 && (stringBuilder.length() + EMPTY_LIST.length()) > maxLength) { return format(stringBuilder).substring(0, maxLength) + "..."; } } return format(stringBuilder); } private int getMaxIndex() { int maxIdx = maxIndex != null ? maxIndex : parameters.length; return Math.min(maxIdx, parameters.length); } private String format(StringBuilder stringBuilder) { return String.format("[%s]", stringBuilder.toString()); } }
wu-sheng/sky-walking
apm-sniffer/apm-sdk-plugin/jdbc-commons/src/main/java/org/apache/skywalking/apm/plugin/jdbc/PreparedStatementParameterBuilder.java
Java
apache-2.0
2,622
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.glue.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.glue.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * StartExportLabelsTaskRunRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class StartExportLabelsTaskRunRequestMarshaller { private static final MarshallingInfo<String> TRANSFORMID_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("TransformId").build(); private static final MarshallingInfo<String> OUTPUTS3PATH_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("OutputS3Path").build(); private static final StartExportLabelsTaskRunRequestMarshaller instance = new StartExportLabelsTaskRunRequestMarshaller(); public static StartExportLabelsTaskRunRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(StartExportLabelsTaskRunRequest startExportLabelsTaskRunRequest, ProtocolMarshaller protocolMarshaller) { if (startExportLabelsTaskRunRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(startExportLabelsTaskRunRequest.getTransformId(), TRANSFORMID_BINDING); protocolMarshaller.marshall(startExportLabelsTaskRunRequest.getOutputS3Path(), OUTPUTS3PATH_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/transform/StartExportLabelsTaskRunRequestMarshaller.java
Java
apache-2.0
2,438
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.route53domains.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * A complex type that contains information about whether the specified domain can be transferred to Route 53. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/route53domains-2014-05-15/DomainTransferability" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DomainTransferability implements Serializable, Cloneable, StructuredPojo { private String transferable; /** * @param transferable * @see Transferable */ public void setTransferable(String transferable) { this.transferable = transferable; } /** * @return * @see Transferable */ public String getTransferable() { return this.transferable; } /** * @param transferable * @return Returns a reference to this object so that method calls can be chained together. * @see Transferable */ public DomainTransferability withTransferable(String transferable) { setTransferable(transferable); return this; } /** * @param transferable * @return Returns a reference to this object so that method calls can be chained together. * @see Transferable */ public DomainTransferability withTransferable(Transferable transferable) { this.transferable = transferable.toString(); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getTransferable() != null) sb.append("Transferable: ").append(getTransferable()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DomainTransferability == false) return false; DomainTransferability other = (DomainTransferability) obj; if (other.getTransferable() == null ^ this.getTransferable() == null) return false; if (other.getTransferable() != null && other.getTransferable().equals(this.getTransferable()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getTransferable() == null) ? 0 : getTransferable().hashCode()); return hashCode; } @Override public DomainTransferability clone() { try { return (DomainTransferability) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.route53domains.model.transform.DomainTransferabilityMarshaller.getInstance().marshall(this, protocolMarshaller); } }
aws/aws-sdk-java
aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53domains/model/DomainTransferability.java
Java
apache-2.0
4,217
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.codecommit.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.codecommit.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * PullRequestMergedStateChangedEventMetadataMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class PullRequestMergedStateChangedEventMetadataMarshaller { private static final MarshallingInfo<String> REPOSITORYNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("repositoryName").build(); private static final MarshallingInfo<String> DESTINATIONREFERENCE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("destinationReference").build(); private static final MarshallingInfo<StructuredPojo> MERGEMETADATA_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("mergeMetadata").build(); private static final PullRequestMergedStateChangedEventMetadataMarshaller instance = new PullRequestMergedStateChangedEventMetadataMarshaller(); public static PullRequestMergedStateChangedEventMetadataMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(PullRequestMergedStateChangedEventMetadata pullRequestMergedStateChangedEventMetadata, ProtocolMarshaller protocolMarshaller) { if (pullRequestMergedStateChangedEventMetadata == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(pullRequestMergedStateChangedEventMetadata.getRepositoryName(), REPOSITORYNAME_BINDING); protocolMarshaller.marshall(pullRequestMergedStateChangedEventMetadata.getDestinationReference(), DESTINATIONREFERENCE_BINDING); protocolMarshaller.marshall(pullRequestMergedStateChangedEventMetadata.getMergeMetadata(), MERGEMETADATA_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-codecommit/src/main/java/com/amazonaws/services/codecommit/model/transform/PullRequestMergedStateChangedEventMetadataMarshaller.java
Java
apache-2.0
2,967
package br.unicamp.ic.lsd.mercurius.datatype; import java.io.Serializable; import java.math.BigDecimal; import java.util.List; public interface OrderProduct extends Serializable { /** * Returns the SKU of the {@link Product} of this {@link OrderProduct}. * * @return */ String getSku(); /** * Returns the {@link Product} of this {@link OrderProduct}. * * @return */ Product getProduct(); /** * Returns the attributes of the {@link Product} of this * {@link OrderProduct}. * * @return */ List<ProductAttribute> getProductAttributes(); /** * Returns the price of one item of this {@link OrderProduct}. * * @return */ BigDecimal getPrice(); /** * Sets the price of one item of this {@link OrderProduct}. * * @param price */ void setPrice(BigDecimal price); /** * Sets the special price of one item of this {@link OrderProduct}. * * @param price */ void setSpecialPrice(BigDecimal price); /** * Returns the special price of one item of this {@link OrderProduct}. * * @return */ BigDecimal getSpecialPrice(); /** * Returns the total price of this {@link OrderProduct}. This price is the * price of one item multiplied by the quantity of items. * * @return */ BigDecimal getTotalPrice(); /** * Returns the quantity of items of this {@link OrderProduct}. * * @return */ Integer getQuantity(); /** * Sets the quantity of items of this {@link OrderProduct}. * * @param quantity */ void setQuantity(Integer quantity); /** * Returns the {@link Order} that this {@link OrderProduct} is part of. * * @return */ Order getOrder(); /** * Sets order. * * @param quantity */ void setOrder(Order order); }
raphaelazzolini/mercurius
mercurius/datatype/src/main/java/br/unicamp/ic/lsd/mercurius/datatype/OrderProduct.java
Java
apache-2.0
1,738
// Copyright (c) Keith D Gregory // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.kdgregory.logback.aws.example; import java.lang.management.ManagementFactory; import java.util.Random; import javax.management.ObjectName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.kdgregory.logback.aws.StatisticsMBean; /** * Example program to generate log events of varying levels. * <p> * Invoke with the number of event-generator threads you want (default is 2): * <pre> * java -jar target/logback-aws-appenders-example-*.jar NUM_THREADS * </pre> * * Each thread will take a random walk, starting at the value 50 and moving up * or down by a small amount at each step. When the current value is in the * range 10..90, the program emits a debug log message. When in the range 0..9 * or 91..100, it emits a warning message. If the value moves outside of the * range 0..100, the program emits an error message and resets the value to the * bound. * <p> * Terminate the program when you've seen enough messages written to the logs. */ public class Main { private static Logger logger = LoggerFactory.getLogger(Main.class); public static void main(String[] argv) throws Exception { int numThreads = (argv.length > 0) ? Integer.parseInt(argv[0]) : 2; ManagementFactory.getPlatformMBeanServer().createMBean( StatisticsMBean.class.getName(), new ObjectName("com.kdgregory.logback.aws:name=statistics")); for (int ii = 0 ; ii < numThreads ; ii++) { Thread t = new Thread(new LogGeneratorRunnable(new Random(ii))); t.setName("example-" + ii); t.setDaemon(false); t.start(); } } private static class LogGeneratorRunnable implements Runnable { private Random rnd; private int value = 50; public LogGeneratorRunnable(Random rnd) { this.rnd = rnd; } @Override public void run() { while (true) { try { updateValue(); Thread.sleep(1000); } catch (InterruptedException ignored) { /* */ } } } private void updateValue() { value += 2 - rnd.nextInt(5); if (value < 0) { logger.error("value is " + value + "; was reset to 0"); value = 0; } else if (value > 100) { logger.error("value is " + value + "; was reset to 100"); value = 100; } else if ((value <= 10) || (value >= 90)) { logger.warn("value is " + value); } else { logger.debug("value is " + value); } } } }
kdgregory/log4j-aws-appenders
examples/logback-example/src/main/java/com/kdgregory/logback/aws/example/Main.java
Java
apache-2.0
3,526
package de.uniulm.omi.cloudiator.lance.application.component; import de.uniulm.omi.cloudiator.lance.lca.container.ContainerException; import de.uniulm.omi.cloudiator.lance.lifecycle.LifecycleStore; public class DeployableComponent extends AbstractComponent { private final LifecycleStore lifecycle; @Override public boolean isDynamicComponent() { return false; } @Override public boolean isDynamicHandler() { return false; } @Override public String getDynamicGroup() throws ContainerException { throw new ContainerException("Deployable Component cannot be in a dynamic group"); } @Override public String getDynamicHandler() throws ContainerException { throw new ContainerException("Deployable Component cannot be a dynamic group handler"); } public static class Builder extends AbstractComponent.Builder<Builder> { private volatile LifecycleStore lifecycle; public Builder(String name, ComponentId id) { //this.lifecycle = lifecycle; this.nameParam = name; this.myIdParam = id; } public Builder addLifecycleStore(LifecycleStore lifecycleStore) { this.lifecycle = lifecycleStore; return this; } public static Builder createBuilder(String name, ComponentId componentId) { return new Builder(name, componentId); } @Override public DeployableComponent build() { return new DeployableComponent(this); } @Override protected Builder self() { return this; } } private DeployableComponent(Builder builder) { super(builder); lifecycle = builder.lifecycle; } public LifecycleStore getLifecycleStore() { return lifecycle; } }
cloudiator/lance
common/src/main/java/de/uniulm/omi/cloudiator/lance/application/component/DeployableComponent.java
Java
apache-2.0
1,703
/******************************************************************************* * * This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim> * for the latest version of iBioSim. * * Copyright (C) 2017 University of Utah * * This library is free software; you can redistribute it and/or modify it * under the terms of the Apache License. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution * and also available online at <http://www.async.ece.utah.edu/ibiosim/License>. * *******************************************************************************/ package edu.utah.ece.async.ibiosim.conversion.scripts; import java.util.ArrayList; import java.util.HashMap; import dataModels.biomodel.util.ExperimentResult; import dataModels.biomodel.util.Utility; import frontend.main.Gui; public class GCMScript { public void generateThresholds(String directory, String species, double bestTime, int num) { double[] highs = new double[3 * num]; double[] lows = new double[3 * num]; for (int i = 1; i <= num; i++) { for (int j = 0; j < 3; j++) { double[] results = generateThreshold(directory + i, gate[j], species, bestTime); highs[3 * (i - 1) + j] = results[1]; lows[3 * (i - 1) + j] = results[0]; } } System.out.println("\nHigh:"); for (int i = 0; i < highs.length; i++) { System.out.print(highs[i] + " "); } System.out.println("\nLow:"); for (int i = 0; i < lows.length; i++) { System.out.print(lows[i] + " "); } } public double[] generateThreshold(String directory, String type, String species, double bestTime) { HashMap<String, double[]> results = null; double[] timeValues = null; double high = 0; double low = 0; int index = -1; results = Utility.calculateAverage(directory + Gui.separator + type + experiment[0]); timeValues = results.get("time"); for (int i = 0; i < timeValues.length; i++) { if (timeValues[i] > bestTime) { index = i - 1; break; } } low = results.get(species)[index]; results = Utility.calculateAverage(directory + Gui.separator + type + experiment[1]); high = results.get(species)[index]; double range = (high - low) / 3.; return new double[] { low + range, high - range }; } public double[][] generateThreshold(String directory, ArrayList<String> species, String type, double bestTime) { ExperimentResult highResults, lowResults = null; //double[] timeValues = null; double[] high = new double[species.size()]; double[] low = new double[species.size()]; //int index = -1; highResults = new ExperimentResult(Utility.calculateAverage(directory + Gui.separator + type + experiment[0])); lowResults = new ExperimentResult(Utility.calculateAverage(directory + Gui.separator + type + experiment[1])); for (int i = 0; i < species.size(); i++) { double range = (highResults.getValue(species.get(i), bestTime)-lowResults.getValue(species.get(i), bestTime)) / 3.; double t1 = highResults.getValue(species.get(i), bestTime)-range; double t2 = lowResults.getValue(species.get(i), bestTime)+range; if (t1 > t2) { high[i] = t1; low[i] = t2; } else { high[i] = t2; low[i] = t1; } } return new double[][] {low, high}; } public static double[][] generateStatistics(String directory, TesterInterface tester) { double[][] passed = null; String[] files = Utility.getTSDFiles(directory); for (int i = 0; i < files.length; i++) { boolean[] results = tester.passedTest(new ExperimentResult(directory+Gui.separator+files[i])); if (passed == null) { passed = new double[3][results.length]; } for (int j = 0; j < results.length; j++) { if (results[j]) { passed[1][j] = passed[1][j] + 1; } } } double[] times = tester.getTimes(); if (passed != null) { for (int i = 0; i < passed[0].length; i++) { passed[0][i] = times[i]; passed[1][i] = 1-passed[1][i]/files.length; passed[2][i] = 1.96*Math.sqrt(passed[1][i]*(1-passed[1][i])/files.length); } } return passed; } //private String[] kind = { "coop", "rep", "promoter" }; private String[] gate = { "maj", "tog", "si" }; private String[] experiment = { "-h-high", "-h-low", "-l-high", "-l-low" }; }
MyersResearchGroup/iBioSim
conversion/src/test/java/edu/utah/ece/async/ibiosim/conversion/scripts/GCMScript.java
Java
apache-2.0
4,325
/* * Copyright (C) 2014-2015 Nagisa Sekiguchi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package aquarius; /** * represent for token * * @author skgchxngsxyz-opensuse */ public class Token { protected int startPos; protected int size; public Token(int startPos, int size) { this.startPos = startPos; this.size = size; } /** * get token start position. inclusive * * @return */ public int getStartPos() { return this.startPos; } /** * get token text size. * * @return */ public int getSize() { return this.size; } @Override public String toString() { return "token<" + this.startPos + ":" + this.size + ">"; } @Override public boolean equals(Object target) { if(target instanceof Token) { Token token = (Token) target; return this.getStartPos() == token.getStartPos() && this.getSize() == token.getSize(); } return false; } }
sekiguchi-nagisa/Aquarius
aquarius-core/src/main/java/aquarius/Token.java
Java
apache-2.0
1,564
package edu.isi.karma.modeling.steiner.topk; import java.util.Set; /** * This class represents an edge in a steiner tree. It has a source node, a sink node, * an edge label and a weight. * @author kasneci * */ public class SteinerEdge extends Fact { protected SteinerNode sourceNode; protected SteinerNode sinkNode; boolean isForced; protected Set<String> modelIds; public SteinerEdge(SteinerNode n1, String l, SteinerNode n2, float weight){ super(new Entity(n1.getNodeId()),new Entity(n2.getNodeId()), new Relation(l),weight); sourceNode= n1;//n1-->n2 sinkNode= n2; isForced = false; } public int hashCode(){ return sourceNode.hashCode()^ label.name.hashCode()^ sinkNode.hashCode(); } public String getEdgeLabel(){ return label.name; } public SteinerNode getSourceNode(){ return sourceNode; } public SteinerNode getSinkNode(){ return sinkNode; } public Set<String> getModelIds() { return modelIds; } public void setModelIds(Set<String> modelIds) { this.modelIds = modelIds; } public boolean isForced() { return isForced; } public void setForced(boolean isForced) { this.isForced = isForced; } }
usc-isi-i2/Web-Karma
karma-common/src/main/java/edu/isi/karma/modeling/steiner/topk/SteinerEdge.java
Java
apache-2.0
1,263
/* * Copyright © 2013-2018 camunda services GmbH and various authors (info@camunda.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.application.impl; import org.camunda.bpm.application.ProcessApplicationInterface; import org.camunda.bpm.application.ProcessApplicationReference; import org.camunda.bpm.application.ProcessApplicationUnavailableException; /** * <p>The process engine holds a strong reference to the embedded process application.</p> * * @author Daniel Meyer * */ public class EmbeddedProcessApplicationReferenceImpl implements ProcessApplicationReference { protected EmbeddedProcessApplication application; public EmbeddedProcessApplicationReferenceImpl(EmbeddedProcessApplication application) { this.application = application; } public String getName() { return application.getName(); } public ProcessApplicationInterface getProcessApplication() throws ProcessApplicationUnavailableException { return application; } }
xasx/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/application/impl/EmbeddedProcessApplicationReferenceImpl.java
Java
apache-2.0
1,515
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http; import java.util.Iterator; /** * An iterator for {@link String} tokens. * This interface is designed as a complement to * {@link HeaderElementIterator}, in cases where the items * are plain strings rather than full header elements. * * @since 4.0 */ public interface TokenIterator extends Iterator<Object> { /** * Indicates whether there is another token in this iteration. * * @return <code>true</code> if there is another token, * <code>false</code> otherwise */ boolean hasNext(); /** * Obtains the next token from this iteration. * This method should only be called while {@link #hasNext hasNext} * is true. * * @return the next token in this iteration */ String nextToken(); }
FabioNgo/sound-cloud-player
apache_lib/src/org/apache/http/TokenIterator.java
Java
apache-2.0
1,986
package com.socks.jandan.adapter; import android.app.Activity; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.afollestad.materialdialogs.MaterialDialog; import com.android.volley.Response; import com.android.volley.VolleyError; import com.socks.jandan.R; import com.socks.jandan.base.ConstantString; import com.socks.jandan.base.JDApplication; import com.socks.jandan.callback.LoadFinishCallBack; import com.socks.jandan.callback.LoadResultCallBack; import com.socks.jandan.model.Comment4FreshNews; import com.socks.jandan.model.Commentator; import com.socks.jandan.net.Request4CommentList; import com.socks.jandan.net.Request4FreshNewsCommentList; import com.socks.jandan.net.RequestManager; import com.socks.jandan.ui.PushCommentActivity; import com.socks.jandan.utils.ShowToast; import com.socks.jandan.utils.String2TimeUtil; import com.socks.jandan.view.floorview.FloorView; import com.socks.jandan.view.floorview.SubComments; import com.socks.jandan.view.floorview.SubFloorFactory; import com.socks.jandan.view.imageloader.ImageLoadProxy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.Optional; /** * This Adapter is for Comment List ,what you need notice is that the comments for fresh news is special */ public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.CommentViewHolder> { private ArrayList<Commentator> commentators; private ArrayList<Comment4FreshNews> commentators4FreshNews; private Activity mActivity; private String thread_key; private String thread_id; private LoadResultCallBack mLoadResultCallBack; private boolean isFromFreshNews; public CommentAdapter(Activity activity, String thread_key, boolean isFromFreshNews, LoadResultCallBack loadResultCallBack) { mActivity = activity; this.thread_key = thread_key; this.isFromFreshNews = isFromFreshNews; mLoadResultCallBack = loadResultCallBack; if (isFromFreshNews) { commentators4FreshNews = new ArrayList<>(); } else { commentators = new ArrayList<>(); } } @Override public CommentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { case Commentator.TYPE_HOT: case Commentator.TYPE_NEW: return new CommentViewHolder(mActivity.getLayoutInflater().inflate(R.layout .item_comment_flag, parent, false)); case Commentator.TYPE_NORMAL: return new CommentViewHolder(mActivity.getLayoutInflater().inflate(R.layout.item_comment, parent, false)); default: return null; } } @Override public void onBindViewHolder(CommentViewHolder holder, int position) { Commentator commentator; if (isFromFreshNews) { commentator = commentators4FreshNews.get(position); } else { commentator = commentators.get(position); } switch (commentator.getType()) { case Commentator.TYPE_HOT: holder.tv_flag.setText("热门评论"); break; case Commentator.TYPE_NEW: holder.tv_flag.setText("最新评论"); break; case Commentator.TYPE_NORMAL: final Commentator comment = commentator; holder.tv_name.setText(commentator.getName()); holder.tv_content.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MaterialDialog.Builder(mActivity) .title(comment.getName()) .items(R.array.comment_dialog) .backgroundColor(mActivity.getResources().getColor(JDApplication.COLOR_OF_DIALOG)) .contentColor(JDApplication.COLOR_OF_DIALOG_CONTENT) .itemsCallback(new MaterialDialog.ListCallback() { @Override public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) { switch (which) { //评论 case 0: Intent intent = new Intent (mActivity, PushCommentActivity.class); intent.putExtra("parent_id", comment.getPost_id()); intent.putExtra("thread_id", thread_id); intent.putExtra("parent_name", comment .getName()); mActivity.startActivityForResult(intent, 0); break; case 1: //复制到剪贴板 ClipboardManager clip = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE); clip.setPrimaryClip(ClipData.newPlainText (null, comment.getMessage())); ShowToast.Short(ConstantString.COPY_SUCCESS); break; } } }).show(); } }); if (isFromFreshNews) { Comment4FreshNews commentators4FreshNews = (Comment4FreshNews) commentator; holder.tv_content.setText(commentators4FreshNews.getCommentContent()); ImageLoadProxy.displayHeadIcon(commentators4FreshNews.getAvatar_url(), holder.img_header); } else { String timeString = commentator.getCreated_at().replace("T", " "); timeString = timeString.substring(0, timeString.indexOf("+")); holder.tv_time.setText(String2TimeUtil.dateString2GoodExperienceFormat(timeString)); holder.tv_content.setText(commentator.getMessage()); ImageLoadProxy.displayHeadIcon(commentator.getAvatar_url(), holder.img_header); } //有楼层,盖楼 if (commentator.getFloorNum() > 1) { SubComments subComments; if (isFromFreshNews) { subComments = new SubComments(addFloors4FreshNews((Comment4FreshNews) commentator)); } else { subComments = new SubComments(addFloors(commentator)); } holder.floors_parent.setComments(subComments); holder.floors_parent.setFactory(new SubFloorFactory()); holder.floors_parent.setBoundDrawer(mActivity.getResources().getDrawable( R.drawable.bg_comment)); holder.floors_parent.init(); } else { holder.floors_parent.setVisibility(View.GONE); } break; } } private List<Comment4FreshNews> addFloors4FreshNews(Comment4FreshNews commentator) { return commentator.getParentComments(); } private List<Commentator> addFloors(Commentator commentator) { //只有一层 if (commentator.getFloorNum() == 1) { return null; } List<String> parentIds = Arrays.asList(commentator.getParents()); ArrayList<Commentator> commentators = new ArrayList<>(); for (Commentator comm : this.commentators) { if (parentIds.contains(comm.getPost_id())) { commentators.add(comm); } } Collections.reverse(commentators); return commentators; } @Override public int getItemCount() { if (isFromFreshNews) { return commentators4FreshNews.size(); } else { return commentators.size(); } } @Override public int getItemViewType(int position) { if (isFromFreshNews) { return commentators4FreshNews.get(position).getType(); } else { return commentators.get(position).getType(); } } public void loadData() { RequestManager.addRequest(new Request4CommentList(Commentator.getUrlCommentList(thread_key), new Response .Listener<ArrayList<Commentator>>() { @Override public void onResponse(ArrayList<Commentator> response) { if (response.size() == 0) { mLoadResultCallBack.onSuccess(LoadResultCallBack.SUCCESS_NONE, null); } else { commentators.clear(); ArrayList<Commentator> hotCommentator = new ArrayList<>(); ArrayList<Commentator> normalComment = new ArrayList<>(); //添加热门评论 for (Commentator commentator : response) { if (commentator.getTag().equals(Commentator.TAG_HOT)) { hotCommentator.add(commentator); } else { normalComment.add(commentator); } } //添加热门评论标签 if (hotCommentator.size() != 0) { Collections.sort(hotCommentator); Commentator hotCommentFlag = new Commentator(); hotCommentFlag.setType(Commentator.TYPE_HOT); hotCommentator.add(0, hotCommentFlag); commentators.addAll(hotCommentator); } //添加最新评论及标签 if (normalComment.size() != 0) { Commentator newCommentFlag = new Commentator(); newCommentFlag.setType(Commentator.TYPE_NEW); commentators.add(newCommentFlag); Collections.sort(normalComment); commentators.addAll(normalComment); } notifyDataSetChanged(); mLoadResultCallBack.onSuccess(LoadResultCallBack.SUCCESS_OK, null); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mLoadResultCallBack.onError(LoadResultCallBack.ERROR_NET, error.getMessage()); } }, new LoadFinishCallBack() { @Override public void loadFinish(Object obj) { thread_id = (String) obj; } }), mActivity); } public void loadData4FreshNews() { RequestManager.addRequest(new Request4FreshNewsCommentList(Comment4FreshNews.getUrlComments(thread_key), new Response .Listener<ArrayList<Comment4FreshNews>>() { @Override public void onResponse(ArrayList<Comment4FreshNews> response) { if (response.size() == 0) { mLoadResultCallBack.onSuccess(LoadResultCallBack.SUCCESS_NONE, null); } else { commentators4FreshNews.clear(); //如果评论条数大于6,就选择positive前6作为热门评论 if (response.size() > 6) { Comment4FreshNews comment4FreshNews = new Comment4FreshNews(); comment4FreshNews.setType(Comment4FreshNews.TYPE_HOT); commentators4FreshNews.add(comment4FreshNews); Collections.sort(response, new Comparator<Comment4FreshNews>() { @Override public int compare(Comment4FreshNews lhs, Comment4FreshNews rhs) { return lhs.getVote_positive() <= rhs.getVote_positive() ? 1 : -1; } }); List<Comment4FreshNews> subComments = response.subList(0, 6); for (Comment4FreshNews subComment : subComments) { subComment.setTag(Comment4FreshNews.TAG_HOT); } commentators4FreshNews.addAll(subComments); } Comment4FreshNews comment4FreshNews = new Comment4FreshNews(); comment4FreshNews.setType(Comment4FreshNews.TYPE_NEW); commentators4FreshNews.add(comment4FreshNews); Collections.sort(response); for (Comment4FreshNews comment4Normal : response) { if (comment4Normal.getTag().equals(Comment4FreshNews.TAG_NORMAL)) { commentators4FreshNews.add(comment4Normal); } } notifyDataSetChanged(); mLoadResultCallBack.onSuccess(LoadResultCallBack.SUCCESS_OK, null); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mLoadResultCallBack.onError(LoadResultCallBack.ERROR_NET, error.getMessage()); } }, new LoadFinishCallBack() { @Override public void loadFinish(Object obj) { thread_id = (String) obj; } }), mActivity); } public String getThreadId() { return thread_id; } static class CommentViewHolder extends RecyclerView.ViewHolder { @Optional @InjectView(R.id.tv_name) TextView tv_name; @Optional @InjectView(R.id.tv_content) TextView tv_content; @Optional @InjectView(R.id.tv_flag) TextView tv_flag; @Optional @InjectView(R.id.tv_time) TextView tv_time; @Optional @InjectView(R.id.img_header) ImageView img_header; @Optional @InjectView(R.id.floors_parent) FloorView floors_parent; public CommentViewHolder(View itemView) { super(itemView); ButterKnife.inject(this, itemView); setIsRecyclable(false); } } }
404neko/jandan_plus
app/src/main/java/com/socks/jandan/adapter/CommentAdapter.java
Java
apache-2.0
15,316
package com.communote.server.core.common.caching; import java.io.Serializable; import com.communote.server.api.core.security.AuthorizationException; /** * This element provider checks for authorization first. * * @param <T> * The cache key. * @param <U> * The object to cache. * @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a> * */ public interface AccessRestrictedCacheElementProvider<T extends CacheKey, U extends Serializable> extends CacheElementProvider<T, U> { /** * @param cacheKey * The cache key to check for. * @throws AuthorizationException * Thrown, when the user is not allowed to access the item. */ public void assertAccess(T cacheKey) throws AuthorizationException; }
Communote/communote-server
communote/persistence/src/main/java/com/communote/server/core/common/caching/AccessRestrictedCacheElementProvider.java
Java
apache-2.0
855
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.berkeley.ground.api.models.postgres; import edu.berkeley.ground.api.models.Tag; import edu.berkeley.ground.api.models.TagFactory; import edu.berkeley.ground.api.versions.GroundType; import edu.berkeley.ground.db.DBClient; import edu.berkeley.ground.db.DbDataContainer; import edu.berkeley.ground.db.PostgresClient; import edu.berkeley.ground.db.QueryResults; import edu.berkeley.ground.exceptions.EmptyResultException; import edu.berkeley.ground.exceptions.GroundException; import java.util.*; public class PostgresTagFactory extends TagFactory { private final PostgresClient dbClient; public PostgresTagFactory(PostgresClient dbClient) { this.dbClient = dbClient; } public Map<String, Tag> retrieveFromDatabaseByVersionId(long id) throws GroundException { return this.retrieveFromDatabaseById(id, "rich_version"); } public Map<String, Tag> retrieveFromDatabaseByItemId(long id) throws GroundException { return this.retrieveFromDatabaseById(id, "item"); } private Map<String, Tag> retrieveFromDatabaseById(long id, String keyPrefix) throws GroundException { List<DbDataContainer> predicates = new ArrayList<>(); predicates.add(new DbDataContainer(keyPrefix + "_id", GroundType.LONG, id)); Map<String, Tag> result = new HashMap<>(); QueryResults resultSet; try { resultSet = this.dbClient.equalitySelect(keyPrefix + "_tag", DBClient.SELECT_STAR, predicates); } catch (EmptyResultException e) { return new HashMap<>(); } do { String key = resultSet.getString(2); // these methods will return null if the input is null, so there's no need to check GroundType type = GroundType.fromString(resultSet.getString(4)); String valueString = resultSet.getString(3); Object value = GroundType.stringToType(valueString, type); result.put(key, new Tag(id, key, value, type)); } while (resultSet.next()); return result; } public List<Long> getVersionIdsByTag(String tag) throws GroundException { return this.getIdsByTag(tag, "rich_version"); } public List<Long> getItemIdsByTag(String tag) throws GroundException { return this.getIdsByTag(tag, "item"); } private List<Long> getIdsByTag(String tag, String keyPrefix) throws GroundException { List<DbDataContainer> predicates = new ArrayList<>(); predicates.add(new DbDataContainer("key", GroundType.STRING, tag)); QueryResults resultSet; try { resultSet = this.dbClient.equalitySelect(keyPrefix + "_tag", DBClient.SELECT_STAR, predicates); } catch (EmptyResultException e) { return new ArrayList<>(); } List<Long> result = new ArrayList<>(); do { result.add(resultSet.getLong(1)); } while (resultSet.next()); return result; } }
ramach/ground
ground-core/src/main/java/edu/berkeley/ground/api/models/postgres/PostgresTagFactory.java
Java
apache-2.0
3,360
/* * Copyright 2013-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.feign; import java.util.Map; import org.springframework.beans.BeansException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; import feign.Client; import feign.Contract; import feign.Feign; import feign.Logger; import feign.Request; import feign.RequestInterceptor; import feign.Retryer; import feign.Target.HardCodedTarget; import feign.codec.Decoder; import feign.codec.Encoder; import feign.codec.ErrorDecoder; import feign.slf4j.Slf4jLogger; import lombok.Data; import lombok.EqualsAndHashCode; /** * @author Spencer Gibb */ @Data @EqualsAndHashCode(callSuper = false) class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean, ApplicationContextAware { private static final Targeter targeter; static { Targeter targeterToUse; if (ClassUtils.isPresent("feign.hystrix.HystrixFeign", FeignClientFactoryBean.class.getClassLoader())) { targeterToUse = new HystrixTargeter(); } else { targeterToUse = new DefaultTargeter(); } targeter = targeterToUse; } private Class<?> type; private String name; private String url; private boolean decode404; private ApplicationContext applicationContext; private Class<?> fallback = void.class; @Override public void afterPropertiesSet() throws Exception { Assert.hasText(this.name, "Name must be set"); } @Override public void setApplicationContext(ApplicationContext context) throws BeansException { this.applicationContext = context; } protected Feign.Builder feign(FeignContext context) { Logger logger = getOptional(context, Logger.class); if (logger == null) { logger = new Slf4jLogger(this.type); } // @formatter:off Feign.Builder builder = get(context, Feign.Builder.class) // required values .logger(logger) .encoder(get(context, Encoder.class)) .decoder(get(context, Decoder.class)) .contract(get(context, Contract.class)); // @formatter:on // optional values Logger.Level level = getOptional(context, Logger.Level.class); if (level != null) { builder.logLevel(level); } Retryer retryer = getOptional(context, Retryer.class); if (retryer != null) { builder.retryer(retryer); } ErrorDecoder errorDecoder = getOptional(context, ErrorDecoder.class); if (errorDecoder != null) { builder.errorDecoder(errorDecoder); } Request.Options options = getOptional(context, Request.Options.class); if (options != null) { builder.options(options); } Map<String, RequestInterceptor> requestInterceptors = context.getInstances( this.name, RequestInterceptor.class); if (requestInterceptors != null) { builder.requestInterceptors(requestInterceptors.values()); } if (decode404) { builder.decode404(); } return builder; } protected <T> T get(FeignContext context, Class<T> type) { T instance = context.getInstance(this.name, type); if (instance == null) { throw new IllegalStateException("No bean found of type " + type + " for " + this.name); } return instance; } protected <T> T getOptional(FeignContext context, Class<T> type) { return context.getInstance(this.name, type); } protected <T> T loadBalance(Feign.Builder builder, FeignContext context, HardCodedTarget<T> target) { Client client = getOptional(context, Client.class); if (client != null) { builder.client(client); return targeter.target(this, builder, context, target); } throw new IllegalStateException( "No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-ribbon?"); } @Override public Object getObject() throws Exception { FeignContext context = applicationContext.getBean(FeignContext.class); Feign.Builder builder = feign(context); if (!StringUtils.hasText(this.url)) { String url; if (!this.name.startsWith("http")) { url = "http://" + this.name; } else { url = this.name; } return loadBalance(builder, context, new HardCodedTarget<>(this.type, this.name, url)); } if (StringUtils.hasText(this.url) && !this.url.startsWith("http")) { this.url = "http://" + this.url; } return targeter.target(this, builder, context, new HardCodedTarget<>( this.type, this.name, this.url)); } @Override public Class<?> getObjectType() { return this.type; } @Override public boolean isSingleton() { return true; } interface Targeter { <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context, HardCodedTarget<T> target); } static class DefaultTargeter implements Targeter { @Override public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context, HardCodedTarget<T> target) { return feign.target(target); } } @SuppressWarnings("unchecked") static class HystrixTargeter implements Targeter { @Override public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context, HardCodedTarget<T> target) { if (factory.fallback == void.class || !(feign instanceof feign.hystrix.HystrixFeign.Builder)) { return feign.target(target); } Object fallbackInstance = context.getInstance(factory.name, factory.fallback); if (fallbackInstance == null) { throw new IllegalStateException(String.format( "No fallback instance of type %s found for feign client %s", factory.fallback, factory.name)); } if (!target.type().isAssignableFrom(factory.fallback)) { throw new IllegalStateException( String.format( "Incompatible fallback instance. Fallback of type %s is not assignable to %s for feign client %s", factory.fallback, target.type(), factory.name)); } feign.hystrix.HystrixFeign.Builder builder = (feign.hystrix.HystrixFeign.Builder) feign; return builder.target(target, (T) fallbackInstance); } } }
jmnarloch/spring-cloud-netflix
spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/feign/FeignClientFactoryBean.java
Java
apache-2.0
6,791
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /** * ModifyInstanceAttributeType.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.5.1 Built on : Oct 19, 2009 (10:59:34 EDT) */ package com.amazon.ec2; /** * ModifyInstanceAttributeType bean class */ public class ModifyInstanceAttributeType implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = ModifyInstanceAttributeType Namespace URI = http://ec2.amazonaws.com/doc/2009-10-31/ Namespace Prefix = ns1 */ private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://ec2.amazonaws.com/doc/2009-10-31/")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * field for InstanceId */ protected java.lang.String localInstanceId ; /** * Auto generated getter method * @return java.lang.String */ public java.lang.String getInstanceId(){ return localInstanceId; } /** * Auto generated setter method * @param param InstanceId */ public void setInstanceId(java.lang.String param){ this.localInstanceId=param; } /** * field for ModifyInstanceAttributeTypeChoice_type0 */ protected com.amazon.ec2.ModifyInstanceAttributeTypeChoice_type0 localModifyInstanceAttributeTypeChoice_type0 ; /** * Auto generated getter method * @return com.amazon.ec2.ModifyInstanceAttributeTypeChoice_type0 */ public com.amazon.ec2.ModifyInstanceAttributeTypeChoice_type0 getModifyInstanceAttributeTypeChoice_type0(){ return localModifyInstanceAttributeTypeChoice_type0; } /** * Auto generated setter method * @param param ModifyInstanceAttributeTypeChoice_type0 */ public void setModifyInstanceAttributeTypeChoice_type0(com.amazon.ec2.ModifyInstanceAttributeTypeChoice_type0 param){ this.localModifyInstanceAttributeTypeChoice_type0=param; } /** * isReaderMTOMAware * @return true if the reader supports MTOM */ public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) { boolean isReaderMTOMAware = false; try{ isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE)); }catch(java.lang.IllegalArgumentException e){ isReaderMTOMAware = false; } return isReaderMTOMAware; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,parentQName){ public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { ModifyInstanceAttributeType.this.serialize(parentQName,factory,xmlWriter); } }; return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl( parentQName,factory,dataSource); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,factory,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); if ((namespace != null) && (namespace.trim().length() > 0)) { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, parentQName.getLocalPart()); } else { if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } else { xmlWriter.writeStartElement(parentQName.getLocalPart()); } if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://ec2.amazonaws.com/doc/2009-10-31/"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":ModifyInstanceAttributeType", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "ModifyInstanceAttributeType", xmlWriter); } } namespace = "http://ec2.amazonaws.com/doc/2009-10-31/"; if (! namespace.equals("")) { prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); xmlWriter.writeStartElement(prefix,"instanceId", namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } else { xmlWriter.writeStartElement(namespace,"instanceId"); } } else { xmlWriter.writeStartElement("instanceId"); } if (localInstanceId==null){ // write the nil attribute throw new org.apache.axis2.databinding.ADBException("instanceId cannot be null!!"); }else{ xmlWriter.writeCharacters(localInstanceId); } xmlWriter.writeEndElement(); if (localModifyInstanceAttributeTypeChoice_type0==null){ throw new org.apache.axis2.databinding.ADBException("ModifyInstanceAttributeTypeChoice_type0 cannot be null!!"); } localModifyInstanceAttributeTypeChoice_type0.serialize(null,factory,xmlWriter); xmlWriter.writeEndElement(); } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2009-10-31/", "instanceId")); if (localInstanceId != null){ elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localInstanceId)); } else { throw new org.apache.axis2.databinding.ADBException("instanceId cannot be null!!"); } elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2009-10-31/", "ModifyInstanceAttributeTypeChoice_type0")); if (localModifyInstanceAttributeTypeChoice_type0==null){ throw new org.apache.axis2.databinding.ADBException("ModifyInstanceAttributeTypeChoice_type0 cannot be null!!"); } elementList.add(localModifyInstanceAttributeTypeChoice_type0); return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static ModifyInstanceAttributeType parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ ModifyInstanceAttributeType object = new ModifyInstanceAttributeType(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"ModifyInstanceAttributeType".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (ModifyInstanceAttributeType)com.amazon.ec2.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2009-10-31/","instanceId").equals(reader.getName())){ java.lang.String content = reader.getElementText(); object.setInstanceId( org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content)); reader.next(); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() ){ object.setModifyInstanceAttributeTypeChoice_type0(com.amazon.ec2.ModifyInstanceAttributeTypeChoice_type0.Factory.parse(reader)); } // End of if for expected property start element while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement()) // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
cinderella/incubator-cloudstack
awsapi/src/com/amazon/ec2/ModifyInstanceAttributeType.java
Java
apache-2.0
25,300
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.sqs.model.transform; import org.w3c.dom.Node; import javax.annotation.Generated; import com.amazonaws.AmazonServiceException; import com.amazonaws.transform.StandardErrorUnmarshaller; import com.amazonaws.services.sqs.model.QueueDoesNotExistException; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class QueueDoesNotExistExceptionUnmarshaller extends StandardErrorUnmarshaller { public QueueDoesNotExistExceptionUnmarshaller() { super(QueueDoesNotExistException.class); } @Override public AmazonServiceException unmarshall(Node node) throws Exception { // Bail out if this isn't the right error code that this // marshaller understands String errorCode = parseErrorCode(node); if (errorCode == null || !errorCode.equals("AWS.SimpleQueueService.NonExistentQueue")) return null; QueueDoesNotExistException e = (QueueDoesNotExistException) super.unmarshall(node); return e; } }
aws/aws-sdk-java
aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/model/transform/QueueDoesNotExistExceptionUnmarshaller.java
Java
apache-2.0
1,601
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.lightsail.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.lightsail.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * CreateContainerServiceResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateContainerServiceResultJsonUnmarshaller implements Unmarshaller<CreateContainerServiceResult, JsonUnmarshallerContext> { public CreateContainerServiceResult unmarshall(JsonUnmarshallerContext context) throws Exception { CreateContainerServiceResult createContainerServiceResult = new CreateContainerServiceResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return createContainerServiceResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("containerService", targetDepth)) { context.nextToken(); createContainerServiceResult.setContainerService(ContainerServiceJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return createContainerServiceResult; } private static CreateContainerServiceResultJsonUnmarshaller instance; public static CreateContainerServiceResultJsonUnmarshaller getInstance() { if (instance == null) instance = new CreateContainerServiceResultJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/transform/CreateContainerServiceResultJsonUnmarshaller.java
Java
apache-2.0
2,945
/* * Copyright 2018 Yan Zhenjie * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yanzhenjie.album.mvp; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.PermissionChecker; import android.support.v7.app.AppCompatActivity; import com.yanzhenjie.album.Album; import com.yanzhenjie.album.util.AlbumUtils; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * Created by YanZhenjie on 2018/4/6. */ public class BaseActivity extends AppCompatActivity implements Bye { public static final String[] PERMISSION_TAKE_PICTURE = {"android.permission.CAMERA", "android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"}; public static final String[] PERMISSION_TAKE_VIDEO = {"android.permission.CAMERA", "android.permission.RECORD_AUDIO", "android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"}; public static final String[] PERMISSION_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"}; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Locale locale = Album.getAlbumConfig().getLocale(); AlbumUtils.applyLanguageForContext(this, locale); } /** * Request permission. */ protected void requestPermission(String[] permissions, int code) { if (Build.VERSION.SDK_INT >= 23) { List<String> deniedPermissions = getDeniedPermissions(this, permissions); if (deniedPermissions.isEmpty()) { onPermissionGranted(code); } else { permissions = new String[deniedPermissions.size()]; deniedPermissions.toArray(permissions); ActivityCompat.requestPermissions(this, permissions, code); } } else { onPermissionGranted(code); } } @Override public final void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (isGrantedResult(grantResults)) onPermissionGranted(requestCode); else onPermissionDenied(requestCode); } protected void onPermissionGranted(int code) { } protected void onPermissionDenied(int code) { } @Override public void bye() { onBackPressed(); } private static List<String> getDeniedPermissions(Context context, String... permissions) { List<String> deniedList = new ArrayList<>(2); for (String permission : permissions) { if (PermissionChecker.checkSelfPermission(context, permission) != PermissionChecker.PERMISSION_GRANTED) { deniedList.add(permission); } } return deniedList; } private static boolean isGrantedResult(int... grantResults) { for (int result : grantResults) { if (result == PackageManager.PERMISSION_DENIED) return false; } return true; } }
yanzhenjie/Album
album/src/main/java/com/yanzhenjie/album/mvp/BaseActivity.java
Java
apache-2.0
3,788
package tests.abstracttile; import code.model.AbstractTile; import code.model.MoveableTile; import static org.junit.Assert.*; import org.junit.Test; public class CheckLegalDirectionsInputTests { public void commonCode(int t, int b, int l, int r, boolean expected){ AbstractTile aT = new MoveableTile(); boolean actual = aT.checkLegalDirectionsInput(t, b, l, r); assertTrue("We expected " + expected + " but got " + actual, expected==actual); } @Test public void test05(){commonCode(0,0,1,1,true);} @Test public void test06(){commonCode(0,1,1,0,true);} @Test public void test07(){commonCode(1,1,0,0,true);} @Test public void test08(){commonCode(1,0,0,1,true);} @Test public void test09(){commonCode(1,0,1,0,true);} @Test public void test10(){commonCode(0,1,0,1,true);} @Test public void test11(){commonCode(0,1,1,1,true);} @Test public void test12(){commonCode(1,1,0,1,true);} @Test public void test13(){commonCode(1,1,1,0,true);} @Test public void test14(){commonCode(1,0,1,1,true);} @Test public void test00(){commonCode(0,0,0,0,false);} @Test public void test01(){commonCode(0,0,0,1,false);} @Test public void test02(){commonCode(0,0,1,0,false);} @Test public void test03(){commonCode(0,1,0,0,false);} @Test public void test04(){commonCode(1,0,0,0,false);} @Test public void test15(){commonCode(1,1,1,1,false);} @Test public void test16(){commonCode(1,1,2,0,false);} @Test public void test17(){commonCode(1,2,1,0,false);} @Test public void test18(){commonCode(2,1,1,0,false);} @Test public void test19(){commonCode(0,1,1,2,false);} @Test public void test20(){commonCode(0,2,1,1,false);} @Test public void test21(){commonCode(1,1,0,2,false);} @Test public void test22(){commonCode(2,0,1,1,false);} @Test public void test23(){commonCode(0,1,2,1,false);} @Test public void test25(){commonCode(0,0,0,2,false);} @Test public void test26(){commonCode(0,0,2,0,false);} @Test public void test27(){commonCode(0,2,0,0,false);} @Test public void test28(){commonCode(2,0,0,0,false);} @Test public void test29(){commonCode(0,0,2,2,false);} @Test public void test30(){commonCode(0,2,2,0,false);} @Test public void test31(){commonCode(2,2,0,0,false);} @Test public void test32(){commonCode(0,2,0,2,false);} @Test public void test33(){commonCode(2,0,2,0,false);} @Test public void test34(){commonCode(2,0,0,2,false);} @Test public void test35(){commonCode(0,0,0,-2,false);} @Test public void test36(){commonCode(0,0,-2,0,false);} @Test public void test37(){commonCode(0,-2,0,0,false);} @Test public void test38(){commonCode(-2,0,0,0,false);} @Test public void test39(){commonCode(0,0,-2,-2,false);} @Test public void test40(){commonCode(0,-2,-2,0,false);} @Test public void test41(){commonCode(-2,-2,0,0,false);} @Test public void test42(){commonCode(0,-2,0,-2,false);} @Test public void test43(){commonCode(-2,0,-2,0,false);} @Test public void test44(){commonCode(-2,0,0,-2,false);} @Test public void test45(){commonCode(0,0,2,1,false);} @Test public void test46(){commonCode(0,2,1,0,false);} @Test public void test47(){commonCode(2,1,0,0,false);} @Test public void test48(){commonCode(0,2,0,1,false);} @Test public void test49(){commonCode(2,0,1,0,false);} @Test public void test50(){commonCode(2,0,0,1,false);} @Test public void test51(){commonCode(0,0,1,2,false);} @Test public void test52(){commonCode(0,1,2,0,false);} @Test public void test53(){commonCode(1,2,0,0,false);} @Test public void test54(){commonCode(0,1,0,2,false);} @Test public void test55(){commonCode(1,0,2,0,false);} @Test public void test56(){commonCode(1,0,0,2,false);} @Test public void test57(){commonCode(1,1,1,2,false);} @Test public void test58(){commonCode(1,1,2,1,false);} @Test public void test59(){commonCode(2,1,1,1,false);} @Test public void test60(){commonCode(100,2,69,2,false);} @Test public void test61(){commonCode(2,50,2,90,false);} @Test public void test62(){commonCode(-1000,1000,30,67,false);} }
anandimous/Master_Labyrinth-Game
Stage_2/src/tests/abstracttile/CheckLegalDirectionsInputTests.java
Java
apache-2.0
4,073
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *******************************************************************************/ package org.apache.wink.common.internal.lifecycle; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.apache.wink.common.internal.registry.metadata.ClassMetadata; import org.apache.wink.common.spi.lifecycle.ObjectCreationException; import org.apache.wink.common.spi.lifecycle.ObjectFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * The only reason to extend LifecycleManagerUtils is to get easy access to collectClassMetadata method * */ public class JSR250LifecycleManagerUtils extends LifecycleManagerUtils { private static Logger logger = LoggerFactory.getLogger(JSR250LifecycleManagerUtils.class); // cache the @PostConstruct and @PreDestroy annotated methods so we don't have to do reflective search each time private static class PreDestroyMethod { private Method m; public PreDestroyMethod(Method _m) { m = _m; } public Method getMethod() { return m; } } private static class PostConstructMethod { private Method m; public PostConstructMethod(Method _m) { m = _m; } public Method getMethod() { return m; } } @SuppressWarnings("unchecked") private static Map<Class, PreDestroyMethod> preDestroyMethodCache = new HashMap<Class, PreDestroyMethod>(); @SuppressWarnings("unchecked") private static Map<Class, PostConstructMethod> postConstructMethodCache = new HashMap<Class, PostConstructMethod>(); public static <T> ObjectFactory<T> createSingletonObjectFactory(T object) { ObjectFactory<T> factory = LifecycleManagerUtils.createSingletonObjectFactory(object); executePostConstructMethod(factory.getInstance(null)); return new JSR250SingletonObjectFactory<T>(factory.getInstance(null)); } public static <T> ObjectFactory<T> createSingletonObjectFactory(final Class<T> cls) { ObjectFactory<T> factory = LifecycleManagerUtils.createSingletonObjectFactory(cls); executePostConstructMethod(factory.getInstance(null)); return new JSR250SingletonObjectFactory<T>(factory.getInstance(null)); } public static <T> ObjectFactory<T> createPrototypeObjectFactory(final Class<T> cls) { ClassMetadata classMetadata = collectClassMetadata(cls, true); return new JSR250PrototypeObjectFactory<T>(classMetadata); } @SuppressWarnings("unchecked") protected static <T> void executePostConstructMethod(T object) { if (object != null) { // check the cache if (postConstructMethodCache.containsKey((Class<T>)object.getClass())) { Method m = postConstructMethodCache.get((Class<T>)object.getClass()).getMethod(); if (m != null) { invokeMethod(object, m, null); if(logger.isTraceEnabled()) { logger.trace("Invoked PostConstruct annotated method {} for class {}", new Object[]{m, (Class<T>)object.getClass()}); } } else { if(logger.isTraceEnabled()) { logger.trace("No PostConstruct annotated method found for class {}", new Object[]{(Class<T>)object.getClass()}); } } return; } // no cache entry; do the search and populate the cache postConstructMethodCache.put((Class<T>)object.getClass(), new PostConstructMethod(null)); List<Method> methods = getMethods(object.getClass()); for (Method method : methods) { if (isPostConstruct(method)) { invokeMethod(object, method, null); // cache it postConstructMethodCache.put((Class<T>)object.getClass(), new PostConstructMethod(method)); // don't invoke all the @PostConstruct methods break; } } // logging: Method m = postConstructMethodCache.get((Class<T>)object.getClass()).getMethod(); if (m != null) { if(logger.isTraceEnabled()) { logger.trace("Invoked and cached PostConstruct annotated method {} for class {}", new Object[]{m, (Class<T>)object.getClass()}); } } else { if(logger.isTraceEnabled()) { logger.trace("No PostConstruct annotated method found for class {}, null value cached", new Object[]{(Class<T>)object.getClass()}); } } } } @SuppressWarnings("unchecked") protected static <T> void executePreDestroyMethod(T object) { if (object != null) { // check the cache if (preDestroyMethodCache.containsKey((Class<T>)object.getClass())) { Method m = preDestroyMethodCache.get((Class<T>)object.getClass()).getMethod(); if (m != null) { invokeMethod(object, m, null); if(logger.isTraceEnabled()) { logger.trace("Invoked PreDestroy annotated method {} for class {}", new Object[]{m, (Class<T>)object.getClass()}); } } else { if(logger.isTraceEnabled()) { logger.trace("No PreDestroy annotated method found for class {}", new Object[]{(Class<T>)object.getClass()}); } } return; } // no cache entry; do the search and populate the cache preDestroyMethodCache.put((Class<T>)object.getClass(), new PreDestroyMethod(null)); List<Method> methods = getMethods(object.getClass()); for (Method method : methods) { if (isPreDestroy(method)) { invokeMethod(object, method, null); // cache it preDestroyMethodCache.put((Class<T>)object.getClass(), new PreDestroyMethod(method)); // don't invoke all the @PreDestroy methods break; } } // logging: Method m = preDestroyMethodCache.get((Class<T>)object.getClass()).getMethod(); if (m != null) { if(logger.isTraceEnabled()) { logger.trace("Invoked and cached PreDestroy annotated method {} for class {}", new Object[]{m, (Class<T>)object.getClass()}); } } else { if(logger.isTraceEnabled()) { logger.trace("No PreDestroy annotated method found for class {}, null value cached", new Object[]{(Class<T>)object.getClass()}); } } } } // utility to detect existence of any method annotated with either @PostConstruct or @PreDestroy @SuppressWarnings("unchecked") protected static boolean hasJSR250AnnotatedMethod(Class clazz) { List<Method> methods = getMethods(clazz); for (Method method : methods) { if (isPreDestroy(method) || isPostConstruct(method)) { return true; } } return false; } @SuppressWarnings("unchecked") private static void invokeMethod(final Object object, final Method m, final Object[] params) throws ObjectCreationException { try { AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws InvocationTargetException, IllegalAccessException { return m.invoke(object, params); } } ); } catch (PrivilegedActionException e) { throw new ObjectCreationException(e.getException()); } } /** * Gets all of the methods in this class and the super classes * * @param beanClass * @return */ @SuppressWarnings("unchecked") private static List<Method> getMethods(final Class beanClass) { // This class must remain private due to Java 2 Security concerns List<Method> methods; methods = (List<Method>)AccessController.doPrivileged( new PrivilegedAction() { public Object run() { List<Method> methods = new ArrayList<Method>(); Class cls = beanClass; while (cls != null) { Method[] methodArray = cls.getDeclaredMethods(); for (Method method : methodArray) { methods.add(method); } cls = cls.getSuperclass(); } return methods; } } ); return methods; } @SuppressWarnings("unchecked") private static boolean isPostConstruct(final Method method) { Annotation[] annotations = (Annotation[]) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return method.getDeclaredAnnotations(); } } ); for (Annotation annotation : annotations) { return PostConstruct.class.isAssignableFrom(annotation.annotationType()); } return false; } @SuppressWarnings("unchecked") private static boolean isPreDestroy(final Method method) { Annotation[] annotations = (Annotation[]) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return method.getDeclaredAnnotations(); } } ); for (Annotation annotation : annotations) { return PreDestroy.class.isAssignableFrom(annotation.annotationType()); } return false; } }
os890/wink2_discuss
wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/JSR250LifecycleManagerUtils.java
Java
apache-2.0
11,492
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.reef.tests.files; import org.apache.reef.runtime.common.files.REEFFileNames; import org.apache.reef.tang.annotations.Parameter; import org.apache.reef.task.Task; import org.apache.reef.tests.library.exceptions.TaskSideFailure; import org.apache.reef.wake.time.Clock; import javax.inject.Inject; import java.io.File; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * An Task that checks the presence of a set of files and throws TaskSideFailure if they cannot be found or read. */ final class FileResourceTestTask implements Task { private final Logger LOG = Logger.getLogger(FileResourceTestTask.class.getName()); private final Set<String> expectedFileNames; private final Clock clock; private final File localFolder; @Inject FileResourceTestTask(@Parameter(FileResourceTestTaskConfiguration.FileNamesToExpect.class) final Set<String> expectedFileNames, final Clock clock, final REEFFileNames fileNames) { this.expectedFileNames = expectedFileNames; this.clock = clock; this.localFolder = fileNames.getLocalFolder(); } @Override public byte[] call(byte[] memento) throws Exception { for (final String fileName : expectedFileNames) { final File file = new File(localFolder, fileName); LOG.log(Level.INFO, "Testing file: " + file.getAbsolutePath()); if (!file.exists()) { throw new TaskSideFailure("Cannot find file: " + fileName); } else if (!file.isFile()) { throw new TaskSideFailure("Not a file: " + fileName); } else if (!file.canRead()) { throw new TaskSideFailure("Can't read: " + fileName); } } return new byte[0]; //To change body of implemented methods use File | Settings | File Templates. } }
taegeonum/incubator-reef
lang/java/reef-tests/src/test/java/org/apache/reef/tests/files/FileResourceTestTask.java
Java
apache-2.0
2,632
package com.iyzipay.google.cloud.vision.model; public class Position { private Double x; private Double y; private Double z; public Double getX() { return x; } public void setX(Double x) { this.x = x; } public Double getY() { return y; } public void setY(Double y) { this.y = y; } public Double getZ() { return z; } public void setZ(Double z) { this.z = z; } }
iyzico/google-cloud-java
google-cloud-vision/src/main/java/com/iyzipay/google/cloud/vision/model/Position.java
Java
apache-2.0
477
/* Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.freshplanet.inapppurchase; /** * Exception thrown when something went wrong with in-app billing. * An IabException has an associated IabResult (an error). * To get the IAB result that caused this exception to be thrown, * call {@link #getResult()}. */ public class IabException extends Exception { IabResult mResult; public IabException(IabResult r) { this(r, null); } public IabException(int response, String message) { this(new IabResult(response, message)); } public IabException(IabResult r, Exception cause) { super(r.getMessage(), cause); mResult = r; } public IabException(int response, String message, Exception cause) { this(new IabResult(response, message), cause); } /** Returns the IAB result (error) that this exception signals. */ public IabResult getResult() { return mResult; } }
alvinlaw/adobe-native-extension-in-app-purchase
NativeAndroid/src/com/freshplanet/inapppurchase/IabException.java
Java
apache-2.0
1,462
package com.example.deviceowner.common; public interface Notifiable { void notifyChanged(); }
raynor73/DeviceOwner
app/src/main/java/com/example/deviceowner/common/Notifiable.java
Java
apache-2.0
96
package com.liubo.account; import io.jsonwebtoken.Claims; import io.jsonwebtoken.ExpiredJwtException; import org.junit.Test; /** * Created by hzlbo on 2017/2/16 0016. */ public class JJWTUtilTest { @Test public void testGeneralKey() throws Exception { String token = new JJWTUtil().createJWT("10086", "18267190230", "liubo", 1000 * 60 * 30); System.out.println(token); } @Test public void testParse() throws Exception { Claims claims = null; try { claims = new JJWTUtil().parseJWT("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJsaXVibyIsInVzZXJJZCI6IjEwMDg2IiwicGhvbmUiOiIxODI2NzE5MDIzMCIsIm5hbWUiOiJsaXVibyIsImp0aSI6ImExMjUzNjA2LWRiMWYtNDk0NC04OWRhLTQ1N2JjNTUzZmJjMyIsImlhdCI6MTQ4NzIxNjQ4Miwic3ViIjoiMTAwODYiLCJleHAiOjE0ODcyMTgyODJ9.IfC040EKcA4Bapud-Mt2B987x1Cb4jMTABZdAl9xFo0"); System.out.println(claims.getSubject() + "|" + claims.getIssuer() + "|" + claims.get("phone")); } catch (ExpiredJwtException e) { System.out.println("token已经过期,重新登录"); } catch (Exception e) { e.printStackTrace(); } } }
liubo6/spring-cloud-microservices
liubo-account/src/test/java/com/liubo/account/JJWTUtilTest.java
Java
apache-2.0
1,159
package com.fruit.thememanager.helper; import com.fruit.thememanager.ThemeUtils.ThemeType; import android.content.Context; import android.util.Log; public class ThemeLoaderHelper { public static ThemeResourceLoader getThemeResLoader(Context context, ThemeInfo themeInfo) { ThemeResourceLoader loader = null; switch (themeInfo.mThemeType) { case THEME_DEFAULT: loader = new ThemeResourceDefaultLoader(context, themeInfo); break; case THEME_CUSTOM: loader = new ThemeResourceCustomLoader(context, themeInfo); break; default: break; } return loader; } public static ThemeInfoLoader getThemeInfoLoader(ThemeType themeType) { ThemeInfoLoader loader = null; Log.d("ThemeLoaderHelper", "Theme type=" + themeType); switch (themeType) { case THEME_DEFAULT: loader = ThemeInfoDefaultLoader.getInstance(); break; case THEME_CUSTOM: loader = ThemeInfoCustomLoader.getInstance(); break; default: break; } return loader; } }
yftx/fruit.thememanager
src/com/fruit/thememanager/helper/ThemeLoaderHelper.java
Java
apache-2.0
981
package edu.hku.sdb.connect; import edu.hku.sdb.conf.JDBCServerConf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.*; /** * Created by andy on 9/23/15. */ public class JDBCServerConnection extends ServerConnection{ private static final Logger LOG = LoggerFactory.getLogger(JDBCServerConnection.class); private java.sql.Connection connection; private java.sql.Statement statement; public JDBCServerConnection(JDBCServerConf jdbcServerConf) { String jdbcDriverName = jdbcServerConf.getJdbcDriverName(); String connectionURL = jdbcServerConf.getJdbcUrl() + "/" + jdbcServerConf.getDatabaseName(); String username = jdbcServerConf.getUsername(); String password = jdbcServerConf.getPassword(); try { Class.forName(jdbcDriverName); } catch (ClassNotFoundException e) { e.printStackTrace(); System.exit(1); } try { LOG.info("Connecting to server: " + connectionURL); connection = DriverManager.getConnection(connectionURL, username, password); } catch (SQLException e) { e.printStackTrace(); } } public void initStatment() { try { statement = connection.createStatement(); } catch (SQLException e) { e.printStackTrace(); } } @Override public void execute(String command) { if(statement == null) initStatment(); try { statement.execute(command); } catch (SQLException e) { e.printStackTrace(); } } @Override public ServerResultSet executeQuery(String query) { if(statement == null) initStatment(); try { JDBCResultSet resultSet = new JDBCResultSet(statement.executeQuery(query)); return resultSet; } catch (SQLException e) { e.printStackTrace(); } return null; } @Override public int executeUpdate(String query) { if(statement == null) initStatment(); try { return statement.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); } return -1; } @Override public void close() { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }
andyhehk/SecureDB
proxy/src/main/java/edu/hku/sdb/connect/JDBCServerConnection.java
Java
apache-2.0
2,193
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.impala.analysis; import org.apache.impala.catalog.FeFsPartition; import org.apache.impala.catalog.FeFsTable; import org.apache.impala.catalog.FeTable; import org.apache.impala.catalog.HdfsFileFormat; import org.apache.impala.catalog.RowFormat; import org.apache.impala.common.AnalysisException; import org.apache.impala.thrift.TAlterTableParams; import org.apache.impala.thrift.TAlterTableSetRowFormatParams; import org.apache.impala.thrift.TAlterTableType; /** * Represents an ALTER TABLE [PARTITION partitionSet] SET ROW FORMAT statement. */ public class AlterTableSetRowFormatStmt extends AlterTableSetStmt { private final RowFormat rowFormat_; public AlterTableSetRowFormatStmt(TableName tableName, PartitionSet partitionSet, RowFormat rowFormat) { super(tableName, partitionSet); rowFormat_ = rowFormat; } public RowFormat getRowFormat() { return rowFormat_; } @Override public TAlterTableParams toThrift() { TAlterTableParams params = super.toThrift(); params.setAlter_type(TAlterTableType.SET_ROW_FORMAT); TAlterTableSetRowFormatParams rowFormatParams = new TAlterTableSetRowFormatParams(getRowFormat().toThrift()); if (getPartitionSet() != null) { rowFormatParams.setPartition_set(getPartitionSet().toThrift()); } params.setSet_row_format_params(rowFormatParams); return params; } @Override public void analyze(Analyzer analyzer) throws AnalysisException { super.analyze(analyzer); FeTable tbl = getTargetTable(); if (!(tbl instanceof FeFsTable)) { throw new AnalysisException(String.format("ALTER TABLE SET ROW FORMAT is only " + "supported on HDFS tables. Conflicting table: %1$s", tbl.getFullName())); } if (partitionSet_ != null) { for (FeFsPartition partition: partitionSet_.getPartitions()) { if (partition.getFileFormat() != HdfsFileFormat.TEXT && partition.getFileFormat() != HdfsFileFormat.SEQUENCE_FILE) { throw new AnalysisException(String.format("ALTER TABLE SET ROW FORMAT is " + "only supported on TEXT or SEQUENCE file formats. " + "Conflicting partition/format: %1$s / %2$s", partition.getPartitionName(), HdfsFileFormat.fromHdfsInputFormatClass( partition.getFileFormat().inputFormat()).name())); } } } else { HdfsFileFormat format = HdfsFileFormat.fromHdfsInputFormatClass( ((FeFsTable) tbl).getMetaStoreTable().getSd().getInputFormat()); if (format != HdfsFileFormat.TEXT && format != HdfsFileFormat.SEQUENCE_FILE) { throw new AnalysisException(String.format("ALTER TABLE SET ROW FORMAT is " + "only supported on TEXT or SEQUENCE file formats. Conflicting " + "table/format: %1$s / %2$s", tbl.getFullName(), format.name())); } } } }
cloudera/Impala
fe/src/main/java/org/apache/impala/analysis/AlterTableSetRowFormatStmt.java
Java
apache-2.0
3,690
/* * 3D City Database - The Open Source CityGML Database * https://www.3dcitydb.org/ * * Copyright 2013 - 2021 * Chair of Geoinformatics * Technical University of Munich, Germany * https://www.lrg.tum.de/gis/ * * The 3D City Database is jointly developed with the following * cooperation partners: * * Virtual City Systems, Berlin <https://vc.systems/> * M.O.S.S. Computer Grafik Systeme GmbH, Taufkirchen <http://www.moss.de/> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.config.project.visExporter; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; @XmlType(name = "DisplayFormType", propOrder = { "active", "visibleFrom" }) public class DisplayForm { @XmlAttribute(required = true) private DisplayFormType type; private boolean active = false; private Integer visibleFrom; @XmlTransient private int visibleTo = -1; public DisplayForm() { } DisplayForm(DisplayFormType type) { this.type = type; } public static DisplayForm of(DisplayFormType type) { return new DisplayForm(type); } public boolean isAchievableFromLoD(int lod) { return type != null && type.isAchievableFromLoD(lod); } public String getName() { return type != null ? type.getName() : "unknown"; } public DisplayFormType getType() { return type; } public void setVisibleFrom(int visibleFrom) { this.visibleFrom = visibleFrom; } public int getVisibleFrom() { return visibleFrom != null ? visibleFrom : 0; } public void setVisibleTo(int visibleTo) { this.visibleTo = visibleTo; } public int getVisibleTo() { return visibleTo; } public void setActive(boolean active) { this.active = active; } public boolean isActive() { return active; } }
3dcitydb/importer-exporter
impexp-config/src/main/java/org/citydb/config/project/visExporter/DisplayForm.java
Java
apache-2.0
2,476
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.plugins.repository.vfs; import java.io.File; import java.io.IOException; import org.apache.ivy.util.FileUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; /** * Testing was the single biggest hurdle I faced. I have tried to provide a complete test * suite that covers all protocols and which can be easily extended. It does differ - somewhat - in * structure from the resolver/repository test suites. Setting up smb, ftp, sftp will undoubtedly be * your biggest headache (it was mine). Here are a few notes about the setup: * <ul> * <li>the VFS test suite uses the build/test/repositories area; * when setting samba, sftp, etc. the corresponding user needs both read and write privileges.</li> * <li>the tests assume that the user and password is the same for all services.</li> * <li>a limited amount of configuration is available by setting the following properties in the * <code>ivy.properties</code> file:</li> * </ul> * <pre> * vfs.host * vfs.username * vfs.password * vfs.samba_share * </pre> * Running the test requires that commons-io and ant jars are on the classpath. Also, I would * recommend that at some time the tests be converted from straight junit to something which better * supports functional testing. Although somewhat crude, I am using jsystem * (http://jsystemtest.sourceforge.net/) in other projects and am finding it a much better solution * than straight junit. * <p>Stephen Nesbitt</p> */ public class VfsRepositoryTest { private VfsRepository repo = null; private VfsTestHelper helper = null; private File scratchDir = null; @Before public void setUp() throws Exception { helper = new VfsTestHelper(); repo = new VfsRepository(); scratchDir = new File(FileUtil.concat(VfsTestHelper.TEST_REPO_DIR, VfsTestHelper.SCRATCH_DIR)); scratchDir.mkdir(); } @After public void tearDown() { repo = null; if (scratchDir.exists()) { FileUtil.forceDelete(scratchDir); } } /** * Basic validation of happy path put - valid VFS URI and no conflict with existing file * * @throws Exception if something goes wrong */ @Test public void testPutValid() throws Exception { String testResource = VfsTestHelper.TEST_IVY_XML; String srcFile = FileUtil.concat(VfsTestHelper.TEST_REPO_DIR, testResource); String destResource = VfsTestHelper.SCRATCH_DIR + "/" + testResource; String destFile = FileUtil.concat(VfsTestHelper.TEST_REPO_DIR, destResource); for (VfsURI vfsURI : helper.createVFSUriSet(destResource)) { if (scratchDir.exists()) { FileUtil.forceDelete(scratchDir); } repo.put(new File(srcFile), vfsURI.toString(), false); assertTrue("Put didn't happen. Src VfsURI: " + vfsURI.toString() + ".\nExpected file: " + destFile, new File(srcFile).exists()); } } /** * Validate that we can overwrite an existing file * * @throws Exception if something goes wrong */ @Test public void testPutOverwriteTrue() throws Exception { String testResource = VfsTestHelper.TEST_IVY_XML; String srcFile = FileUtil.concat(VfsTestHelper.TEST_REPO_DIR, testResource); String destResource = VfsTestHelper.SCRATCH_DIR + "/" + testResource; File destFile = new File(FileUtil.concat(VfsTestHelper.TEST_REPO_DIR, destResource)); for (VfsURI vfsURI : helper.createVFSUriSet(destResource)) { // remove existing scratch dir and populate it with an empty file // that we can overwrite. We do this so that we can test file sizes. // seeded file has length 0, while put file will have a length > 0 if (scratchDir.exists()) { FileUtil.forceDelete(scratchDir); } destFile.getParentFile().mkdirs(); destFile.createNewFile(); repo.put(new File(srcFile), vfsURI.toString(), true); assertTrue("Put didn't happen. Src VfsURI: " + vfsURI.toString() + ".\nExpected file: " + destFile, new File(srcFile).exists()); assertNotEquals("Zero file size indicates file not overwritten", 0, destFile.length()); } } /** * Validate that we put will respect a request not to overwrite an existing file * * @throws Exception if something goes wrong */ @Test(expected = IOException.class) public void testPutOverwriteFalse() throws Exception { String testResource = VfsTestHelper.TEST_IVY_XML; String srcFile = FileUtil.concat(VfsTestHelper.TEST_REPO_DIR, testResource); String destResource = VfsTestHelper.SCRATCH_DIR + "/" + testResource; File destFile = new File(FileUtil.concat(VfsTestHelper.TEST_REPO_DIR, destResource)); destFile.getParentFile().mkdirs(); destFile.createNewFile(); for (VfsURI vfsURI : helper.createVFSUriSet(destResource)) { repo.put(new File(srcFile), vfsURI.toString(), false); } } /** * Test the retrieval of an artifact from the repository creating a new artifact * * @throws Exception if something goes wrong */ @Test public void testGetNoExisting() throws Exception { String testResource = VfsTestHelper.TEST_IVY_XML; String testFile = FileUtil.concat(scratchDir.getAbsolutePath(), testResource); for (VfsURI vfsURI : helper.createVFSUriSet(testResource)) { if (scratchDir.exists()) { FileUtil.forceDelete(scratchDir); } repo.get(vfsURI.toString(), new File(testFile)); assertTrue("Expected file: " + testFile + "not found. Failed vfsURI: " + vfsURI.toString(), new File(testFile).exists()); } } /** * Test the retrieval of an artifact from the repository overwriting an existing artifact * * @throws Exception if something goes wrong */ @Test public void testGetOverwriteExisting() throws Exception { String testResource = VfsTestHelper.TEST_IVY_XML; File testFile = new File(FileUtil.concat(scratchDir.getAbsolutePath(), testResource)); for (VfsURI vfsURI : helper.createVFSUriSet(testResource)) { // setup - remove existing scratch area and populate with a file to override if (scratchDir.exists()) { FileUtil.forceDelete(scratchDir); } testFile.getParentFile().mkdirs(); testFile.createNewFile(); repo.get(vfsURI.toString(), testFile); assertTrue("Expected file: " + testFile + "not found. Failed vfsURI: " + vfsURI.toString(), testFile.exists()); assertNotEquals("Zero file size indicates file not overwritten", 0, testFile.length()); } } /** * Validate that we get a non null Resource instance when passed a well-formed VfsURI pointing * to an existing file * * @throws Exception if something goes wrong */ @Test public void testGetResourceValidExist() throws Exception { String testResource = VfsTestHelper.TEST_IVY_XML; for (VfsURI vfsURI : helper.createVFSUriSet(testResource)) { assertNotNull(repo.getResource(vfsURI.toString())); } } /** * Validate that we get a non null Resource instance when passed a well-formed VfsURI pointing * to a non-existent file. * * @throws Exception if something goes wrong */ @Test public void testGetResourceValidNoExist() throws Exception { String testResource = VfsTestHelper.SCRATCH_DIR + "/nosuchfile.jar"; for (VfsURI vfsURI : helper.createVFSUriSet(testResource)) { // make sure the declared resource does not exist if (scratchDir.exists()) { FileUtil.forceDelete(scratchDir); } assertNotNull(repo.getResource(vfsURI.toString())); } } }
jaikiran/ant-ivy
test/java/org/apache/ivy/plugins/repository/vfs/VfsRepositoryTest.java
Java
apache-2.0
9,169
package it.unifi.utility; import it.unifi.gameutility.Board; import it.unifi.gameutility.Player; import java.util.UUID; public class SingleGame { private Board board; private Player player; private String gameID; public SingleGame() { } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SingleGame that = (SingleGame) o; return gameID != null ? gameID.equals(that.gameID) : that.gameID == null; } @Override public int hashCode() { return gameID != null ? gameID.hashCode() : 0; } public SingleGame(Board board, Player player) { this.board = board; this.player = player; this.gameID = UUID.randomUUID().toString(); } public Board getBoard() { return board; } public void setBoard(Board board) { this.board = board; } public Player getPlayer() { return player; } public String getGameID() { return gameID; } }
iskorini/APT-Project
TicTacToeWeb/src/main/java/it/unifi/utility/SingleGame.java
Java
apache-2.0
1,084
package ml.options; /** * A structure to build a data graph. * <pre> * Field Name: Description : default * ------------------------------------------------------------------------------------------- * 'graphType': 'nn' | 'epsballs' : 'nn' * 'graphParam': number of nearest neighbor size of 'epsballs' : 6 * 'kernelType': 'linear' | 'rbf' | 'poly' | 'cosine' : 'linear' * 'kernelParam': -- | sigma | degree | -- : 1 * 'graphDistanceFunction': distance function for graph: 'euclidean' | 'cosine' : 'euclidean' * 'graphWeightType': 'binary' | 'distance' | 'heat' : 'binary' * 'graphWeightParam': e.g. for heat kernel, width to use : 1 * 'graphNormalize': Use normalized graph Laplacian (1) or not (0) : 1 * 'classEdges': Disconnect edges across classes:yes(1) no (0) : 0 * 'gamma_A': RKHS norm regularization parameter (Ambient) : 1 * 'gamma_I': Manifold regularization parameter (Intrinsic) : 1 * ------------------------------------------------------------------------------------------- * Note: Kernel and KernelParam are meant for calcKernel function. * </pre> * * @version 1.0 Jan. 27th, 2014 * @author Mingjie Qian */ public class GraphOptions { public String graphType; public double graphParam; public String kernelType; public double kernelParam; public String graphDistanceFunction; public String graphWeightType; public double graphWeightParam; public boolean graphNormalize; public boolean classEdges; /** * Generate/alter {@code GraphOptions} structure to build a data graph. * <pre> * Field Name: Description : default * ------------------------------------------------------------------------------------------- * 'graphType': 'nn' | 'epsballs' : 'nn' * 'graphParam': number of nearest neighbor size of 'epsballs' : 6 * 'kernelType': 'linear' | 'rbf' | 'poly' | 'cosine' : 'linear' * 'kernelParam': -- | sigma | degree | -- : 1 * 'graphDistanceFunction': distance function for graph: 'euclidean' | 'cosine' : 'euclidean' * 'graphWeightType': 'binary' | 'distance' | 'heat' : 'binary' * 'graphWeightParam': e.g. for heat kernel, width to use : 1 * 'graphNormalize': Use normalized graph Laplacian (1) or not (0) : 1 * 'classEdges': Disconnect edges across classes:yes(1) no (0) : 0 * 'gamma_A': RKHS norm regularization parameter (Ambient) : 1 * 'gamma_I': Manifold regularization parameter (Intrinsic) : 1 * ------------------------------------------------------------------------------------------- * Note: Kernel and KernelParam are meant for calcKernel function. * </pre> */ public GraphOptions() { graphType = "nn"; kernelType = "linear"; kernelParam = 1; graphParam = 6; graphDistanceFunction = "euclidean"; graphWeightType = "binary"; graphWeightParam = 1; graphNormalize = true; classEdges = false; } public GraphOptions(GraphOptions graphOtions) { graphType = graphOtions.graphType; kernelType = graphOtions.kernelType; kernelParam = graphOtions.kernelParam; graphParam = graphOtions.graphParam; graphDistanceFunction = graphOtions.graphDistanceFunction; graphWeightType = graphOtions.graphWeightType; graphWeightParam = graphOtions.graphWeightParam; graphNormalize = graphOtions.graphNormalize; classEdges = graphOtions.classEdges; } }
MingjieQian/LAML
src/ml/options/GraphOptions.java
Java
apache-2.0
3,960
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package de.schenk.objectweb.asm; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * A Java field or method type. This class can be used to make it easier to * manipulate type and method descriptors. * * @author Eric Bruneton * @author Chris Nokleberg */ public class Type { /** * The sort of the <tt>void</tt> type. See {@link #getSort getSort}. */ public static final int VOID = 0; /** * The sort of the <tt>boolean</tt> type. See {@link #getSort getSort}. */ public static final int BOOLEAN = 1; /** * The sort of the <tt>char</tt> type. See {@link #getSort getSort}. */ public static final int CHAR = 2; /** * The sort of the <tt>byte</tt> type. See {@link #getSort getSort}. */ public static final int BYTE = 3; /** * The sort of the <tt>short</tt> type. See {@link #getSort getSort}. */ public static final int SHORT = 4; /** * The sort of the <tt>int</tt> type. See {@link #getSort getSort}. */ public static final int INT = 5; /** * The sort of the <tt>float</tt> type. See {@link #getSort getSort}. */ public static final int FLOAT = 6; /** * The sort of the <tt>long</tt> type. See {@link #getSort getSort}. */ public static final int LONG = 7; /** * The sort of the <tt>double</tt> type. See {@link #getSort getSort}. */ public static final int DOUBLE = 8; /** * The sort of array reference types. See {@link #getSort getSort}. */ public static final int ARRAY = 9; /** * The sort of object reference types. See {@link #getSort getSort}. */ public static final int OBJECT = 10; /** * The sort of method types. See {@link #getSort getSort}. */ public static final int METHOD = 11; /** * The <tt>void</tt> type. */ public static final Type VOID_TYPE = new Type(VOID, null, ('V' << 24) | (5 << 16) | (0 << 8) | 0, 1); /** * The <tt>boolean</tt> type. */ public static final Type BOOLEAN_TYPE = new Type(BOOLEAN, null, ('Z' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The <tt>char</tt> type. */ public static final Type CHAR_TYPE = new Type(CHAR, null, ('C' << 24) | (0 << 16) | (6 << 8) | 1, 1); /** * The <tt>byte</tt> type. */ public static final Type BYTE_TYPE = new Type(BYTE, null, ('B' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The <tt>short</tt> type. */ public static final Type SHORT_TYPE = new Type(SHORT, null, ('S' << 24) | (0 << 16) | (7 << 8) | 1, 1); /** * The <tt>int</tt> type. */ public static final Type INT_TYPE = new Type(INT, null, ('I' << 24) | (0 << 16) | (0 << 8) | 1, 1); /** * The <tt>float</tt> type. */ public static final Type FLOAT_TYPE = new Type(FLOAT, null, ('F' << 24) | (2 << 16) | (2 << 8) | 1, 1); /** * The <tt>long</tt> type. */ public static final Type LONG_TYPE = new Type(LONG, null, ('J' << 24) | (1 << 16) | (1 << 8) | 2, 1); /** * The <tt>double</tt> type. */ public static final Type DOUBLE_TYPE = new Type(DOUBLE, null, ('D' << 24) | (3 << 16) | (3 << 8) | 2, 1); // ------------------------------------------------------------------------ // Fields // ------------------------------------------------------------------------ /** * The sort of this Java type. */ private final int sort; /** * A buffer containing the internal name of this Java type. This field is * only used for reference types. */ private final char[] buf; /** * The offset of the internal name of this Java type in {@link #buf buf} or, * for primitive types, the size, descriptor and getOpcode offsets for this * type (byte 0 contains the size, byte 1 the descriptor, byte 2 the offset * for IALOAD or IASTORE, byte 3 the offset for all other instructions). */ private final int off; /** * The length of the internal name of this Java type. */ private final int len; // ------------------------------------------------------------------------ // Constructors // ------------------------------------------------------------------------ /** * Constructs a reference type. * * @param sort * the sort of the reference type to be constructed. * @param buf * a buffer containing the descriptor of the previous type. * @param off * the offset of this descriptor in the previous buffer. * @param len * the length of this descriptor. */ private Type(final int sort, final char[] buf, final int off, final int len) { this.sort = sort; this.buf = buf; this.off = off; this.len = len; } /** * Returns the Java type corresponding to the given type descriptor. * * @param typeDescriptor * a field or method type descriptor. * @return the Java type corresponding to the given type descriptor. */ public static Type getType(final String typeDescriptor) { return getType(typeDescriptor.toCharArray(), 0); } /** * Returns the Java type corresponding to the given internal name. * * @param internalName * an internal name. * @return the Java type corresponding to the given internal name. */ public static Type getObjectType(final String internalName) { char[] buf = internalName.toCharArray(); return new Type(buf[0] == '[' ? ARRAY : OBJECT, buf, 0, buf.length); } /** * Returns the Java type corresponding to the given method descriptor. * Equivalent to <code>Type.getType(methodDescriptor)</code>. * * @param methodDescriptor * a method descriptor. * @return the Java type corresponding to the given method descriptor. */ public static Type getMethodType(final String methodDescriptor) { return getType(methodDescriptor.toCharArray(), 0); } /** * Returns the Java method type corresponding to the given argument and * return types. * * @param returnType * the return type of the method. * @param argumentTypes * the argument types of the method. * @return the Java type corresponding to the given argument and return * types. */ public static Type getMethodType(final Type returnType, final Type... argumentTypes) { return getType(getMethodDescriptor(returnType, argumentTypes)); } /** * Returns the Java type corresponding to the given class. * * @param c * a class. * @return the Java type corresponding to the given class. */ public static Type getType(final Class<?> c) { if (c.isPrimitive()) { if (c == Integer.TYPE) { return INT_TYPE; } else if (c == Void.TYPE) { return VOID_TYPE; } else if (c == Boolean.TYPE) { return BOOLEAN_TYPE; } else if (c == Byte.TYPE) { return BYTE_TYPE; } else if (c == Character.TYPE) { return CHAR_TYPE; } else if (c == Short.TYPE) { return SHORT_TYPE; } else if (c == Double.TYPE) { return DOUBLE_TYPE; } else if (c == Float.TYPE) { return FLOAT_TYPE; } else /* if (c == Long.TYPE) */{ return LONG_TYPE; } } else { return getType(getDescriptor(c)); } } /** * Returns the Java method type corresponding to the given constructor. * * @param c * a {@link Constructor Constructor} object. * @return the Java method type corresponding to the given constructor. */ public static Type getType(final Constructor<?> c) { return getType(getConstructorDescriptor(c)); } /** * Returns the Java method type corresponding to the given method. * * @param m * a {@link Method Method} object. * @return the Java method type corresponding to the given method. */ public static Type getType(final Method m) { return getType(getMethodDescriptor(m)); } /** * Returns the Java types corresponding to the argument types of the given * method descriptor. * * @param methodDescriptor * a method descriptor. * @return the Java types corresponding to the argument types of the given * method descriptor. */ public static Type[] getArgumentTypes(final String methodDescriptor) { char[] buf = methodDescriptor.toCharArray(); int off = 1; int size = 0; while (true) { char car = buf[off++]; if (car == ')') { break; } else if (car == 'L') { while (buf[off++] != ';') { } ++size; } else if (car != '[') { ++size; } } Type[] args = new Type[size]; off = 1; size = 0; while (buf[off] != ')') { args[size] = getType(buf, off); off += args[size].len + (args[size].sort == OBJECT ? 2 : 0); size += 1; } return args; } /** * Returns the Java types corresponding to the argument types of the given * method. * * @param method * a method. * @return the Java types corresponding to the argument types of the given * method. */ public static Type[] getArgumentTypes(final Method method) { Class<?>[] classes = method.getParameterTypes(); Type[] types = new Type[classes.length]; for (int i = classes.length - 1; i >= 0; --i) { types[i] = getType(classes[i]); } return types; } /** * Returns the Java type corresponding to the return type of the given * method descriptor. * * @param methodDescriptor * a method descriptor. * @return the Java type corresponding to the return type of the given * method descriptor. */ public static Type getReturnType(final String methodDescriptor) { char[] buf = methodDescriptor.toCharArray(); int off = 1; while (true) { char car = buf[off++]; if (car == ')') { return getType(buf, off); } else if (car == 'L') { while (buf[off++] != ';') { } } } } /** * Returns the Java type corresponding to the return type of the given * method. * * @param method * a method. * @return the Java type corresponding to the return type of the given * method. */ public static Type getReturnType(final Method method) { return getType(method.getReturnType()); } /** * Computes the size of the arguments and of the return value of a method. * * @param desc * the descriptor of a method. * @return the size of the arguments of the method (plus one for the * implicit this argument), argSize, and the size of its return * value, retSize, packed into a single int i = * <tt>(argSize &lt;&lt; 2) | retSize</tt> (argSize is therefore equal to * <tt>i &gt;&gt; 2</tt>, and retSize to <tt>i &amp; 0x03</tt>). */ public static int getArgumentsAndReturnSizes(final String desc) { int n = 1; int c = 1; while (true) { char car = desc.charAt(c++); if (car == ')') { car = desc.charAt(c); return n << 2 | (car == 'V' ? 0 : (car == 'D' || car == 'J' ? 2 : 1)); } else if (car == 'L') { while (desc.charAt(c++) != ';') { } n += 1; } else if (car == '[') { while ((car = desc.charAt(c)) == '[') { ++c; } if (car == 'D' || car == 'J') { n -= 1; } } else if (car == 'D' || car == 'J') { n += 2; } else { n += 1; } } } /** * Returns the Java type corresponding to the given type descriptor. For * method descriptors, buf is supposed to contain nothing more than the * descriptor itself. * * @param buf * a buffer containing a type descriptor. * @param off * the offset of this descriptor in the previous buffer. * @return the Java type corresponding to the given type descriptor. */ private static Type getType(final char[] buf, final int off) { int len; switch (buf[off]) { case 'V': return VOID_TYPE; case 'Z': return BOOLEAN_TYPE; case 'C': return CHAR_TYPE; case 'B': return BYTE_TYPE; case 'S': return SHORT_TYPE; case 'I': return INT_TYPE; case 'F': return FLOAT_TYPE; case 'J': return LONG_TYPE; case 'D': return DOUBLE_TYPE; case '[': len = 1; while (buf[off + len] == '[') { ++len; } if (buf[off + len] == 'L') { ++len; while (buf[off + len] != ';') { ++len; } } return new Type(ARRAY, buf, off, len + 1); case 'L': len = 1; while (buf[off + len] != ';') { ++len; } return new Type(OBJECT, buf, off + 1, len - 1); // case '(': default: return new Type(METHOD, buf, off, buf.length - off); } } // ------------------------------------------------------------------------ // Accessors // ------------------------------------------------------------------------ /** * Returns the sort of this Java type. * * @return {@link #VOID VOID}, {@link #BOOLEAN BOOLEAN}, {@link #CHAR CHAR}, * {@link #BYTE BYTE}, {@link #SHORT SHORT}, {@link #INT INT}, * {@link #FLOAT FLOAT}, {@link #LONG LONG}, {@link #DOUBLE DOUBLE}, * {@link #ARRAY ARRAY}, {@link #OBJECT OBJECT} or {@link #METHOD * METHOD}. */ public int getSort() { return sort; } /** * Returns the number of dimensions of this array type. This method should * only be used for an array type. * * @return the number of dimensions of this array type. */ public int getDimensions() { int i = 1; while (buf[off + i] == '[') { ++i; } return i; } /** * Returns the type of the elements of this array type. This method should * only be used for an array type. * * @return Returns the type of the elements of this array type. */ public Type getElementType() { return getType(buf, off + getDimensions()); } /** * Returns the binary name of the class corresponding to this type. This * method must not be used on method types. * * @return the binary name of the class corresponding to this type. */ public String getClassName() { switch (sort) { case VOID: return "void"; case BOOLEAN: return "boolean"; case CHAR: return "char"; case BYTE: return "byte"; case SHORT: return "short"; case INT: return "int"; case FLOAT: return "float"; case LONG: return "long"; case DOUBLE: return "double"; case ARRAY: StringBuilder sb = new StringBuilder(getElementType().getClassName()); for (int i = getDimensions(); i > 0; --i) { sb.append("[]"); } return sb.toString(); case OBJECT: return new String(buf, off, len).replace('/', '.'); default: return null; } } /** * Returns the internal name of the class corresponding to this object or * array type. The internal name of a class is its fully qualified name (as * returned by Class.getName(), where '.' are replaced by '/'. This method * should only be used for an object or array type. * * @return the internal name of the class corresponding to this object type. */ public String getInternalName() { return new String(buf, off, len); } /** * Returns the argument types of methods of this type. This method should * only be used for method types. * * @return the argument types of methods of this type. */ public Type[] getArgumentTypes() { return getArgumentTypes(getDescriptor()); } /** * Returns the return type of methods of this type. This method should only * be used for method types. * * @return the return type of methods of this type. */ public Type getReturnType() { return getReturnType(getDescriptor()); } /** * Returns the size of the arguments and of the return value of methods of * this type. This method should only be used for method types. * * @return the size of the arguments (plus one for the implicit this * argument), argSize, and the size of the return value, retSize, * packed into a single * int i = <tt>(argSize &lt;&lt; 2) | retSize</tt> * (argSize is therefore equal to <tt>i &gt;&gt; 2</tt>, * and retSize to <tt>i &amp; 0x03</tt>). */ public int getArgumentsAndReturnSizes() { return getArgumentsAndReturnSizes(getDescriptor()); } // ------------------------------------------------------------------------ // Conversion to type descriptors // ------------------------------------------------------------------------ /** * Returns the descriptor corresponding to this Java type. * * @return the descriptor corresponding to this Java type. */ public String getDescriptor() { StringBuilder buf = new StringBuilder(); getDescriptor(buf); return buf.toString(); } /** * Returns the descriptor corresponding to the given argument and return * types. * * @param returnType * the return type of the method. * @param argumentTypes * the argument types of the method. * @return the descriptor corresponding to the given argument and return * types. */ public static String getMethodDescriptor(final Type returnType, final Type... argumentTypes) { StringBuilder buf = new StringBuilder(); buf.append('('); for (int i = 0; i < argumentTypes.length; ++i) { argumentTypes[i].getDescriptor(buf); } buf.append(')'); returnType.getDescriptor(buf); return buf.toString(); } /** * Appends the descriptor corresponding to this Java type to the given * string buffer. * * @param buf * the string buffer to which the descriptor must be appended. */ private void getDescriptor(final StringBuilder buf) { if (this.buf == null) { // descriptor is in byte 3 of 'off' for primitive types (buf == // null) buf.append((char) ((off & 0xFF000000) >>> 24)); } else if (sort == OBJECT) { buf.append('L'); buf.append(this.buf, off, len); buf.append(';'); } else { // sort == ARRAY || sort == METHOD buf.append(this.buf, off, len); } } // ------------------------------------------------------------------------ // Direct conversion from classes to type descriptors, // without intermediate Type objects // ------------------------------------------------------------------------ /** * Returns the internal name of the given class. The internal name of a * class is its fully qualified name, as returned by Class.getName(), where * '.' are replaced by '/'. * * @param c * an object or array class. * @return the internal name of the given class. */ public static String getInternalName(final Class<?> c) { return c.getName().replace('.', '/'); } /** * Returns the descriptor corresponding to the given Java type. * * @param c * an object class, a primitive class or an array class. * @return the descriptor corresponding to the given class. */ public static String getDescriptor(final Class<?> c) { StringBuilder buf = new StringBuilder(); getDescriptor(buf, c); return buf.toString(); } /** * Returns the descriptor corresponding to the given constructor. * * @param c * a {@link Constructor Constructor} object. * @return the descriptor of the given constructor. */ public static String getConstructorDescriptor(final Constructor<?> c) { Class<?>[] parameters = c.getParameterTypes(); StringBuilder buf = new StringBuilder(); buf.append('('); for (int i = 0; i < parameters.length; ++i) { getDescriptor(buf, parameters[i]); } return buf.append(")V").toString(); } /** * Returns the descriptor corresponding to the given method. * * @param m * a {@link Method Method} object. * @return the descriptor of the given method. */ public static String getMethodDescriptor(final Method m) { Class<?>[] parameters = m.getParameterTypes(); StringBuilder buf = new StringBuilder(); buf.append('('); for (int i = 0; i < parameters.length; ++i) { getDescriptor(buf, parameters[i]); } buf.append(')'); getDescriptor(buf, m.getReturnType()); return buf.toString(); } /** * Appends the descriptor of the given class to the given string buffer. * * @param buf * the string buffer to which the descriptor must be appended. * @param c * the class whose descriptor must be computed. */ private static void getDescriptor(final StringBuilder buf, final Class<?> c) { Class<?> d = c; while (true) { if (d.isPrimitive()) { char car; if (d == Integer.TYPE) { car = 'I'; } else if (d == Void.TYPE) { car = 'V'; } else if (d == Boolean.TYPE) { car = 'Z'; } else if (d == Byte.TYPE) { car = 'B'; } else if (d == Character.TYPE) { car = 'C'; } else if (d == Short.TYPE) { car = 'S'; } else if (d == Double.TYPE) { car = 'D'; } else if (d == Float.TYPE) { car = 'F'; } else /* if (d == Long.TYPE) */{ car = 'J'; } buf.append(car); return; } else if (d.isArray()) { buf.append('['); d = d.getComponentType(); } else { buf.append('L'); String name = d.getName(); int len = name.length(); for (int i = 0; i < len; ++i) { char car = name.charAt(i); buf.append(car == '.' ? '/' : car); } buf.append(';'); return; } } } // ------------------------------------------------------------------------ // Corresponding size and opcodes // ------------------------------------------------------------------------ /** * Returns the size of values of this type. This method must not be used for * method types. * * @return the size of values of this type, i.e., 2 for <tt>long</tt> and * <tt>double</tt>, 0 for <tt>void</tt> and 1 otherwise. */ public int getSize() { // the size is in byte 0 of 'off' for primitive types (buf == null) return buf == null ? (off & 0xFF) : 1; } /** * Returns a JVM instruction opcode adapted to this Java type. This method * must not be used for method types. * * @param opcode * a JVM instruction opcode. This opcode must be one of ILOAD, * ISTORE, IALOAD, IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, * ISHL, ISHR, IUSHR, IAND, IOR, IXOR and IRETURN. * @return an opcode that is similar to the given opcode, but adapted to * this Java type. For example, if this type is <tt>float</tt> and * <tt>opcode</tt> is IRETURN, this method returns FRETURN. */ public int getOpcode(final int opcode) { if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) { // the offset for IALOAD or IASTORE is in byte 1 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF00) >> 8 : 4); } else { // the offset for other instructions is in byte 2 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF0000) >> 16 : 4); } } // ------------------------------------------------------------------------ // Equals, hashCode and toString // ------------------------------------------------------------------------ /** * Tests if the given object is equal to this type. * * @param o * the object to be compared to this type. * @return <tt>true</tt> if the given object is equal to this type. */ @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Type)) { return false; } Type t = (Type) o; if (sort != t.sort) { return false; } if (sort >= ARRAY) { if (len != t.len) { return false; } for (int i = off, j = t.off, end = i + len; i < end; i++, j++) { if (buf[i] != t.buf[j]) { return false; } } } return true; } /** * Returns a hash code value for this type. * * @return a hash code value for this type. */ @Override public int hashCode() { int hc = 13 * sort; if (sort >= ARRAY) { for (int i = off, end = i + len; i < end; i++) { hc = 17 * (hc + buf[i]); } } return hc; } /** * Returns a string representation of this type. * * @return the descriptor of this type. */ @Override public String toString() { return getDescriptor(); } }
ChristianPSchenk/JRTrace
de.schenk.jrtrace.helperlib/src/de/schenk/objectweb/asm/Type.java
Java
apache-2.0
29,589
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.identitymanagement.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachGroupPolicy" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AttachGroupPolicyResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof AttachGroupPolicyResult == false) return false; AttachGroupPolicyResult other = (AttachGroupPolicyResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public AttachGroupPolicyResult clone() { try { return (AttachGroupPolicyResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
dagnir/aws-sdk-java
aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/AttachGroupPolicyResult.java
Java
apache-2.0
2,266
/** * */ package com.zhigu.common.alibaba; /** * @author lkl * */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.httpclient.methods.PostMethod; /** * 通用工具类,包括了签名工具、url拼装以及httpResponse的解析 */ public final class CommonUtil { /** * 解析http请求的response * @param method * @return 请求结果 * @throws IOException */ public static String parserResponse(PostMethod method) throws IOException{ StringBuffer contentBuffer = new StringBuffer(); InputStream in = method.getResponseBodyAsStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, method.getResponseCharSet())); String inputLine = null; while((inputLine = reader.readLine()) != null) { contentBuffer.append(inputLine); contentBuffer.append("/n"); } //去掉结尾的换行符 contentBuffer.delete(contentBuffer.length() - 2, contentBuffer.length()); in.close(); return contentBuffer.toString(); } /** * 将urlPath和请求参数同时作为签名因子进行签名 * @param urlPath protocol/version/namespace/name/appKey * @param params api请求的各参数键值对 * @param appSecretKey app签名密钥 * @return */ public static String signatureWithParamsAndUrlPath(String urlPath, Map<String, String> params, String appSecretKey){ List<String> paramValueList = new ArrayList<String>(); if(params != null){ for (Map.Entry<String, String> entry : params.entrySet()) { paramValueList.add(entry.getKey() + entry.getValue()); } } final String[] datas = new String[1 + paramValueList.size()]; datas[0] = urlPath; Collections.sort(paramValueList); for (int i = 0; i < paramValueList.size(); i++) { datas[i+1] = paramValueList.get(i); } byte[] signature = SecurityUtil.hmacSha1(datas, StringUtil.toBytes(appSecretKey)); return StringUtil.encodeHexStr(signature); } /** * * 仅将请求参数作为签名因子进行签名 * @param params api请求的各参数键值对 * @param appSecretKey * @return */ public static String signatureWithParamsOnly(Map<String, String> params, String appSecretKey){ List<String> paramValueList = new ArrayList<String>(); if(params != null){ for (Map.Entry<String, String> entry : params.entrySet()) { paramValueList.add(entry.getKey() + entry.getValue()); } } Collections.sort(paramValueList); String[] datas = new String[paramValueList.size()]; paramValueList.toArray(datas); byte[] signature = SecurityUtil.hmacSha1(datas, StringUtil.toBytes(appSecretKey)); return StringUtil.encodeHexStr(signature); } /** * 生成api签名的urlPath,即protocol/version/namespace/name/appKey * @param apiNamespace * @param apiName * @param apiVersion * @param protocol * @param appKey * @return */ public static String buildInvokeUrlPath(String apiNamespace, String apiName, int apiVersion, String protocol, String appKey) { String url = protocol + "/" + apiVersion + "/" + apiNamespace + "/" + apiName + "/" + appKey; return url; } /** * 获取完整的url * @param url 请求uri * @param params 请求参数 * @return */ public static String getWholeUrl(String url, Map<String, String> params){ if(url == null){ return null; } if(params == null){ return url; } Set<Map.Entry<String, String>> set = params.entrySet(); if(set.size() <= 0){ return url; } url += "?"; Iterator<Map.Entry<String, String>> it = set.iterator(); if(it.hasNext()){ Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next(); String param = entry.getKey() + "=" + entry.getValue(); url += param; } while(it.hasNext()){ Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next(); String param = entry.getKey() + "=" + entry.getValue(); url += "&" + param; } return url; } private CommonUtil(){ } }
lklong/fuckproject
src/com/zhigu/common/alibaba/CommonUtil.java
Java
apache-2.0
4,734
package spet.sbwo.server; import org.eclipse.jetty.server.session.AbstractSessionDataStore; import org.eclipse.jetty.server.session.SessionData; import spet.sbwo.control.controller.user.ISessionManager; import spet.sbwo.data.table.UserSession; import java.io.*; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.function.Supplier; /** * Adapter class between the session manager and the Jetty specific session data * store. * * @author Serban Petrescu */ public class SessionDataStore extends AbstractSessionDataStore { private final ISessionManager manager; public SessionDataStore(ISessionManager manager) { this.manager = manager; } @Override public boolean isPassivating() { return true; } @Override public boolean exists(String id) { return runInContext(() -> manager.exists(id)); } @Override public SessionData load(String id) { return runInContext(() -> { UserSession session = manager.read(id); if (session != null) { try { SessionData result = new SessionData(session.getId(), session.getContextPath(), session.getVirtualHost(), session.getCreateTime(), session.getAccessTime(), session.getLastAccessTime(), session.getMaxInterval(), deserialize(session.getAttributes())); result.setExpiry(session.getExpiryTime()); result.setLastSaved(session.getLastSaveTime()); result.setCookieSet(session.getCookieTime()); result.setLastNode(session.getLastNode()); return result; } catch (Exception e) { throw new IllegalStateException(e); } } else { throw new IllegalArgumentException(); } }); } @Override public boolean delete(String id) { return runInContext(() -> manager.remove(id)); } @Override public void doStore(String id, SessionData data, long lastSaveTime) throws IOException { UserSession session = new UserSession(); session.setAccessTime(data.getAccessed()); session.setAttributes(serialize(new HashMap<>(data.getAllAttributes()))); session.setContextPath(data.getContextPath()); session.setCookieTime(data.getCookieSet()); session.setCreateTime(data.getCreated()); session.setExpiryTime(data.getExpiry()); session.setId(id); session.setLastAccessTime(data.getLastAccessed()); session.setLastSaveTime(lastSaveTime); session.setLastNode(data.getLastNode()); session.setMaxInterval(data.getMaxInactiveMs()); session.setVirtualHost(data.getVhost()); manager.upsert(session); } @Override public Set<String> doGetExpired(Set<String> candidates) { return new HashSet<>(manager.readAllExpired(new Date().getTime())); } /** * Runs a given task in the context. */ protected <T> T runInContext(Supplier<T> executor) { Deferred<T> deferred = new Deferred<>(executor); this._context.run(deferred); return deferred.getResult(); } /** * Serializes the session attributes. */ protected byte[] serialize(HashMap<String, Object> data) throws IOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream(1024); ObjectOutputStream obj = new ObjectOutputStream(out)) { obj.writeObject(data); obj.flush(); return out.toByteArray(); } } /** * Deserializes the session attributes. */ @SuppressWarnings("unchecked") protected HashMap<String, Object> deserialize(byte[] data) throws ClassNotFoundException, IOException { try (ByteArrayInputStream in = new ByteArrayInputStream(data); ObjectInputStream obj = new ObjectInputStream(in)) { return (HashMap<String, Object>) obj.readObject(); } } /** * Utility class for executing a task and keeping a deferred reference to * the result. */ private class Deferred<T> implements Runnable { private final Supplier<T> supplier; private T result; public Deferred(Supplier<T> supplier) { this.supplier = supplier; } @Override public void run() { result = supplier.get(); } public T getResult() { return result; } } }
serban-petrescu/sbwo
src/main/java/spet/sbwo/server/SessionDataStore.java
Java
apache-2.0
4,653
/** * Copyright (C) 2014 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dashbuilder.displayer.impl; import org.dashbuilder.displayer.BarChartSettingsBuilder; import org.dashbuilder.displayer.DisplayerSettings; import org.dashbuilder.displayer.DisplayerType; public class BarChartSettingsBuilderImpl extends AbstractXAxisChartSettingsBuilder<BarChartSettingsBuilderImpl> implements BarChartSettingsBuilder<BarChartSettingsBuilderImpl> { protected DisplayerSettings createDisplayerSettings() { return new DisplayerSettings( DisplayerType.BARCHART ); } public BarChartSettingsBuilderImpl set3d( boolean b ) { displayerSettings.setChart3D( b ); return this; } public BarChartSettingsBuilderImpl horizontal() { displayerSettings.setBarchartHorizontal( true ); return this; } public BarChartSettingsBuilderImpl vertical() { displayerSettings.setBarchartHorizontal( false ); return this; } }
ryanzhang/dashbuilder
dashbuilder-shared/dashbuilder-displayer-api/src/main/java/org/dashbuilder/displayer/impl/BarChartSettingsBuilderImpl.java
Java
apache-2.0
1,519
/* * Copyright (c) 2014, NewTouch * All rights reserved. * * $id: ResourceVo.java 9552 2014-4-4 下午08:14:36 WangLijun$ */ package com.newtouch.lion.admin.web.model.system.resource; import com.newtouch.lion.model.system.Attributes; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.Digits; /** * <p> * Title: 资源管理类 * </p> * <p> * Description: 资源管理类-Vo * </p> * <p> * Copyright: Copyright (c) 2014 * </p> * <p> * Company: NewTouch * </p> * * @author WangLijun * @version 1.0 */ public class ResourceVo { /*** * 资源ID */ private Long id; /** 资源父ID */ private Long parentResourceId; /** 资源类型 */ @NotEmpty(message="{sys.resource.type.missing}") private String type; /** 资源路径 URL Class.Method */ private String path; /** 资源名称-中文 */ @NotEmpty(message="{sys.resource.namezh.missing}") @Length(max=128,min=1,message="{sys.resource.namezh.length}") private String nameZh; /** 资源名称-英文 */ @NotEmpty(message="{sys.resource.namezh.missing}") @Length(max=128,min=1,message="{sys.resource.namezh.length}") private String nameEn; /** 资源描述 */ private String description; /** 资源排序 */ //@NotNull(message="{sys.resource.seqnum.missing}") @Digits(fraction=0,integer=10,message="{sys.resource.seqnum.digits}") private Integer seqNum; /** 资源是否叶节点,其下没有子资源 默认为:true */ private Boolean isLeaf = Boolean.FALSE; /** 资源是否可编辑 */ private Boolean editable = Boolean.FALSE; /** 资源目标 指HTML链接的target属性 */ private String target; /** 资源性 */ private Attributes attributes; /**权限名称*/ private String permission; /**ICON图标*/ private String icon; public ResourceVo() { super(); } /** * @return the id */ public Long getId() { return id; } /** * @param id * the id to set */ public void setId(Long id) { this.id = id; } /** * @return the parentResourceId */ public Long getParentResourceId() { return parentResourceId; } /** * @param parentResourceId * the parentResourceId to set */ public void setParentResourceId(Long parentResourceId) { this.parentResourceId = parentResourceId; } /** * @return the type */ public String getType() { return type; } /** * @param type * the type to set */ public void setType(String type) { this.type = type; } /** * @return the path */ public String getPath() { return path; } /** * @param path * the path to set */ public void setPath(String path) { this.path = path; } /** * @return the nameZh */ public String getNameZh() { return nameZh; } /** * @param nameZh * the nameZh to set */ public void setNameZh(String nameZh) { this.nameZh = nameZh; } /** * @return the nameEn */ public String getNameEn() { return nameEn; } /** * @param nameEn * the nameEn to set */ public void setNameEn(String nameEn) { this.nameEn = nameEn; } /** * @return the description */ public String getDescription() { return description; } /** * @param description * the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the seqNum */ public Integer getSeqNum() { return seqNum; } /** * @param seqNum * the seqNum to set */ public void setSeqNum(Integer seqNum) { this.seqNum = seqNum; } /** * @return the isLeaf */ public Boolean getIsLeaf() { return isLeaf; } /** * @param isLeaf * the isLeaf to set */ public void setIsLeaf(Boolean isLeaf) { this.isLeaf = isLeaf; } /** * @return the editable */ public Boolean getEditable() { return editable; } /** * @param editable * the editable to set */ public void setEditable(Boolean editable) { this.editable = editable; } /** * @return the target */ public String getTarget() { return target; } /** * @param target * the target to set */ public void setTarget(String target) { this.target = target; } /** * @return the attributes */ public Attributes getAttributes() { return attributes; } /** * @param attributes * the attributes to set */ public void setAttributes(Attributes attributes) { this.attributes = attributes; } /** * @return the permission */ public String getPermission() { return permission; } /** * @param permission the permission to set */ public void setPermission(String permission) { this.permission = permission; } /** * @return ICON图标 */ public String getIcon() { return icon; } /** * @param icon ICON图标 */ public void setIcon(String icon) { this.icon = icon; } }
scwanglijun/lion-admin
lion-admin-web/src/main/java/com/newtouch/lion/admin/web/model/system/resource/ResourceVo.java
Java
apache-2.0
4,966
package ikube.action.index.parse; import static org.junit.Assert.assertTrue; import ikube.AbstractTest; import ikube.IConstants; import ikube.toolkit.FILE; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.OutputStream; import org.junit.Test; /** * @author Michael Couck * @since 10.02.10 * @version 01.00 */ public class HtmlParserTest extends AbstractTest { @Test public void parse() throws Exception { File file = FILE.findFileRecursively(new File("."), "html.html"); byte[] bytes = FILE.getContents(file, IConstants.ENCODING).getBytes(); // URL url = new URL("http://www.oki.com"); HtmlParser parser = new HtmlParser(); // byte[] bytes = FileUtilities.getContents(url.openStream(), Integer.MAX_VALUE).toByteArray(); OutputStream parsed = parser.parse(new ByteArrayInputStream(bytes), new ByteArrayOutputStream()); assertTrue(parsed.toString().indexOf("nodethirtythree") > -1); } }
michaelcouck/ikube
code/core/src/test/java/ikube/action/index/parse/HtmlParserTest.java
Java
apache-2.0
1,006
/* * Copyright 2001-2008 Artima, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.scalatest.finders; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MethodDefinition implements AstNode { private final String className; private final AstNode parent; private final List<AstNode> children; private final String name; private final String[] paramTypes; public MethodDefinition(String className, AstNode parent, AstNode[] children, String name, String... paramTypes) { this.className = className; this.parent = parent; if (parent != null) parent.addChild(this); this.children = new ArrayList<>(); this.children.addAll(Arrays.asList(children)); this.name = name; this.paramTypes = paramTypes; } public String className() { return className; } public AstNode parent() { return parent; } public AstNode[] children() { return children.toArray(new AstNode[0]); } public String name() { return name; } public void addChild(AstNode node) { if (!children.contains(node)) children.add(node); } @Override public boolean canBePartOfTestName() { return true; } public String[] paramTypes() { return paramTypes; } }
JetBrains/intellij-scala
scala/test-integration/scalatest-finders/src/main/java/org/scalatest/finders/MethodDefinition.java
Java
apache-2.0
1,810
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tcl.simpletv.launcher2; import java.util.ArrayList; import android.content.ContentValues; /** * Represents a folder containing shortcuts or apps. */ class FolderInfo extends ItemInfo { /** * Whether this folder has been opened */ boolean opened; /** * The apps and shortcuts */ ArrayList<ShortcutInfo> contents = new ArrayList<ShortcutInfo>(); ArrayList<FolderListener> listeners = new ArrayList<FolderListener>(); FolderInfo() { itemType = LauncherSettings.Favorites.ITEM_TYPE_FOLDER; } /** * Add an app or shortcut * * @param item */ public void add(ShortcutInfo item) { contents.add(item); for (int i = 0; i < listeners.size(); i++) { listeners.get(i).onAdd(item); } itemsChanged(); } /** * Remove an app or shortcut. Does not change the DB. * * @param item */ public void remove(ShortcutInfo item) { contents.remove(item); for (int i = 0; i < listeners.size(); i++) { listeners.get(i).onRemove(item); } itemsChanged(); } public void setTitle(CharSequence title) { this.title = title; for (int i = 0; i < listeners.size(); i++) { listeners.get(i).onTitleChanged(title); } } @Override void onAddToDatabase(ContentValues values) { super.onAddToDatabase(values); values.put(LauncherSettings.Favorites.TITLE, title.toString()); } void addListener(FolderListener listener) { listeners.add(listener); } void removeListener(FolderListener listener) { if (listeners.contains(listener)) { listeners.remove(listener); } } void itemsChanged() { for (int i = 0; i < listeners.size(); i++) { listeners.get(i).onItemsChanged(); } } @Override void unbind() { super.unbind(); listeners.clear(); } interface FolderListener { public void onAdd(ShortcutInfo item); public void onRemove(ShortcutInfo item); public void onTitleChanged(CharSequence title); public void onItemsChanged(); } }
SmileMx/Screen_Launcher
Launcher/src/com/tcl/simpletv/launcher2/FolderInfo.java
Java
apache-2.0
2,859
package org.javaan.model; /* * #%L * Java Static Code Analysis * %% * Copyright (C) 2013 Andreas Behnke * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * An object which is sortable and equals by it's name */ public interface NamedObject extends Comparable<NamedObject> { String getName(); }
andreasbehnke/javaan
javaan-lib/src/main/java/org/javaan/model/NamedObject.java
Java
apache-2.0
833
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.tooling.internal.provider; import org.gradle.StartParameter; import org.gradle.initialization.BuildRequestContext; import org.gradle.initialization.SessionLifecycleListener; import org.gradle.internal.concurrent.CompositeStoppable; import org.gradle.internal.concurrent.Stoppable; import org.gradle.internal.event.ListenerManager; import org.gradle.internal.invocation.BuildAction; import org.gradle.internal.service.ServiceRegistry; import org.gradle.internal.service.scopes.BuildSessionScopeServices; import org.gradle.internal.service.scopes.CrossBuildSessionScopeServices; import org.gradle.internal.service.scopes.GradleUserHomeScopeServiceRegistry; import org.gradle.launcher.exec.BuildActionExecuter; import org.gradle.launcher.exec.BuildActionParameters; import org.gradle.launcher.exec.BuildExecuter; public class ServicesSetupBuildActionExecuter implements BuildExecuter { private final BuildActionExecuter<BuildActionParameters> delegate; private final GradleUserHomeScopeServiceRegistry userHomeServiceRegistry; public ServicesSetupBuildActionExecuter(BuildActionExecuter<BuildActionParameters> delegate, GradleUserHomeScopeServiceRegistry userHomeServiceRegistry) { this.delegate = delegate; this.userHomeServiceRegistry = userHomeServiceRegistry; } @Override public Object execute(BuildAction action, BuildRequestContext requestContext, BuildActionParameters actionParameters, ServiceRegistry contextServices) { StartParameter startParameter = action.getStartParameter(); final ServiceRegistry userHomeServices = userHomeServiceRegistry.getServicesFor(startParameter.getGradleUserHomeDir()); CrossBuildSessionScopeServices crossBuildSessionScopeServices = new CrossBuildSessionScopeServices(contextServices, startParameter); try { ServiceRegistry buildSessionScopeServices = new BuildSessionScopeServices( userHomeServices, crossBuildSessionScopeServices, startParameter, requestContext, actionParameters.getInjectedPluginClasspath(), requestContext.getCancellationToken() ); try { SessionLifecycleListener sessionLifecycleListener = buildSessionScopeServices.get(ListenerManager.class).getBroadcaster(SessionLifecycleListener.class); try { sessionLifecycleListener.afterStart(); return delegate.execute(action, requestContext, actionParameters, buildSessionScopeServices); } finally { sessionLifecycleListener.beforeComplete(); } } finally { CompositeStoppable.stoppable(buildSessionScopeServices).stop(); } } finally { new CompositeStoppable().add(new Stoppable() { @Override public void stop() { userHomeServiceRegistry.release(userHomeServices); } }, crossBuildSessionScopeServices).stop(); } } }
lsmaira/gradle
subprojects/launcher/src/main/java/org/gradle/tooling/internal/provider/ServicesSetupBuildActionExecuter.java
Java
apache-2.0
3,736
/* * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.bpel.core.ode.integration.store; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ode.bpel.compiler.api.CompilationException; import org.apache.ode.bpel.dd.DeployDocument; import org.apache.ode.bpel.dd.TBAMServerProfiles; import org.apache.ode.bpel.dd.TDeployment; import org.apache.ode.bpel.dd.TProvide; import org.apache.ode.bpel.engine.BpelServerImpl; import org.apache.ode.bpel.iapi.ContextException; import org.apache.ode.bpel.iapi.ProcessConf; import org.apache.ode.bpel.iapi.ProcessState; import org.apache.ode.store.DeploymentUnitDAO; import org.apache.ode.store.DeploymentUnitDir; import org.apache.ode.store.ProcessConfDAO; import org.wso2.carbon.application.deployer.AppDeployerUtils; import org.wso2.carbon.bpel.common.config.EndpointConfiguration; import org.wso2.carbon.bpel.core.BPELConstants; import org.wso2.carbon.bpel.core.internal.BPELServiceComponent; import org.wso2.carbon.bpel.core.ode.integration.BPELServerImpl; import org.wso2.carbon.bpel.core.ode.integration.config.bam.BAMServerProfile; import org.wso2.carbon.bpel.core.ode.integration.config.bam.BAMServerProfileBuilder; import org.wso2.carbon.bpel.core.ode.integration.store.clustering.BPELProcessStateChangedCommand; import org.wso2.carbon.bpel.core.ode.integration.store.repository.BPELPackageInfo; import org.wso2.carbon.bpel.core.ode.integration.store.repository.BPELPackageRepository; import org.wso2.carbon.bpel.core.ode.integration.store.repository.BPELPackageRepositoryUtils; import org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.ProcessManagementException; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.RegistryConstants; import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.utils.RegistryClientUtils; import org.wso2.carbon.unifiedendpoint.core.UnifiedEndpointConstants; import org.wso2.carbon.utils.FileManipulator; import javax.xml.namespace.QName; import java.io.File; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Tenant specific process store. * Contains all the information about tenant's BPEL packages and processes. */ public class TenantProcessStoreImpl implements TenantProcessStore { private static final Log log = LogFactory.getLog(TenantProcessStoreImpl.class); private static final Log deploymentLog = LogFactory.getLog(BPELConstants.LOGGER_DEPLOYMENT); // ID of the tenant who owns this process store private Integer tenantId; // Tenant's Configuration context private ConfigurationContext tenantConfigContext; // Tenant's configuration registry private Registry tenantConfigRegistry; // Parent process store private ProcessStoreImpl parentProcessStore; // BPEL Deployment units available for this tenant private final Map<String, DeploymentUnitDir> deploymentUnits = new ConcurrentHashMap<String, DeploymentUnitDir>(); // BPEL Processes in this tenant private final Map<QName, ProcessConfigurationImpl> processConfigMap = new ConcurrentHashMap<QName, ProcessConfigurationImpl>(); private final Map<String, List<QName>> processesInDeploymentUnit = new ConcurrentHashMap<String, List<QName>>(); private BPELPackageRepository repository; // Tenant's BPEL deployment unit repository private File bpelDURepo; // Axis2 bpel deployment repository where we put BPEL archive artifacts private File bpelArchiveRepo; // Holds the BAM server profiles private final Map<String, BAMServerProfile> bamProfiles = new ConcurrentHashMap<String, BAMServerProfile>(); private final Map<String, Object> dataPublisherMap = new ConcurrentHashMap<String, Object>(); public TenantProcessStoreImpl(ConfigurationContext configContext, ProcessStoreImpl parent) throws RegistryException { tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); tenantConfigContext = configContext; tenantConfigRegistry = BPELServiceComponent.getRegistryService().getConfigSystemRegistry(tenantId); parentProcessStore = parent; } public void init() throws Exception { bpelDURepo = new File(parentProcessStore.getLocalDeploymentUnitRepo(), tenantId.toString()); if (!bpelDURepo.exists() && !bpelDURepo.mkdirs()) { log.warn("Cannot create tenant " + tenantId + " BPEL deployment unit repository."); } repository = new BPELPackageRepository(tenantConfigRegistry, bpelDURepo, bpelArchiveRepo); repository.init(); } public void handleNewBPELPackageDeploymentNotification(String bpelPackageName) { // Copy archive to file system // Write the deployment logic to handle that. try { repository.restoreBPELArchive(repository.getBPELPackageInfo( BPELConstants.REG_PATH_OF_BPEL_PACKAGES + bpelPackageName)); } catch (Exception e) { log.error("Error occurred while deploying: " + bpelPackageName, e); } } public void handleBPELPackageUndeploymentNotification(String bpelPackageName, List<String> versionsOfPackage) { updateLocalInstanceWithUndeployment(bpelPackageName, versionsOfPackage); } public void handleBPELProcessStateChangedNotification(QName pid, ProcessState processState) { if (log.isDebugEnabled()) { log.debug("Changing state of the process " + pid + " to " + processState); } if (!isProcessExist(pid)) { String errMsg = "Process " + pid + " not found. Process state change failed."; log.error(errMsg); return; } if (processState == null) { String errMessage = "Process State cannot be null. Process state change failed"; log.error(errMessage); return; } parentProcessStore.updateLocalInstanceWithStateChange(pid, processState); } /** * Deploy processes in given BPEL archive in ODE. * <p/> * Deployment flow: * - Get the current version from ODE(This version number is global to ODE.) * - Create the deployment context(@see BPELDeploymentContext) * - Check for existing BPEL archives with the same name(use when updating BPEL packages) * - If this is a new deployment or update, extract the archive and deploy processes * - If this is a reload(at startup) handle the reload. * <p/> * Process Versioning: * Process version is a single, sequentially incremented number. All deployed packages share * the same sequence. All processes in a bundle share the same version number and it's * the number of their bundle. * * @param bpelArchive BPEL package directory * @throws RegistryException */ public void deploy(File bpelArchive) throws Exception { log.info("Deploying BPEL archive: " + bpelArchive.getName()); long versionForThisDeployment = parentProcessStore.getCurrentVersion(); BPELDeploymentContext deploymentContext = new BPELDeploymentContext( tenantId, parentProcessStore.getLocalDeploymentUnitRepo().getAbsolutePath(), bpelArchive, versionForThisDeployment); boolean isExistingPackage = repository.isExistingBPELPackage(deploymentContext); boolean isLoadOnly = repository.isBPELPackageReload(deploymentContext); deploymentContext.setExistingPackage(isExistingPackage); if (deploymentLog.isDebugEnabled()) { if (isExistingPackage) { deploymentLog.debug("Package: " + deploymentContext.getBpelPackageName() + " is already available"); } else { deploymentLog.debug("Package: " + deploymentContext.getBpelPackageName() + " is a new deployment"); } if (isLoadOnly) { deploymentLog.debug("Package: " + deploymentContext.getBpelPackageName() + " has already deployed. Therefore the package is reloaded"); } else { deploymentLog.debug("Package: " + deploymentContext.getBpelPackageName() + " is found as a new deployment"); } } if (isExistingPackage && isLoadOnly) { reloadExistingVersionsOfBPELPackage(deploymentContext); // attach this bpel archive with cApp /* attachWithCapp(deploymentContext.getArchiveName(), deploymentContext.getBpelPackageName(), tenantId);*/ return; // Once we finish reloading exit from the normal flow. // Else this is a update of existing BPEL package } if (isConfigRegistryReadOnly()) { log.warn("This node seems to be a slave, since the configuration registry is in read-only mode, " + "hence processes cannot be directly deployed in this node. Please deploy the process in Master node first."); return; } try { Utils.extractBPELArchive(deploymentContext); } catch (Exception exception) { String errMsg = "Error extracting BPEL archive " + deploymentContext.getBpelArchive() + "."; deploymentContext.setDeploymentFailureCause(errMsg); deploymentContext.setStackTrace(exception); deploymentContext.setFailed(true); handleDeploymentError(deploymentContext); throw exception; } if (!validateBPELPackage(deploymentContext, isExistingPackage)) { deploymentContext.setFailed(true); handleDeploymentError(deploymentContext); return; // Exist from the normal flow on BPEL package validation error. } deployBPELPackageInODE(deploymentContext); if (isExistingPackage) { repository.handleBPELPackageUpdate(deploymentContext); } else { repository.handleNewBPELPackageAddition(deploymentContext); } // attach this bpel archive with cApp /* attachWithCapp(deploymentContext.getArchiveName(), deploymentContext.getBpelPackageName(), tenantId);*/ // We should use the deployment synchronizer instead of the below code // parentProcessStore.sendProcessDeploymentNotificationsToCluster( // new NewBPELPackageDeployedCommand(deploymentContext.getBpelPackageName(), tenantId), // configurationContext); } private boolean isConfigRegistryReadOnly() { RegistryContext context = tenantConfigRegistry.getRegistryContext(); try { if (context != null) { return context.isReadOnly(); } } catch (Exception e) { log.error("An error occurred while obtaining registry instance", e); } return false; } /** * Undeploying BPEL package. * * @param bpelPackageName Name of the BPEL package which going to be undeployed */ public void undeploy(String bpelPackageName) throws RegistryException { if (log.isDebugEnabled()) { log.debug("Un-deploying BPEL package " + bpelPackageName + " ...."); } if (!repository.isExistingBPELPackage(bpelPackageName)) { // This can be a situation where we un-deploy the archive through management console, // so that, the archive is deleted from the repo. As a result this method get invoked. // to handle this case we just log the message but does not throw an exception. final String warningMsg = "Cannot find BPEL package with name " + bpelPackageName + " in the repository. If the bpel package is un-deployed through the management" + " console or if this node is a member of a cluster, please ignore this warning."; if(isConfigRegistryReadOnly()) { // This is for the deployment synchronizer scenarios where package un-deployment on a worker node // has to remove the deployed bpel package from the memory and remove associated services handleUndeployOnSlaveNode(bpelPackageName); } else { log.warn(warningMsg); } return; } if (repository.isExistingBPELPackage(bpelPackageName) && isConfigRegistryReadOnly()) { log.warn("This node seems to be a slave, since the configuration registry is in read-only mode, hence processes cannot be directly undeployed from this node. Please undeploy the process in Master node first."); return; } List<String> versionsOfThePackage; try { versionsOfThePackage = repository.getAllVersionsForPackage(bpelPackageName); } catch (RegistryException re) { String errMessage = "Cannot get all versions of the package " + bpelPackageName + " from registry."; log.error(errMessage); throw re; } for (String nameWithVersion : versionsOfThePackage) { parentProcessStore.deleteDeploymentUnitDataFromDB(nameWithVersion); Utils.deleteInstances(getProcessesInPackage(nameWithVersion)); //location for extracted BPEL package String bpelPackageLocation = parentProcessStore.getLocalDeploymentUnitRepo().getAbsolutePath() + File.separator + tenantId + File.separator + nameWithVersion; File bpelPackage = new File(bpelPackageLocation); //removing extracted bpel package at repository/bpel/0/ deleteBpelPackageFromRepo(bpelPackage); for (QName pid : getProcessesInPackage(nameWithVersion)) { ProcessConfigurationImpl processConf = (ProcessConfigurationImpl) getProcessConfiguration(pid); // This property is read when we removing the axis service for this process. // So that we can decide whether we should persist service QOS configs processConf.setUndeploying(true); } } try { repository.handleBPELPackageUndeploy(bpelPackageName); } catch (RegistryException re) { String errMessage = "Cannot update the BPEL package repository for undeployment of" + "package " + bpelPackageName + "."; log.error(errMessage); throw re; } updateLocalInstanceWithUndeployment(bpelPackageName, versionsOfThePackage); // We should use the deployment synchronizer, instead of the code below. // parentProcessStore.sendProcessDeploymentNotificationsToCluster( // new BPELPackageUndeployedCommand(versionsOfThePackage, bpelPackageName, tenantId), // configurationContext); } /** * Undeployment scenario in a worker node( Slave ) in the clustered setup * When the BPELDeployer get called for undeploying the bpel package, following has already taken place. * The package information stored in the registry as well as the zip archive is deleted * Process, Instance information have been removed from the ODE database * However, on the slave node, the bpel process and the web services associated with the bpel process * is still in memory. We need to unload the bpel process and the associated web services * @param bpelPackageName bpel package name * @return * */ private int handleUndeployOnSlaveNode( String bpelPackageName) { List<String> packageList = findMatchingProcessByPackageName(bpelPackageName); if(packageList.size() < 1) { log.debug("Handling un-deploy operation on salve (worker) node : package list is empty"); return -1; } for(String packageName : packageList) { //location for extracted BPEL package String bpelPackageLocation = parentProcessStore.getLocalDeploymentUnitRepo().getAbsolutePath() + File.separator + tenantId + File.separator + packageName; File bpelPackage = new File(bpelPackageLocation); //removing extracted bpel package at repository/bpel/tenantID/ deleteBpelPackageFromRepo(bpelPackage); for (QName pid : getProcessesInPackage(packageName)) { ProcessConfigurationImpl processConf = (ProcessConfigurationImpl) getProcessConfiguration(pid); // This property is read when we removing the axis service for this process. // So that we can decide whether we should persist service QOS configs processConf.setUndeploying(true); } } Collection<QName> undeployedProcesses = new ArrayList<QName>(); for (String nameWithVersion : packageList) { undeploySpecificVersionOfBPELPackage(nameWithVersion, undeployedProcesses); } BPELServerImpl instance = BPELServerImpl.getInstance(); BpelServerImpl odeBpelServer = instance.getODEBPELServer(); for (QName pid : undeployedProcesses) { odeBpelServer.unregister(pid); ProcessConf pConf = parentProcessStore.getProcessConfiguration(pid); if(pConf != null) { if (log.isDebugEnabled()) { log.debug("Cancelling all cron scheduled jobs for process " + pid); } odeBpelServer.getContexts().cronScheduler.cancelProcessCronJobs( pid, true); } log.info("Process " + pid + " un-deployed."); } parentProcessStore.updateProcessAndDUMapsForSalve(tenantId, bpelPackageName, undeployedProcesses); return 0; } private List<String> findMatchingProcessByPackageName(String packageName) { List<String> stringList = new ArrayList<String>(); Set<String> strings = processesInDeploymentUnit.keySet(); String regexPattern = packageName + "-(\\d*)"; Pattern pattern = Pattern.compile(regexPattern); Iterator<String> iterator = strings.iterator(); while (iterator.hasNext()) { String next = iterator.next(); Matcher matcher= pattern.matcher(next); if(matcher.matches()) { stringList.add(next); } } return stringList; } private void deleteBpelPackageFromRepo(File bpelPackage) { log.info("Undeploying BPEL package. " + "Deleting " + bpelPackage + " BPEL package"); if (bpelPackage.exists()) { FileManipulator.deleteDir(bpelPackage); } else { log.warn("BPEL package " + bpelPackage.getAbsolutePath() + " not found. This can happen if you delete " + "the BPEL package from the file system."); } } /** * Update the local instance of the BPS server regarding the undeployment of the bpel package. * * @param bpelPackageName Name of the BPEL package * @param versionsOfThePackage List of deployed versions of the package */ public void updateLocalInstanceWithUndeployment(String bpelPackageName, List<String> versionsOfThePackage) { // Delete the package from the file repository deleteBpelArchive(bpelPackageName); Collection<QName> undeployedProcesses = new ArrayList<QName>(); for (String nameWithVersion : versionsOfThePackage) { undeploySpecificVersionOfBPELPackage(nameWithVersion, undeployedProcesses); } parentProcessStore.updateMapsAndFireStateChangeEventsForUndeployedProcesses(tenantId, bpelPackageName, undeployedProcesses); } /** * Delete BPEL Archive from the BPEL repository of the file system. * * @param bpelPackageName Name of the BPEL package */ private void deleteBpelArchive(String bpelPackageName) { String bpelArchiveLocation = tenantConfigContext.getAxisConfiguration().getRepository(). getPath() + File.separator + BPELConstants.BPEL_REPO_DIRECTORY + File.separator + bpelPackageName + "." + BPELConstants.BPEL_PACKAGE_EXTENSION; log.info("Undeploying BPEL package " + bpelPackageName + ". Deleting BPEL archive " + bpelArchiveLocation + "...."); File bpelArchive = new File(bpelArchiveLocation); if (bpelArchive.exists()) { if (!bpelArchive.delete()) { //For windows bpelArchive.deleteOnExit(); } } else { log.warn("BPEL archive " + bpelArchive.getAbsolutePath() + " not found. This can happen if you delete " + "the BPEL archive from the file system."); } } private void undeploySpecificVersionOfBPELPackage(final String packageName, final Collection<QName> undeployedProcesses) { DeploymentUnitDir du = deploymentUnits.remove(packageName); processesInDeploymentUnit.remove(packageName); if (du != null) { long version = du.getVersion(); for (QName name : du.getProcessNames()) { QName pid = Utils.toPid(name, version); undeployedProcesses.add(pid); } } } public void handleTenantUnload() { } public void hydrate() { } public ProcessConf getProcessConfiguration(QName pid) { return processConfigMap.get(pid); } public void setState(QName pid, ProcessState processState) throws Exception { if (log.isDebugEnabled()) { log.debug("Changing state of the process " + pid + " to " + processState); } if (!isProcessExist(pid)) { String errMsg = "Process " + pid + " not found."; log.error(errMsg); // TODO : Introduce hierarchical exceptions to ODE integration layer. throw new Exception(errMsg); } if (processState == null) { String errMessage = "Process State cannot be null."; log.error(errMessage); throw new Exception(errMessage); } parentProcessStore.setState(pid, processState); parentProcessStore.sendProcessDeploymentNotificationsToCluster( new BPELProcessStateChangedCommand(pid, processState, tenantId)); } private Boolean isProcessExist(QName pid) { return processConfigMap.containsKey(pid); } public BPELPackageRepository getBPELPackageRepository() { return repository; } public Map<QName, ProcessConfigurationImpl> getProcessConfigMap() { return processConfigMap; } public ProcessConf removeProcessConfiguration(QName pid) { return processConfigMap.remove(pid); } public List<QName> getProcessesInPackage(String packageName) { List<QName> processes = processesInDeploymentUnit.get(packageName); if (processes == null) { processes = Collections.EMPTY_LIST; } return processes; } public Boolean containsProcess(QName pid) { return processConfigMap.containsKey(pid); } public void setBpelArchiveRepo(File bpelArchiveRepo) { this.bpelArchiveRepo = bpelArchiveRepo; } /** * Log and store the information to registry on BPEL deployment error. * * @param deploymentContext information about current deployment * @throws RegistryException on error accessing registry for persisting information. */ private void handleDeploymentError(BPELDeploymentContext deploymentContext) throws Exception { if (deploymentContext.getStackTrace() != null) { log.error(deploymentContext.getDeploymentFailureCause(), deploymentContext.getStackTrace()); } else { log.error(deploymentContext.getDeploymentFailureCause()); } // Stop writing the error condition to the registry. //repository.handleBPELPackageDeploymentError(deploymentContext); } /** * Reload old versions of BPEL package. This is used to handle restart of BPEL server. * At restart based on the last modified time of the BPEL archives we'll reload all the versions * of that BPEL archive. * * @param deploymentContext information about current deployment * @throws RegistryException on error loading resources from registry. * @throws org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.ProcessManagementException * */ private void reloadExistingVersionsOfBPELPackage(BPELDeploymentContext deploymentContext) throws RegistryException, ProcessManagementException { BPELPackageInfo bpelPackage = repository.getBPELPackageInfo(deploymentContext); for (String packageName : bpelPackage.getAvailableVersions()) { if (!deploymentUnits.containsKey(packageName)) { loadExistingBPELPackage(packageName); } } } /** * Deploy BPEL package in ODE and add process configuration objects to necessary maps in process * store. * * @param deploymentContext information about current deployment * @throws Exception in case of duplicate deployment unit or if error occurred during deploying package in ODE */ private void deployBPELPackageInODE(BPELDeploymentContext deploymentContext) throws Exception { File bpelPackage = deploymentContext.getBPELPackageContent(); log.info("Starting deployment of processes from directory " + bpelPackage.getAbsolutePath()); final Date deployDate = new Date(); // Create the DU and compile/scan it before doing any other work. final DeploymentUnitDir du = new DeploymentUnitDir(bpelPackage); // Before coming to this stage, we create the bpel package directory with the static version // so we don't need to get the version from database. We can directly use static version // calculated from bpel package directory name. du.setVersion(du.getStaticVersion()); try { du.compile(); } catch (CompilationException ce) { String logMessage = "Deployment failed due to compilation issues. " + ce.getMessage(); log.error(logMessage, ce); deploymentContext.setFailed(true); deploymentContext.setDeploymentFailureCause(logMessage); deploymentContext.setStackTrace(ce); handleDeploymentError(deploymentContext); throw new BPELDeploymentException(logMessage, ce); } du.scan(); DeployDocument dd = du.getDeploymentDescriptor(); List<ProcessConfigurationImpl> processConfs = new ArrayList<ProcessConfigurationImpl>(); List<QName> processIds = new ArrayList<QName>(); if (deploymentUnits.containsKey(du.getName())) { String logMessage = "Aborting deployment. Duplicate Deployment unit " + du.getName() + "."; log.error(logMessage); deploymentContext.setFailed(true); deploymentContext.setDeploymentFailureCause(logMessage); handleDeploymentError(deploymentContext); throw new BPELDeploymentException(logMessage); } // Validate BPEL package partially before retiring old versions. validateBPELPackage(du); if (deploymentContext.isExistingPackage()) { reloadExistingVersionsOfBPELPackage(deploymentContext); } // Before updating a BPEL package we need to retire processes in old version retirePreviousPackageVersions(du); for (TDeployment.Process processDD : dd.getDeploy().getProcessList()) { QName processId = Utils.toPid(processDD.getName(), du.getVersion()); ProcessConfigurationImpl processConf = new ProcessConfigurationImpl( tenantId, processDD, du, deployDate, parentProcessStore.getEndpointReferenceContext(), tenantConfigContext); processConf.setAbsolutePathForBpelArchive(deploymentContext.getBpelArchive().getAbsolutePath()); processIds.add(processId); processConfs.add(processConf); readBAMServerProfiles(processDD, du); } deploymentUnits.put(du.getName(), du); processesInDeploymentUnit.put(du.getName(), processIds); for (ProcessConfigurationImpl processConf : processConfs) { processConfigMap.put(processConf.getProcessId(), processConf); deploymentContext.addProcessId(processConf.getProcessId()); } try { parentProcessStore.onBPELPackageDeployment( tenantId, du.getName(), BPELPackageRepositoryUtils.getResourcePathForBPELPackageContent(deploymentContext), processConfs); } catch (ContextException ce) { deploymentContext.setDeploymentFailureCause("BPEL Package deployment failed at " + "ODE layer. Possible cause: " + ce.getMessage()); deploymentContext.setStackTrace(ce); deploymentContext.setFailed(true); handleDeploymentError(deploymentContext); throw ce; } } /** * Check whether processes in this package are already available in the process store or check * whether processes are correctly compiled. * * @param du BPEL deployment unit * @throws BPELDeploymentException if there's a error in BPEL package */ private void validateBPELPackage(DeploymentUnitDir du) throws BPELDeploymentException { DeployDocument dd = du.getDeploymentDescriptor(); for (TDeployment.Process processDD : dd.getDeploy().getProcessList()) { QName processId = Utils.toPid(processDD.getName(), du.getVersion()); if (processConfigMap.containsKey(processId)) { String logMessage = "Aborting deployment. Duplicate process ID " + processId + "."; log.error(logMessage); throw new BPELDeploymentException(logMessage); } QName processType = Utils.getProcessType(processDD); DeploymentUnitDir.CBPInfo cbpInfo = du.getCBPInfo(processType); if (cbpInfo == null) { //removeDeploymentArtifacts(deploymentContext, du); String logMessage = "Aborting deployment. Cannot find Process definition for type " + processType + "."; log.error(logMessage); throw new BPELDeploymentException(logMessage); } } } private void handleDeploymentErrorsAtODELayer(BPELDeploymentContext deploymentContext, String duName) { deploymentUnits.remove(duName); processesInDeploymentUnit.remove(duName); for (QName pid : deploymentContext.getProcessIdsForCurrentDeployment()) { processConfigMap.remove(pid); } } private void loadExistingBPELPackage(String bpelPackageName) throws RegistryException, ProcessManagementException, BPELDeploymentException { DeploymentUnitDAO duDAO = parentProcessStore.getDeploymentUnitDAO(bpelPackageName); if (duDAO == null) { String errMsg = "Cannot find DeploymentUnitDAO instance for package " + bpelPackageName + "."; log.error(errMsg); throw new BPELDeploymentException(errMsg); } File bpelPackage = findBPELPackageInFileSystem(duDAO); if (bpelPackage == null || !bpelPackage.exists()) { throw new BPELDeploymentException("Deployed directory " + bpelPackage + " no longer there!"); } DeploymentUnitDir du = new DeploymentUnitDir(bpelPackage); du.setVersion(du.getStaticVersion()); du.scan(); List<ProcessConfigurationImpl> loaded = new ArrayList<ProcessConfigurationImpl>(); List<QName> processIds = new ArrayList<QName>(); for (ProcessConfDAO pConfDAO : duDAO.getProcesses()) { TDeployment.Process processDD = du.getProcessDeployInfo(pConfDAO.getType()); if (processDD == null) { log.warn("Cannot load " + pConfDAO.getPID() + "; cannot find descriptor."); continue; } // TODO: update the props based on the values in the DB. ProcessConfigurationImpl pConf = new ProcessConfigurationImpl( tenantId, processDD, du, duDAO.getDeployDate(), parentProcessStore.getEndpointReferenceContext(), tenantConfigContext); pConf.setAbsolutePathForBpelArchive(bpelPackage.getAbsolutePath()); pConf.setState(pConfDAO.getState()); processIds.add(pConfDAO.getPID()); // if the deployment descriptor is updated at runtime, first load the updated data in // registry and use them with the specific process repository.readPropertiesOfUpdatedDeploymentInfo(pConf, bpelPackageName); readBAMServerProfiles(processDD, du); processConfigMap.put(pConf.getProcessId(), pConf); loaded.add(pConf); } deploymentUnits.put(du.getName(), du); processesInDeploymentUnit.put(du.getName(), processIds); parentProcessStore.onBPELPackageReload(tenantId, du.getName(), loaded); } private void readBAMServerProfiles(TDeployment.Process processDD, DeploymentUnitDir du){ TBAMServerProfiles bamServerProfiles = processDD.getBamServerProfiles(); if (bamServerProfiles != null) { for (TBAMServerProfiles.Profile bamServerProfile : bamServerProfiles.getProfileList()) { String location = bamServerProfile.getLocation(); if (location.startsWith(UnifiedEndpointConstants.VIRTUAL_FILE)) { if (!EndpointConfiguration.isAbsoutePath( location.substring(UnifiedEndpointConstants.VIRTUAL_FILE.length()))) { location = EndpointConfiguration.getAbsolutePath( du.getDeployDir().getAbsolutePath(), location.substring(UnifiedEndpointConstants.VIRTUAL_FILE.length())); } } else if((!location.startsWith(UnifiedEndpointConstants.VIRTUAL_CONF_REG) && !location.startsWith(UnifiedEndpointConstants.VIRTUAL_GOV_REG) && !location.startsWith(UnifiedEndpointConstants.VIRTUAL_REG))) { if(EndpointConfiguration.isAbsoutePath(location)){ location = UnifiedEndpointConstants.VIRTUAL_FILE + location; }else { location = EndpointConfiguration.getAbsolutePath(du.getDeployDir().getAbsolutePath(), location); location = UnifiedEndpointConstants.VIRTUAL_FILE + location; } } BAMServerProfileBuilder builder = new BAMServerProfileBuilder(location, tenantId); BAMServerProfile profile = builder.build(); addBAMServerProfile(profile.getName(), profile); } } } private File findBPELPackageInFileSystem(DeploymentUnitDAO dudao) { String duName = dudao.getName(); // Done: Fix the logic to handle registry log.info("Looking for BPEL package in file system for deployment unit " + duName); File bpelDUDirectory = new File(bpelDURepo, duName); if (bpelDUDirectory.exists()) { return bpelDUDirectory; } else { String registryCollectionPath = dudao.getDeploymentUnitDir(); try { if (tenantConfigRegistry.resourceExists(registryCollectionPath)) { if (!bpelDUDirectory.exists() && !bpelDUDirectory.mkdirs()) { String errMsg = "Error creating BPEL deployment unit repository for " + "tenant " + tenantId; log.error(errMsg); log.error("Failed to load BPEL deployment unit " + duName + " due to above error."); throw new BPELDeploymentException(errMsg); } boolean deployedOnCarbon310 = false; //Check whether the registry repo is of type carbon 3.1.0 if (tenantConfigRegistry.resourceExists(registryCollectionPath + RegistryConstants.PATH_SEPARATOR + duName)) { registryCollectionPath += RegistryConstants.PATH_SEPARATOR + duName; deployedOnCarbon310 = true; if (log.isDebugEnabled()) { log.debug("Found a carbon 3.1.0 compatible deployment unit at " + registryCollectionPath); } } RegistryClientUtils.exportFromRegistry(bpelDUDirectory, registryCollectionPath, tenantConfigRegistry); if (deployedOnCarbon310) { if (log.isDebugEnabled()) { log.debug("Recompiling the carbon 3.1.0 compatible deployment unit at " + bpelDUDirectory); } //Re-compiling to get rid of binary compatibility issues. DeploymentUnitDir du = new DeploymentUnitDir(bpelDUDirectory); for (File file : du.allFiles()) { if (file.getAbsolutePath().endsWith(".cbp") && !file.delete()) { log.warn("Unable to delete " + file); } } du.compile(); } return bpelDUDirectory; } else { String errMsg = "Expected resource: " + registryCollectionPath + " not found in the registry"; log.error(errMsg); throw new BPELDeploymentException(errMsg); } } catch (RegistryException re) { String errMsg = "Error while exporting deployment unit: " + duName + " to file system from the registry."; log.error(errMsg, re); throw new BPELDeploymentException(errMsg, re); } } } /** * Retire all the other versions of the same DU: * first take the DU name and insert version regexp, * than try to match the this string against names of already deployed DUs. * For instance if we are deploying DU "AbsenceRequest-2/AbsenceRequest.ode" and * there's already version 2 than regexp * "AbsenceRequest([-\\.](\d)+)?/AbsenceRequest.ode" will be matched against * "AbsenceRequest-2/AbsenceRequest.ode" and setRetirePackage() will be called accordingly. * * @param du DeploymentUnitDir object containing in-memory representation of BPEL package.  */ private void retirePreviousPackageVersions(DeploymentUnitDir du) { //retire all the other versions of the same DU String[] nameParts = du.getName().split("/"); /* Replace the version number (if any) with regexp to match any version number */ nameParts[0] = nameParts[0].replaceAll("([-\\Q.\\E](\\d)+)?\\z", ""); nameParts[0] += "([-\\Q.\\E](\\d)+)?"; StringBuilder duNameRegExp = new StringBuilder(du.getName().length() * 2); for (int i = 0, n = nameParts.length; i < n; i++) { if (i > 0) { duNameRegExp.append("/"); } duNameRegExp.append(nameParts[i]); } Pattern duNamePattern = Pattern.compile(duNameRegExp.toString()); for (String deployedDUname : deploymentUnits.keySet()) { Matcher matcher = duNamePattern.matcher(deployedDUname); if (matcher.matches()) { parentProcessStore.setRetiredPackage(deployedDUname, true); } } } private boolean validateBPELPackage(BPELDeploymentContext bpelDeploymentContext, boolean isExistingPackage) { DeploymentUnitDir du; try { du = new DeploymentUnitDir(bpelDeploymentContext.getBPELPackageContent()); } catch (IllegalArgumentException e) { bpelDeploymentContext.setDeploymentFailureCause(e.getMessage()); bpelDeploymentContext.setStackTrace(e); return false; } if (!isExistingPackage) { DeployDocument deployDocument = du.getDeploymentDescriptor(); List<TDeployment.Process> processList = deployDocument.getDeploy().getProcessList(); for (TDeployment.Process process : processList) { List<TProvide> provideList = process.getProvideList(); for (TProvide provide : provideList) { if (getDeployedServices().containsKey(provide.getService().getName())) { String errMsg = "Service: " + provide.getService().getName() + " already " + "used by another process. Try again with a different " + "service name"; bpelDeploymentContext.setDeploymentFailureCause(errMsg); return false; } } } } return true; } /** * Current bpel package can be coming from a cApp. If that is the case, we have to attach * this process with its owner cApp. * * @param bpelArchiveName - file name of the BPEL package * @param bpelPackageName - package name extracted out of the archive name * @param tenantId - current tenant id */ private void attachWithCapp(String bpelArchiveName, String bpelPackageName, int tenantId) { // attach with cApp AppDeployerUtils.attachArtifactToOwnerApp(bpelArchiveName, BPELConstants.BPEL_TYPE, bpelPackageName, tenantId); } public Map<QName, Object> getDeployedServices() { return parentProcessStore.getServicesPublishedByTenant(tenantId); } public void addBAMServerProfile(String name, BAMServerProfile profile) { bamProfiles.put(name, profile); } public BAMServerProfile getBAMServerProfile(String name) { return bamProfiles.get(name); } public synchronized void addDataPublisher(String processName, Object publisher) { dataPublisherMap.put(processName, publisher); } public Object getDataPublisher(String processName) { return dataPublisherMap.get(processName); } public Map getDataPublisherMap(){ return dataPublisherMap; } public DeploymentUnitDir getDeploymentUnitDir(QName pid) { for (String du : processesInDeploymentUnit.keySet()) { if (processesInDeploymentUnit.get(du) != null) { if (processesInDeploymentUnit.get(du).contains(pid)) { return deploymentUnits.get(du); } } } return null; } }
maheshika/carbon-business-process
components/bpel/org.wso2.carbon.bpel/src/main/java/org/wso2/carbon/bpel/core/ode/integration/store/TenantProcessStoreImpl.java
Java
apache-2.0
45,284
package com.examw.oa.domain.plan; import java.io.Serializable; import java.util.Date; import com.examw.oa.domain.check.Entry; import com.examw.oa.domain.org.Employee; /** * 部门计划成员。 * <pre> * 部门下的员工可以在[查看我的计划]中查看到自己的计划安排; * 并可以进行[完成申请],由部门负责人确认后更新<code>status</code>并记录<code>finishTime</code> * content:由部门负责人分配的计划内容; * remarks:为计划成员在[完成申请]时提交的备注信息; * </pre> * @author yangyong. * @since 2014-07-30. */ public class DeptPlanMember implements Serializable { private static final long serialVersionUID = 1L; private String id,content,remarks; private DeptPlan plan; private Employee employee; private Entry entry; private Integer status; private Date createTime,lastTime,startTime,endTime,finishTime; /** * 获取所属部门计划。 * @return 所属部门计划。 */ public DeptPlan getPlan() { return plan; } /** * 设置所属部门计划。 * @param plan * 所属部门计划。 */ public void setPlan(DeptPlan plan) { this.plan = plan; } /** * 获取成员计划ID。 * @return 成员计划ID。 */ public String getId() { return id; } /** * 设置成员计划ID。 * @param id * 成员计划ID。 */ public void setId(String id) { this.id = id; } /** * 获取成员计划内容。 * @return 成员计划内容。 */ public String getContent() { return content; } /** * 设置成员计划内容。 * @param content * 成员计划内容。 */ public void setContent(String content) { this.content = content; } /** * 获取所属部门员工。 * @return 所属部门员工。 */ public Employee getEmployee() { return employee; } /** * 设置所属部门员工。 * @param employee * 所属部门员工。 */ public void setEmployee(Employee employee) { this.employee = employee; } /** * 获取所属奖惩条目。 * @return 所属奖惩条目。 */ public Entry getEntry() { return entry; } /** * 设置所属奖惩条目。 * @param entry * 所属奖惩条目。 */ public void setEntry(Entry entry) { this.entry = entry; } /** * 获取成员计划状态(0-未开始,1-开始,2-确认请求,3-完成)。 * @return 成员计划状态(0-未开始,1-开始,2-确认请求,3-完成)。 */ public Integer getStatus() { return status; } /** * 设置成员计划状态(0-未开始,1-开始,2-确认请求,3-完成)。 * @param status * 成员计划状态(0-未开始,1-开始,2-确认请求,3-完成)。 */ public void setStatus(Integer status) { this.status = status; } /** * 获取员工备注。 * @return 员工备注。 */ public String getRemarks() { return remarks; } /** * 设置员工备注。 * @param remarks * 员工备注。 */ public void setRemarks(String remarks) { this.remarks = remarks; } /** * 获取创建时间。 * @return 创建时间。 */ public Date getCreateTime() { return createTime; } /** * 设置创建时间。 * @param createTime * 创建时间。 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取最后修改时间。 * @return 最后修改时间。 */ public Date getLastTime() { return lastTime; } /** * 设置最后修改时间。 * @param lastTime * 最后修改时间。 */ public void setLastTime(Date lastTime) { this.lastTime = lastTime; } /** * 获取成员计划开始时间。 * @return 成员计划开始时间。 */ public Date getStartTime() { return startTime; } /** * 设置成员计划开始时间。 * @param startTime * 成员计划开始时间。 */ public void setStartTime(Date startTime) { this.startTime = startTime; } /** * 获取成员计划结束时间。 * @return 成员计划结束时间。 */ public Date getEndTime() { return endTime; } /** * 设置成员计划结束时间。 * @param endTime * 成员计划结束时间。 */ public void setEndTime(Date endTime) { this.endTime = endTime; } /** * 获取成员计划完成时间。 * @return 成员计划完成时间。 */ public Date getFinishTime() { return finishTime; } /** * 设置成员计划完成时间。 * @param finishTime * 成员计划完成时间。 */ public void setFinishTime(Date finishTime) { this.finishTime = finishTime; } }
jeasonyoung/examw-oa
src/main/java/com/examw/oa/domain/plan/DeptPlanMember.java
Java
apache-2.0
4,528
package com.amplifino.obelix.hash; import java.util.stream.LongStream; import java.util.stream.Stream; import org.osgi.annotation.versioning.ProviderType; import com.amplifino.obelix.pairs.LongKeyPair; import com.amplifino.obelix.sets.LongFullFunction; @ProviderType public interface HashSpace<T> extends LongFullFunction<T> { long capacity(); @Override default LongStream domain() { return LongStream.range(0, capacity()); } @Override default Stream<LongKeyPair<T>> graph() { return domain().mapToObj(LongKeyPair.graph(this::get)); } @Override default Stream<T> range() { return domain().mapToObj(this::get); } HashSpace<T> put(long key, T value); }
Amplifino/obelix
com.amplifino.obelix.maps/src/com/amplifino/obelix/hash/HashSpace.java
Java
apache-2.0
718
/******************************************************************************* * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.wincom.actor.editor.flow.policies; import org.eclipse.gef.commands.Command; import org.eclipse.gef.editpolicies.ComponentEditPolicy; import com.wincom.actor.editor.flow.model.Activity; import com.wincom.actor.editor.flow.model.StructuredActivity; import com.wincom.actor.editor.flow.model.commands.DeleteCommand; import org.eclipse.gef.requests.GroupRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Daniel Lee */ public class ActivityEditPolicy extends ComponentEditPolicy { Logger log = LoggerFactory.getLogger(this.getClass()); /** * @see ComponentEditPolicy#createDeleteCommand(org.eclipse.gef.requests.GroupRequest) */ protected Command createDeleteCommand(GroupRequest deleteRequest) { log.info("check"); StructuredActivity parent = (StructuredActivity) (getHost().getParent() .getModel()); DeleteCommand deleteCmd = new DeleteCommand(); deleteCmd.setParent(parent); deleteCmd.setChild((Activity) (getHost().getModel())); return deleteCmd; } }
xtwxy/actor-editor
plugins/com.wincom.actor.editor.flow/src/com/wincom/actor/editor/flow/policies/ActivityEditPolicy.java
Java
apache-2.0
1,563
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.palette; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.Nullable; /** * @author yole */ public interface PaletteGroup { PaletteGroup[] EMPTY_ARRAY = new PaletteGroup[0]; PaletteItem[] getItems(); /** * Returns the text of the group header for the palette group. * * @return the text of the group header for the palette group, or null if no header should be shown. */ @Nullable String getName(); String getTabName(); /** * Returns the action group from which the context menu is built when the palette * item is right-clicked. * * @return the action group, or null if no context menu should be shown. */ @Nullable ActionGroup getPopupActionGroup(); /** * Returns the data for the specified data constant. * * @param project the project in the context of which data is requested. * @param dataId the data constant id (see {@link com.intellij.openapi.actionSystem.DataConstants}). * @return the data item, or null if no data is available for this constant. */ @Nullable Object getData(Project project, String dataId); /** * Processes the drop of a palette item on the specified index in the palette group. * * @param project the project to which the drop target palette belongs. * @param item the dropped item. * @param index the index at which the dropped item should be inserted (from 0 to getItems().length). */ void handleDrop(Project project, PaletteItem item, int index); }
jexp/idea2
java/openapi/src/com/intellij/ide/palette/PaletteGroup.java
Java
apache-2.0
2,190
/* * Copyright (C) 2013 The Conclusions Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file without in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ru.rulex.conclusion; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.*; import org.junit.Test; import ru.rulex.conclusion.execution.Callables; import ru.rulex.conclusion.execution.ParallelStrategy; import ru.rulex.conclusion.ConclusionFunction; import ru.rulex.conclusion.FluentConclusionPredicate; import ru.rulex.conclusion.PhraseExecutionException; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static ru.rulex.conclusion.FluentConclusionPredicate.*; import static ru.rulex.conclusion.RulexMatchersDsl.*; public class TestParallelStrategyExecution { private final ListeningExecutorService service = MoreExecutors.listeningDecorator( Executors .newFixedThreadPool( Runtime.getRuntime().availableProcessors() / 2 ) ); private interface FutureMerger<T> { ListenableFuture<List<T>> merged( List<ListenableFuture<T>> futures ); } FutureMerger<Boolean> allMerger = new FutureMerger<Boolean>() { @Override public ListenableFuture<List<Boolean>> merged( List<ListenableFuture<Boolean>> futures ) { return Futures.allAsList( futures ); } }; FutureMerger<Boolean> successMerger = new FutureMerger<Boolean>() { @Override public ListenableFuture<List<Boolean>> merged( List<ListenableFuture<Boolean>> futures ) { return Futures.successfulAsList( futures ); } }; @Test public void testBind() throws Exception { Model en = Model.from( 40 ); assertTrue( "testBind error !!!", Callables.bind( Callables.identity( en ), new ConclusionFunction<Model, Callable<Boolean>>() { @Override public Callable<Boolean> apply( final Model argument ) { return new Callable<Boolean>() { String accessor = Model.INT_ACCESSOR; FluentConclusionPredicate<?> fluent = fluent(); @Override public Boolean call() { return fluent.eq( argument( 23 ), descriptor( Model.class, accessor ) ) .and( fluent.eq( argument( 39 ), descriptor( Model.class, accessor ) ) ) .and( fluent.eq( argument( 39 ), descriptor( Model.class, accessor ) ) ) .or( fluent.eq( argument( 40 ), descriptor( Model.class, accessor ) ) ) .apply( argument ); } }; } } ).call() ); } @Test public void testBlockToGetResult() throws Exception { // explicitly block execution thread assertTrue( "testBlockToGetResult 1 error !!!", ParallelStrategy.<Boolean>listenableFutureStrategy( service ) .lift( new ConclusionFunction<Integer, Boolean>() { @Override public Boolean apply( Integer argument ) { return always().apply( argument ); } } ).apply( 2 ).get() ); // implicitly block execution thread assertTrue( "testBlockToGetResult 2 error !!!", Callables.obtain( ParallelStrategy.<Boolean> listenableFutureStrategy( service ) .lift( new ConclusionFunction<Integer, Boolean>() { @Override public Boolean apply( Integer argument ) { return always().apply( argument ); } } ).apply( 2 ) ).call() ); } @Test public void testFmap() throws Exception { Model en = Model.from( 40 ); assertTrue( "testFmap error !!!", Callables.fmap( new ConclusionFunction<Model, Boolean>() { @Override public Boolean apply( Model argument ) { return always().apply( argument ); } } ).apply( Callables.identity( en ) ).call() ); } @Test public void testListenableFutureWithParallelStrategy() throws InterruptedException { Model en = Model.from( 40 ); final CountDownLatch latch = new CountDownLatch( 1 ); FutureCallback<List<Boolean>> callback = new FutureCallback<List<Boolean>>() { @Override public void onSuccess( List<Boolean> result ) { latch.countDown(); } @Override public void onFailure( Throwable t ) { fail( "testWithParallelStrategy error" ); } }; ParallelStrategy<Boolean> pStrategy = ParallelStrategy .listenableFutureStrategy( service ); ImmutableList.Builder<ListenableFuture<Boolean>> blist = ImmutableList.builder(); blist.add( pStrategy.lift( new ConclusionFunction<Model, Boolean>() { @Override public Boolean apply( Model argument ) { String accessor = Model.INT_ACCESSOR; return fluent().eq( argument( 39 ), descriptor( Model.class, accessor ) ) .and( fluent().eq( argument( 39 ), descriptor( Model.class, accessor ) ) ) .and( fluent().eq( argument( 39 ), descriptor( Model.class, accessor ) ) ) .or( fluent().eq( argument( 40 ), descriptor( Model.class, accessor ) ) ) .apply( argument ); } } ).apply( en ) ); blist.add( pStrategy.lift( new ConclusionFunction<Model, Boolean>() { @Override public Boolean apply( Model argument ) { return true; } } ).apply( en ) ); Futures.addCallback( allMerger.merged( blist.build() ), callback ); assertTrue( "testWithParallelStrategy error !!!", latch.await( 5, TimeUnit.SECONDS ) ); } /** * with obtain we implicitly block execution thread on {@code future.get()} * * @throws Exception */ @Test public void testObtainWithException() throws Exception { Model en = Model.from( 40 ); ParallelStrategy<Boolean> pStrategy = ParallelStrategy .listenableFutureStrategy( service ); try { Callables.bind( Callables.obtain( pStrategy.lift( new ConclusionFunction<Model, Boolean>() { @Override public Boolean apply( Model argument ) { throw new IllegalArgumentException( "expected" ); } } ).apply( en ) ), new ConclusionFunction<Boolean, Callable<Integer>>() { @Override public Callable<Integer> apply( Boolean argument ) { // post action, executed in main thread after function completion // 0 could be possitive result marker return Callables.identity( 0 ); } } ).call(); } catch (PhraseExecutionException e) { e.printStackTrace(); // expected } catch (Exception ex) { fail( "testObtainWithException error !!!" ); } } }
haghard/Rulex
src/test/java/ru/rulex/conclusion/TestParallelStrategyExecution.java
Java
apache-2.0
7,496
/* * Copyright (c) 2015 Akexorcist * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.akexorcist.localizationactivity; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import java.util.Locale; /** * Created by Akexorcist on 7/20/15 AD. */ public class LanguageSetting { private static final String PREFERENCE_LANGUAGE = "pref_language"; private static final String KEY_LANGUAGE = "key_language"; private static String DEFAULT_LANGUAGE = Locale.ENGLISH.getLanguage(); private static String currentLanguage = Locale.ENGLISH.getLanguage(); public static void setDefaultLanguage(String language) { DEFAULT_LANGUAGE = language; } public static String getDefaultLanguage() { return DEFAULT_LANGUAGE; } public static void setLanguage(Context context, String language) { currentLanguage = language; SharedPreferences.Editor editor = getLanguagePreference(context).edit(); editor.putString(KEY_LANGUAGE, language); editor.apply(); } public static void setLanguage(Context context, Locale locale) { setLanguage(context, locale.getLanguage()); } public static String getLanguage() { return currentLanguage; } private static String getLanguage(Context context) { return getLanguagePreference(context).getString(KEY_LANGUAGE, DEFAULT_LANGUAGE); } private static SharedPreferences getLanguagePreference(Context context) { return context.getSharedPreferences(PREFERENCE_LANGUAGE, Activity.MODE_PRIVATE); } public static void setDefaultLanguage(Locale locale) { LanguageSetting.setDefaultLanguage(locale.getLanguage()); } public static Locale getLocale() { return getLocale(getLanguage()); } public static Locale getLocale(Context context) { return getLocale(getLanguage(context)); } public static Locale getLocale(String language) { return new Locale(language.toLowerCase(Locale.getDefault())); } }
first087/Android-LocalizationActivity
localizationActivity/src/main/java/com/akexorcist/localizationactivity/LanguageSetting.java
Java
apache-2.0
3,113
package com.zjw.mobilesafe.service; import java.util.List; import com.zjw.mobilesafe.InputPwdActivity; import com.zjw.mobilesafe.db.dao.AppLockDao; import android.app.ActivityManager; import android.app.ActivityManager.RunningTaskInfo; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; public class WatchdogService extends Service { private ActivityManager am; private boolean flag; private AppLockDao dao; private TmpStopReceiver tmpStopReceiver; private ScreenOffReceiver screenOffReceiver; private AppLockListChangedReceiver appLockListChangedReceiver; private String protected_packname; private List<String> protected_list; private Intent intent; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { tmpStopReceiver = new TmpStopReceiver(); registerReceiver(tmpStopReceiver, new IntentFilter("com.zjw.mobilesafe.tmpstop")); screenOffReceiver = new ScreenOffReceiver(); registerReceiver(screenOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); appLockListChangedReceiver = new AppLockListChangedReceiver(); registerReceiver(appLockListChangedReceiver, new IntentFilter("com.zjw.mobilesafe.appLockListChanged")); am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); dao = new AppLockDao(this); flag = true; protected_list = dao.findAll();//Õâ¸ölistÊÇ»áÓб仯µÄ£¬Òò´ËÐèÒªÓÐÒ»¸ö¹ã²¥À´¸üиÃlist intent = new Intent(getApplicationContext(), InputPwdActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //»ñÈ¡×îнø³Ì£¬´Ë·½·¨×ÜÊÇ°Ñ×îнø³Ì·ÅÔÚµÚһλ //¼´£ºÈçºÎ»ñÈ¡Óû§µ±Ç°ÕýÔÚʹÓõÄactivity new Thread(new Runnable() { @Override public void run() { while(flag){ List<RunningTaskInfo> runningTasks = am.getRunningTasks(1);//ÓÅ»¯1£¬½«»ñÈ¡Êý´Ó100¸ÄΪ1 String packageName = runningTasks.get(0).topActivity.getPackageName(); System.out.println("packagename:"+packageName);//ÓÅ»¯2£¬×¢Ê͵ô´ËÐдúÂë // if (dao.find(packageName)) {//ÓÅ»¯3£º²éѯÊý¾Ý¿â if(protected_list.contains(packageName)){ if (packageName.equals(protected_packname)) { //´Ëʱ²»ÐèÒª±£»¤£¬Ê²Ã´ÊÂÒ²²»×ö }else { //ÓÅ»¯4£º½«¿ªÆôÃÜÂëactivityµÄÒâͼ¶¨Òåµ½ÍâÃæÈ¥ intent.putExtra("packname", packageName); startActivity(intent); } } try { //ÕâÊÇÒ»¶¨ÒªÐ´µÄ£¬²»È»Ì«¿ì Thread.sleep(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); super.onCreate(); } /** * ÄÚ²¿Àࣺ¹ã²¥½ÓÊÜÕߣ¬½ÓÊÕÔÝʱֹͣ¿´ÃŹ·¼à¿ØÖ¸¶¨°üÃûµÄ¹ã²¥ */ private class TmpStopReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { protected_packname = intent.getStringExtra("packname"); } } /** * ¹ã²¥½ÓÊÕÕߣ¬½ÓÊÜËøÆÁ¹ã²¥ */ private class ScreenOffReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { System.out.println("ËøÆÁÁË"); protected_packname = null; } } /** * ¹ã²¥½ÓÊÕÕߣ¬½ÓÊÕÊý¾Ý¿â·¢Éú±ä»¯µÄ¹ã²¥ */ private class AppLockListChangedReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { protected_list = dao.findAll(); } } @Override public void onDestroy() { flag = false; unregisterReceiver(tmpStopReceiver); tmpStopReceiver = null; unregisterReceiver(screenOffReceiver); screenOffReceiver = null; unregisterReceiver(appLockListChangedReceiver); appLockListChangedReceiver = null; super.onDestroy(); } }
jj4856951/MobileSafe
src/com/zjw/mobilesafe/service/WatchdogService.java
Java
apache-2.0
3,769