text
stringlengths
7
1.01M
/** * Ed-Fi Operational Data Store API * The Ed-Fi ODS / API enables applications to read and write education data stored in an Ed-Fi ODS through a secure REST interface. The Ed-Fi ODS / API supports both transactional and bulk modes of operation. *** > *Note: Consumers of ODS / API information should sanitize all data for display and storage. The ODS / API provides reasonable safeguards against cross-site scripting attacks and other malicious content, but the platform does not and cannot guarantee that the data it contains is free of all potentially harmful content.* *** * * OpenAPI spec version: 3 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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.edfi.model.resource; import java.util.Objects; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * TpdmSectionCourseTranscriptFactsAggregatedFinalLetterGradeEarned */ @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2020-06-09T12:36:29.493-07:00") public class TpdmSectionCourseTranscriptFactsAggregatedFinalLetterGradeEarned { @SerializedName("finalLetterGrade") private String finalLetterGrade = null; @SerializedName("letterGradeTypeNumber") private Integer letterGradeTypeNumber = null; @SerializedName("letterGradeTypePercentage") private Double letterGradeTypePercentage = null; public TpdmSectionCourseTranscriptFactsAggregatedFinalLetterGradeEarned finalLetterGrade(String finalLetterGrade) { this.finalLetterGrade = finalLetterGrade; return this; } /** * The final indicator of student performance in a class as submitted by the instructor. * @return finalLetterGrade **/ @ApiModelProperty(example = "null", required = true, value = "The final indicator of student performance in a class as submitted by the instructor.") public String getFinalLetterGrade() { return finalLetterGrade; } public void setFinalLetterGrade(String finalLetterGrade) { this.finalLetterGrade = finalLetterGrade; } public TpdmSectionCourseTranscriptFactsAggregatedFinalLetterGradeEarned letterGradeTypeNumber(Integer letterGradeTypeNumber) { this.letterGradeTypeNumber = letterGradeTypeNumber; return this; } /** * The number of students receiving a letter grade by letter grade type * @return letterGradeTypeNumber **/ @ApiModelProperty(example = "null", value = "The number of students receiving a letter grade by letter grade type") public Integer getLetterGradeTypeNumber() { return letterGradeTypeNumber; } public void setLetterGradeTypeNumber(Integer letterGradeTypeNumber) { this.letterGradeTypeNumber = letterGradeTypeNumber; } public TpdmSectionCourseTranscriptFactsAggregatedFinalLetterGradeEarned letterGradeTypePercentage(Double letterGradeTypePercentage) { this.letterGradeTypePercentage = letterGradeTypePercentage; return this; } /** * The percentage of students receiving a letter grade by type. * @return letterGradeTypePercentage **/ @ApiModelProperty(example = "null", value = "The percentage of students receiving a letter grade by type.") public Double getLetterGradeTypePercentage() { return letterGradeTypePercentage; } public void setLetterGradeTypePercentage(Double letterGradeTypePercentage) { this.letterGradeTypePercentage = letterGradeTypePercentage; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TpdmSectionCourseTranscriptFactsAggregatedFinalLetterGradeEarned tpdmSectionCourseTranscriptFactsAggregatedFinalLetterGradeEarned = (TpdmSectionCourseTranscriptFactsAggregatedFinalLetterGradeEarned) o; return Objects.equals(this.finalLetterGrade, tpdmSectionCourseTranscriptFactsAggregatedFinalLetterGradeEarned.finalLetterGrade) && Objects.equals(this.letterGradeTypeNumber, tpdmSectionCourseTranscriptFactsAggregatedFinalLetterGradeEarned.letterGradeTypeNumber) && Objects.equals(this.letterGradeTypePercentage, tpdmSectionCourseTranscriptFactsAggregatedFinalLetterGradeEarned.letterGradeTypePercentage); } @Override public int hashCode() { return Objects.hash(finalLetterGrade, letterGradeTypeNumber, letterGradeTypePercentage); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class TpdmSectionCourseTranscriptFactsAggregatedFinalLetterGradeEarned {\n"); sb.append(" finalLetterGrade: ").append(toIndentedString(finalLetterGrade)).append("\n"); sb.append(" letterGradeTypeNumber: ").append(toIndentedString(letterGradeTypeNumber)).append("\n"); sb.append(" letterGradeTypePercentage: ").append(toIndentedString(letterGradeTypePercentage)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package eu.monnetproject.morph; import eu.monnetproject.pos.POSToken; import java.util.List; /** * Models a compound word splitter * * @author John McCrae */ public interface CompoundSplitter { /** * Split a word. * @param token The pos-tagged token * @return The result */ List<StemmerResult> split(POSToken token); }
/* * 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.shardingsphere.sharding.route.spi; import org.apache.shardingsphere.spi.NewInstanceServiceLoader; import java.util.Collection; import java.util.Date; /** * Time service for SPI. */ public final class SPITimeService implements TimeService { private final Collection<TimeService> timeServices = NewInstanceServiceLoader.newServiceInstances(TimeService.class); static { NewInstanceServiceLoader.register(TimeService.class); } @Override public Date getTime() { Date result = null; for (TimeService server : timeServices) { result = server.getTime(); if (!(server instanceof DefaultTimeService) && null != result) { return result; } } return result; } }
/* * Copyright 2009-2012 Amazon Technologies, 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://aws.amazon.com/apache2.0 * * 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.eclipse.ec2.utils; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuCreator; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Menu; import com.amazonaws.eclipse.ec2.Ec2Plugin; import com.amazonaws.eclipse.ec2.utils.IMenu.MenuItem; /** * Action class to create static Menu objects */ public class MenuAction extends Action implements IMenuCreator { /** Holds MenuHandler object to process the menus */ private MenuHandler menuHandler; /** Menu that gets displayed */ protected Menu menu; /** * Constructor * * @param text * Text that gets displayed on the Menu * @param toolTip * Tooltip that gets displayed for the menu * @param imageDescriptor * The icon used for the menu * @param menuHandler * The MenuHandler object used to manage actions */ public MenuAction(String text, String toolTip, String imageDescriptor, MenuHandler menuHandler) { setText(text); setToolTipText(toolTip); setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor(imageDescriptor)); this.menuHandler = menuHandler; setMenuCreator(this); } /** * @see org.eclipse.jface.action.IMenuCreator#getMenu(Menu) */ @Override public Menu getMenu(Menu parent) { return menu; } /** * @see org.eclipse.jface.action.IMenuCreator#getMenu(Control) */ @Override public Menu getMenu(Control parent) { if (menu != null) { return menu; } return constructMenu(parent); } /** * Creates the menu dynamically * * @param parent * Composite on which the menu is drawn * * @return The created menu */ protected Menu constructMenu(Control parent) { menu = new Menu(parent); for (final MenuItem menuItem : menuHandler.getMenuItems()) { if (menuItem.equals(MenuItem.SEPARATOR)) { new org.eclipse.swt.widgets.MenuItem(menu, SWT.SEPARATOR); } else { IAction action = new Action(menuItem.getMenuText(), AS_RADIO_BUTTON) { @Override public void run() { if (isChecked()) { menuHandler.setCurrentSelection(menuItem); } } }; addActionToMenu(action); // Every Time new object is created, so getMenuId is used for // determining the current selection action.setChecked(menuHandler.getCurrentSelection().getMenuId().equals(menuItem.getMenuId())); } } return menu; } /** * Use to add different MenuItems to the menu * * @param action * The Action to be added */ protected void addActionToMenu(IAction action) { ActionContributionItem item = new ActionContributionItem(action); item.fill(menu, -1); } /** * @see org.eclipse.jface.action.IMenuCreator#dispose() */ @Override public void dispose() { if (menu != null) { menu.dispose(); } } /** * Used to popup the menu * * @see org.eclipse.jface.action.Action#run() */ @Override public void run() { if (menu != null) menu.setVisible(true); } }
/******************************************************************************* * Copyright 2020-2022 Zebrunner Inc (https://www.zebrunner.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.qaprosoft.carina.core.foundation.listeners; import java.io.File; import java.lang.invoke.MethodHandles; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Category; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.openqa.selenium.Capabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.events.EventFiringWebDriver; import org.testng.Assert; import org.testng.IClassListener; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ITestClass; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.SkipException; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.azure.storage.blob.models.BlobProperties; import com.qaprosoft.amazon.AmazonS3Manager; import com.qaprosoft.appcenter.AppCenterManager; import com.qaprosoft.azure.AzureManager; import com.qaprosoft.carina.browsermobproxy.ProxyPool; import com.qaprosoft.carina.core.foundation.commons.SpecialKeywords; import com.qaprosoft.carina.core.foundation.report.ReportContext; import com.qaprosoft.carina.core.foundation.report.TestResultItem; import com.qaprosoft.carina.core.foundation.report.TestResultType; import com.qaprosoft.carina.core.foundation.report.email.EmailReportGenerator; import com.qaprosoft.carina.core.foundation.report.email.EmailReportItemCollector; import com.qaprosoft.carina.core.foundation.report.qtest.IQTestManager; import com.qaprosoft.carina.core.foundation.report.testrail.ITestRailManager; import com.qaprosoft.carina.core.foundation.skip.ExpectedSkipManager; import com.qaprosoft.carina.core.foundation.utils.Configuration; import com.qaprosoft.carina.core.foundation.utils.Configuration.Parameter; import com.qaprosoft.carina.core.foundation.utils.DateUtils; import com.qaprosoft.carina.core.foundation.utils.FileManager; import com.qaprosoft.carina.core.foundation.utils.Messager; import com.qaprosoft.carina.core.foundation.utils.R; import com.qaprosoft.carina.core.foundation.utils.ZebrunnerNameResolver; import com.qaprosoft.carina.core.foundation.utils.ownership.Ownership; import com.qaprosoft.carina.core.foundation.utils.resources.L10N; import com.qaprosoft.carina.core.foundation.utils.tag.PriorityManager; import com.qaprosoft.carina.core.foundation.utils.tag.TagManager; import com.qaprosoft.carina.core.foundation.webdriver.CarinaDriver; import com.qaprosoft.carina.core.foundation.webdriver.IDriverPool; import com.qaprosoft.carina.core.foundation.webdriver.Screenshot; import com.qaprosoft.carina.core.foundation.webdriver.TestPhase; import com.qaprosoft.carina.core.foundation.webdriver.TestPhase.Phase; import com.qaprosoft.carina.core.foundation.webdriver.core.capability.CapabilitiesLoader; import com.qaprosoft.carina.core.foundation.webdriver.device.Device; import com.qaprosoft.carina.core.foundation.webdriver.screenshot.AutoScreenshotRule; import com.qaprosoft.carina.core.foundation.webdriver.screenshot.IScreenshotRule; import com.zebrunner.agent.core.registrar.Artifact; import com.zebrunner.agent.core.registrar.CurrentTest; import com.zebrunner.agent.core.registrar.CurrentTestRun; import com.zebrunner.agent.core.registrar.Label; import com.zebrunner.agent.core.registrar.TestRail; import com.zebrunner.agent.core.registrar.label.CompositeLabelResolver; import com.zebrunner.agent.core.registrar.maintainer.ChainedMaintainerResolver; import com.zebrunner.agent.core.webdriver.RemoteWebDriverFactory; import com.zebrunner.agent.testng.core.testname.TestNameResolverRegistry; /* * CarinaListener - base carina-core TestNG Listener. * * @author Vadim Delendik */ public class CarinaListener extends AbstractTestListener implements ISuiteListener, IQTestManager, ITestRailManager, IClassListener { private static final Logger LOGGER = Logger.getLogger(MethodHandles.lookup().lookupClass()); protected static final long EXPLICIT_TIMEOUT = Configuration.getLong(Parameter.EXPLICIT_TIMEOUT); protected static final String SUITE_TITLE = "%s%s%s - %s (%s%s)"; protected static final String XML_SUITE_NAME = " (%s)"; protected static boolean automaticDriversCleanup = true; protected boolean isRunLabelsRegistered = false; public CarinaListener(){ // Add shutdown hook Runtime.getRuntime().addShutdownHook(new ShutdownHook()); // Zebrunner core java agent is user for capturing events of RemoteDriverSession instances. // Internally, the agent uses java instrumentation agent for its purposes. // The instrumentation agent implicitly triggers initialization of the R class because it uses logger. // Carina has the ThreadLogAppender class which is closely related to logging and internally uses the R class. // Technically, this happen when the maven-surefire-plugin has not set inherited program arguments (passed to mvn process). // That is why it is necessary to reinit R class here when TestNG loads the CarinaListener class. R.reinit(); // Set log4j properties URL log4jUrl = ClassLoader.getSystemResource("carina-log4j.properties"); LOGGER.debug("carina-log4j.properties: " + log4jUrl); PropertyConfigurator.configure(log4jUrl); LOGGER.info(Configuration.asString()); // Configuration.validateConfiguration(); try { L10N.load(); } catch (Exception e) { LOGGER.error("L10N bundle is not initialized successfully!", e); } // declare global capabilities in configuration if custom_capabilities is declared String customCapabilities = Configuration.get(Parameter.CUSTOM_CAPABILITIES); if (!customCapabilities.isEmpty()) { // redefine core CONFIG properties using global custom capabilities file new CapabilitiesLoader().loadCapabilities(customCapabilities); } // declare global capabilities from Zebrunner Launcher if any Capabilities zebrunnerCapabilities = RemoteWebDriverFactory.getCapabilities(); if (!zebrunnerCapabilities.asMap().isEmpty()) { // redefine core CONFIG properties using caps from Zebrunner launchers new CapabilitiesLoader().loadCapabilities(zebrunnerCapabilities); } IScreenshotRule autoScreenshotsRule = (IScreenshotRule) new AutoScreenshotRule(); Screenshot.addScreenshotRule(autoScreenshotsRule); updateAppPath(); TestNameResolverRegistry.set(new ZebrunnerNameResolver()); CompositeLabelResolver.addResolver(new TagManager()); CompositeLabelResolver.addResolver(new PriorityManager()); ReportContext.getBaseDir(); // create directory for logging as soon as possible } @Override public void onStart(ISuite suite) { LOGGER.debug("CarinaListener->onStart(ISuite suite)"); // first means that ownership/maintainer resolver from carina has higher priority ChainedMaintainerResolver.addFirst(new Ownership(suite.getParameter("suiteOwner"))); List<String> coreLogPackages = new ArrayList<String>( Arrays.asList(Configuration.get(Parameter.CORE_LOG_PACKAGES).split(","))); if (coreLogPackages.size() > 0 && !"INFO".equalsIgnoreCase(Configuration.get(Parameter.CORE_LOG_LEVEL))) { // do core log level change only if custom properties are declared try { Logger root = Logger.getRootLogger(); Enumeration<?> allLoggers = root.getLoggerRepository().getCurrentCategories(); while (allLoggers.hasMoreElements()) { Category tmpLogger = (Category) allLoggers.nextElement(); // LOGGER.debug("loggerName: " + tmpLogger.getName()); for (String coreLogPackage : coreLogPackages) { if (tmpLogger.getName().contains(coreLogPackage.trim())) { LOGGER.info("Updaged logger level for '" + tmpLogger.getName() + "' to " + Configuration.get(Parameter.CORE_LOG_LEVEL)); tmpLogger.setLevel(Level.toLevel(Configuration.get(Parameter.CORE_LOG_LEVEL))); } } } } catch (NoSuchMethodError e) { LOGGER.error("Unable to redefine logger level due to the conflicts between log4j and slf4j!"); } } setThreadCount(suite); onHealthCheck(suite); if (Configuration.getPlatform().equalsIgnoreCase(SpecialKeywords.API)) { CurrentTestRun.setPlatform(SpecialKeywords.API); } String mobileApp = Configuration.getMobileApp(); if (!mobileApp.isEmpty()) { // [VD] do not move into the static block as Zebrunner reporting need registered test run! Artifact.attachReferenceToTestRun("app", mobileApp); } // register app_version/build as artifact if available... Configuration.setBuild(Configuration.get(Parameter.APP_VERSION)); String branch = Configuration.get(Parameter.GIT_BRANCH); if (!branch.isEmpty()) { Label.attachToTestRun("branch", branch); } String sha1 = Configuration.get(Parameter.GIT_COMMIT); if (!sha1.isEmpty()) { Label.attachToTestRun("sha1", sha1); } /* * To support multi-suite declaration as below we have to init test run labels at once only! * <suite-files> * <suite-file path="suite1.xml"/> * <suite-file path="suite2.xml"/> * </suite-files> */ if (!this.isRunLabelsRegistered) { attachTestRunLabels(suite); this.isRunLabelsRegistered = true; } LOGGER.info("CARINA_CORE_VERSION: " + getCarinaVersion()); } @Override public void onStart(ITestContext context) { LOGGER.debug("CarinaListener->OnTestStart(ITestContext context): " + context.getName()); super.onStart(context); } @Override public void beforeConfiguration(ITestResult result) { LOGGER.debug("CarinaListener->beforeConfiguration"); super.beforeConfiguration(result); // remember active test phase to organize valid driver pool manipulation // process if (result.getMethod().isBeforeSuiteConfiguration()) { TestPhase.setActivePhase(Phase.BEFORE_SUITE); } if(result.getMethod().isBeforeTestConfiguration()){ TestPhase.setActivePhase(Phase.BEFORE_TEST); } if (result.getMethod().isBeforeClassConfiguration()) { TestPhase.setActivePhase(Phase.BEFORE_CLASS); } if (result.getMethod().isBeforeMethodConfiguration()) { TestPhase.setActivePhase(Phase.BEFORE_METHOD); } if (result.getMethod().isAfterMethodConfiguration()) { TestPhase.setActivePhase(Phase.AFTER_METHOD); } if (result.getMethod().isAfterClassConfiguration()) { TestPhase.setActivePhase(Phase.AFTER_CLASS); } if (result.getMethod().isAfterTestConfiguration()){ TestPhase.setActivePhase(Phase.AFTER_TEST); } if (result.getMethod().isAfterSuiteConfiguration()) { TestPhase.setActivePhase(Phase.AFTER_SUITE); } } @Override public void onConfigurationFailure(ITestResult result) { LOGGER.debug("CarinaListener->onConfigurationFailure"); super.onConfigurationFailure(result); } @Override public void onTestStart(ITestResult result) { LOGGER.debug("CarinaListener->onTestStart"); TestPhase.setActivePhase(Phase.METHOD); // handle expected skip Method testMethod = result.getMethod().getConstructorOrMethod().getMethod(); if (ExpectedSkipManager.getInstance().isSkip(testMethod, result.getTestContext())) { skipExecution("Based on rule listed above"); } super.onTestStart(result); } @Override public void onTestSuccess(ITestResult result) { LOGGER.debug("CarinaListener->onTestSuccess"); onTestFinish(result); super.onTestSuccess(result); } @Override public void onTestFailure(ITestResult result) { LOGGER.debug("CarinaListener->onTestFailure"); String errorMessage = getFailureReason(result); takeScreenshot("TEST FAILED - " + errorMessage); onTestFinish(result); super.onTestFailure(result); } @Override public void onTestSkipped(ITestResult result) { LOGGER.debug("CarinaListener->onTestSkipped"); String errorMessage = getFailureReason(result); takeScreenshot("TEST SKIPPED - " + errorMessage, false); onTestFinish(result); super.onTestSkipped(result); } private boolean hasDependencies(ITestResult result) { String methodName = result.getMethod().getMethodName(); String className = result.getMethod().getTestClass().getName(); // analyze all suite methods and return true if any of them depends on // existing method List<ITestNGMethod> methods = result.getTestContext().getSuite().getAllMethods(); for (ITestNGMethod method : methods) { List<String> dependencies = Arrays.asList(method.getMethodsDependedUpon()); if (dependencies.contains(methodName) || dependencies.contains(className + "." + methodName)) { LOGGER.debug("dependency detected for " + methodName); return true; } } return false; } private void onTestFinish(ITestResult result) { try { // clear all kind of temporary properties R.CONFIG.clearTestProperties(); R.TESTDATA.clearTestProperties(); R.DATABASE.clearTestProperties(); R.EMAIL.clearTestProperties(); R.REPORT.clearTestProperties(); R.ZAFIRA.clearTestProperties(); LOGGER.debug("Test result is : " + result.getStatus()); // result status == 2 means failure, status == 3 means skip. We need to quit driver anyway for failure and skip if ((automaticDriversCleanup && !hasDependencies(result)) || result.getStatus() == 2 || result.getStatus() == 3) { if (!Configuration.getBoolean(Parameter.FORCIBLY_DISABLE_DRIVER_QUIT)) { quitDrivers(Phase.BEFORE_METHOD, Phase.METHOD); } } attachTestLabels(result); } catch (Exception e) { LOGGER.error("Exception in CarinaListener->onTestFinish!", e); } } @Override public void onAfterClass(ITestClass testClass){ LOGGER.debug("CarinaListener->onAfterClass(ITestClass testClass)"); quitDrivers(Phase.BEFORE_CLASS); } @Override public void onFinish(ITestContext context) { LOGGER.debug("CarinaListener->onFinish(ITestContext context)"); super.onFinish(context); // [SZ] it's still needed to close driver from BeforeClass stage. // Otherwise it could be potentially used in other test classes // quitDrivers(Phase.BEFORE_CLASS); already exited in onAfterClass() method quitDrivers(Phase.BEFORE_TEST); LOGGER.debug("CarinaListener->onFinish(context): " + context.getName()); } @Override public void onFinish(ISuite suite) { LOGGER.debug("CarinaListener->onFinish(ISuite suite)"); try { // TODO: quitAllDivers forcibly ReportContext.removeTempDir(); // clean temp artifacts directory // HtmlReportGenerator.generate(ReportContext.getBaseDir().getAbsolutePath()); String browser = getBrowser(); String deviceName = getFullDeviceName(); // String suiteName = getSuiteName(context); String title = getTitle(suite.getXmlSuite()); TestResultType testResult = EmailReportGenerator.getSuiteResult(EmailReportItemCollector.getTestResults()); String status = testResult.getName(); title = status + ": " + title; String env = ""; if (!Configuration.isNull(Parameter.ENV)) { env = Configuration.get(Parameter.ENV); } if (!Configuration.get(Parameter.URL).isEmpty()) { env += " - <a href='" + Configuration.get(Parameter.URL) + "'>" + Configuration.get(Parameter.URL) + "</a>"; } ReportContext.getTempDir().delete(); // EmailReportItemCollector.getTestResults()); LOGGER.debug("Generating email report..."); // Generate emailable html report using regular method EmailReportGenerator report = new EmailReportGenerator(title, env, Configuration.get(Parameter.APP_VERSION), deviceName, browser, DateUtils.now(), EmailReportItemCollector.getTestResults(), EmailReportItemCollector.getCreatedItems()); String emailContent = report.getEmailBody(); // Store emailable report under emailable-report.html ReportContext.generateHtmlReport(emailContent); printExecutionSummary(EmailReportItemCollector.getTestResults()); ReportContext.setCustomTestDirName("run_summary"); TestResultType suiteResult = EmailReportGenerator.getSuiteResult(EmailReportItemCollector.getTestResults()); switch (suiteResult) { case SKIP_ALL: Assert.fail("All tests were skipped! Analyze logs to determine possible configuration issues."); break; case SKIP_ALL_ALREADY_PASSED: LOGGER.info( "Nothing was executed in rerun mode because all tests already passed and registered in Zafira Repoting Service!"); break; default: // do nothing } LOGGER.debug("Finish email report generation."); } catch (Exception e) { LOGGER.error("Exception in CarinaListener->onFinish(ISuite suite)", e); } } /** * Disable automatic drivers cleanup after each TestMethod and switch to controlled by tests itself. * But anyway all drivers will be closed forcibly as only suite is finished or aborted */ public static void disableDriversCleanup() { automaticDriversCleanup = false; } // TODO: remove this private method private String getFullDeviceName() { String deviceName = "Desktop"; if (!IDriverPool.getDefaultDevice().isNull()) { // Samsung - Android 4.4.2; iPhone - iOS 7 Device device = IDriverPool.getDefaultDevice(); String deviceTemplate = "%s - %s %s"; deviceName = String.format(deviceTemplate, device.getName(), device.getOs(), device.getOsVersion()); } return deviceName; } protected String getBrowser() { return Configuration.getBrowser(); } protected String getTitle(XmlSuite suite) { String browser = getBrowser(); if (!browser.isEmpty()) { browser = " " + browser; // insert the space before } String device = getFullDeviceName(); String env = !Configuration.isNull(Parameter.ENV) ? Configuration.get(Parameter.ENV) : Configuration.get(Parameter.URL); String title = ""; String app_version = ""; if (!Configuration.get(Parameter.APP_VERSION).isEmpty()) { // if nothing is specified then title will contain nothing app_version = Configuration.get(Parameter.APP_VERSION) + " - "; } String suiteName = getSuiteName(suite); String xmlFile = getSuiteFileName(suite); title = String.format(SUITE_TITLE, app_version, suiteName, String.format(XML_SUITE_NAME, xmlFile), env, device, browser); return title; } private String getSuiteFileName(XmlSuite suite) { // TODO: investigate why we need such method and suite file name at all String fileName = suite.getFileName(); if (fileName == null) { fileName = "undefined"; } LOGGER.debug("Full suite file name: " + fileName); if (fileName.contains("\\")) { fileName = fileName.replaceAll("\\\\", "/"); } fileName = StringUtils.substringAfterLast(fileName, "/"); LOGGER.debug("Short suite file name: " + fileName); return fileName; } protected String getSuiteName(XmlSuite suite) { String suiteName = ""; if (suite != null && !"Default suite".equals(suite.getName())) { suiteName = Configuration.get(Parameter.SUITE_NAME).isEmpty() ? suite.getName() : Configuration.get(Parameter.SUITE_NAME); } else { suiteName = Configuration.get(Parameter.SUITE_NAME).isEmpty() ? R.EMAIL.get("title") : Configuration.get(Parameter.SUITE_NAME); } return suiteName; } private void printExecutionSummary(List<TestResultItem> tris) { Messager.INFORMATION.info("**************** Test execution summary ****************"); int num = 1; for (TestResultItem tri : tris) { String failReason = tri.getFailReason(); if (failReason == null) { failReason = ""; } if (!tri.isConfig()) { String reportLinks = !StringUtils.isEmpty(tri.getLinkToScreenshots()) ? "screenshots=" + tri.getLinkToScreenshots() + " | " : ""; reportLinks += !StringUtils.isEmpty(tri.getLinkToLog()) ? "log=" + tri.getLinkToLog() : ""; Messager.TEST_RESULT.info(String.valueOf(num++), tri.getTest(), tri.getResult().toString(), reportLinks); } } } protected void putS3Artifact(String key, String path) { AmazonS3Manager.getInstance().put(Configuration.get(Parameter.S3_BUCKET_NAME), key, path); } protected S3Object getS3Artifact(String bucket, String key) { return AmazonS3Manager.getInstance().get(Configuration.get(Parameter.S3_BUCKET_NAME), key); } protected S3Object getS3Artifact(String key) { return getS3Artifact(Configuration.get(Parameter.S3_BUCKET_NAME), key); } protected void putAzureArtifact(String remotePath, String localPath) { AzureManager.getInstance().put(Configuration.get(Parameter.AZURE_CONTAINER_NAME), remotePath, localPath); } protected void getAzureArtifact(String bucket, String remotePath, File localPath) { AzureManager.getInstance().download(bucket, remotePath, localPath); } private static void updateAppPath() { if (!Configuration.get(Parameter.AZURE_ACCESS_KEY_TOKEN).isEmpty()) { updateAzureAppPath(); } if (!Configuration.get(Parameter.APPCENTER_TOKEN).isEmpty()) { updateAppCenterAppPath(); } // AWS S3 is preferable and has higher priority if (!Configuration.get(Parameter.ACCESS_KEY_ID).isEmpty()) { updateS3AppPath(); } } /** * Method to update MOBILE_APP path in case if apk is located in Hockey App. */ private static void updateAppCenterAppPath() { // appcenter://appName/platformName/buildType/version Pattern APPCENTER_PATTERN = Pattern.compile( "appcenter:\\/\\/([a-zA-Z-0-9][^\\/]*)\\/([a-zA-Z-0-9][^\\/]*)\\/([a-zA-Z-0-9][^\\/]*)\\/([a-zA-Z-0-9][^\\/]*)"); String mobileAppPath = Configuration.getMobileApp(); Matcher matcher = APPCENTER_PATTERN.matcher(mobileAppPath); LOGGER.info("Analyzing if mobile_app is located on AppCenter..."); if (matcher.find()) { LOGGER.info("app artifact is located on AppCenter..."); String appName = matcher.group(1); String platformName = matcher.group(2); String buildType = matcher.group(3); String version = matcher.group(4); //TODO: test if generated appcenter download url is valid String presignedAppUrl = AppCenterManager.getInstance().getDownloadUrl(appName, platformName, buildType, version); Configuration.setMobileApp(presignedAppUrl); } } /** * Method to update MOBILE_APP path in case if apk is located in s3 bucket. */ private static void updateS3AppPath() { Pattern S3_BUCKET_PATTERN = Pattern.compile("s3:\\/\\/([a-zA-Z-0-9][^\\/]*)\\/(.*)"); // get app path to be sure that we need(do not need) to download app // from s3 bucket String mobileAppPath = Configuration.getMobileApp(); Matcher matcher = S3_BUCKET_PATTERN.matcher(mobileAppPath); LOGGER.info("Analyzing if mobile app is located on S3..."); if (matcher.find()) { LOGGER.info("app artifact is located on s3..."); String bucketName = matcher.group(1); String key = matcher.group(2); Pattern pattern = Pattern.compile(key); // analyze if we have any pattern inside mobile_app to make extra // search in AWS int position = key.indexOf(".*"); if (position > 0) { // /android/develop/dfgdfg.*/Mapmyrun.apk int slashPosition = key.substring(0, position).lastIndexOf("/"); if (slashPosition > 0) { key = key.substring(0, slashPosition); S3ObjectSummary lastBuild = AmazonS3Manager.getInstance().getLatestBuildArtifact(bucketName, key, pattern); key = lastBuild.getKey(); } } else { key = AmazonS3Manager.getInstance().get(bucketName, key).getKey(); } LOGGER.info("next s3 app key will be used: " + key); // generate presign url explicitly to register link as run artifact long hours = 72L*1000*60*60; // generate presigned url for nearest 3 days String presignedAppUrl = AmazonS3Manager.getInstance().generatePreSignUrl(bucketName, key, hours).toString(); Configuration.setMobileApp(presignedAppUrl); } } /** * Method to update MOBILE_APP path in case if apk is located in Azure storage. */ private static void updateAzureAppPath() { Pattern AZURE_CONTAINER_PATTERN = Pattern.compile("\\/\\/([a-z0-9]{3,24})\\.blob.core.windows.net\\/(?:(\\$root|(?:[a-z0-9](?!.*--)[a-z0-9-]{1,61}[a-z0-9]))\\/)?(.{1,1024})"); String mobileAppPath = Configuration.getMobileApp(); Matcher matcher = AZURE_CONTAINER_PATTERN.matcher(mobileAppPath); LOGGER.info("Analyzing if mobile app is located on Azure..."); if (matcher.find()) { LOGGER.info("app artifact is located on Azure..."); String accountName = matcher.group(1); String containerName = matcher.group(2) == null ? "$root" : matcher.group(2); String remoteFilePath = matcher.group(3); LOGGER.info( "Account: " + accountName + "\n" + "Container: " + containerName + "\n" + "RemotePath: " + remoteFilePath + "\n" ); R.CONFIG.put(Parameter.AZURE_ACCOUNT_NAME.getKey(), accountName); BlobProperties blobProperties = AzureManager.getInstance().get(containerName, remoteFilePath); String azureLocalStorage = Configuration.get(Parameter.AZURE_LOCAL_STORAGE); String localFilePath = azureLocalStorage + File.separator + StringUtils.substringAfterLast(remoteFilePath, "/"); File file = new File(localFilePath); try { // verify requested artifact by checking the checksum if (file.exists() && FileManager.getFileChecksum(FileManager.Checksum.MD5, file).equals(Base64.encodeBase64String(blobProperties.getContentMd5()))) { LOGGER.info("build artifact with the same checksum already downloaded: " + file.getAbsolutePath()); } else { LOGGER.info( String.format("Following data was extracted: container: %s, remotePath: %s, local file: %s", containerName, remoteFilePath, file.getAbsolutePath()) ); AzureManager.getInstance().download(containerName, remoteFilePath, file); } } catch (Exception exception) { LOGGER.error("Azure app path update exception detected!", exception); } Configuration.setMobileApp(file.getAbsolutePath()); // try to redefine app_version if it's value is latest or empty String appVersion = Configuration.get(Parameter.APP_VERSION); if (appVersion.equals("latest") || appVersion.isEmpty()) { Configuration.setBuild(file.getName()); } } } protected void skipExecution(String message) { CurrentTest.revertRegistration(); throw new SkipException(message); } protected void onHealthCheck(ISuite suite) { String healthCheckClass = Configuration.get(Parameter.HEALTH_CHECK_CLASS); if (suite.getParameter(Parameter.HEALTH_CHECK_CLASS.getKey()) != null) { // redefine by suite arguments as they have higher priority healthCheckClass = suite.getParameter(Parameter.HEALTH_CHECK_CLASS.getKey()); } String healthCheckMethods = Configuration.get(Parameter.HEALTH_CHECK_METHODS); if (suite.getParameter(Parameter.HEALTH_CHECK_METHODS.getKey()) != null) { // redefine by suite arguments as they have higher priority healthCheckMethods = suite.getParameter(Parameter.HEALTH_CHECK_METHODS.getKey()); } String[] healthCheckMethodsArray = null; if (!healthCheckMethods.isEmpty()) { healthCheckMethodsArray = healthCheckMethods.split(","); } checkHealth(suite, healthCheckClass, healthCheckMethodsArray); } private void checkHealth(ISuite suite, String className, String[] methods) { if (className.isEmpty()) { return; } // create runtime XML suite for health check XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setName("HealthCheck XmlSuite - " + className); XmlTest xmlTest = new XmlTest(xmlSuite); xmlTest.setName("HealthCheck TestCase"); XmlClass xmlHealthCheckClass = new XmlClass(); xmlHealthCheckClass.setName(className); // TestNG do not execute missed methods so we have to calulate expected // methods count to handle potential mistakes in methods naming int expectedMethodsCount = -1; if (methods != null) { // declare particular methods if they are provided List<XmlInclude> methodsToRun = constructIncludes(methods); expectedMethodsCount = methodsToRun.size(); xmlHealthCheckClass.setIncludedMethods(methodsToRun); } xmlTest.setXmlClasses(Arrays.asList(new XmlClass[] { xmlHealthCheckClass })); xmlSuite.setTests(Arrays.asList(new XmlTest[] { xmlTest })); LOGGER.info("HealthCheck '" + className + "' is started."); LOGGER.debug("HealthCheck suite content:" + xmlSuite.toXml()); // Second TestNG process to run HealthCheck TestNG testng = new TestNG(); testng.setXmlSuites(Arrays.asList(xmlSuite)); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); testng.run(); synchronized (this) { boolean passed = false; if (expectedMethodsCount == -1) { if (tla.getPassedTests().size() > 0 && tla.getFailedTests().size() == 0 && tla.getSkippedTests().size() == 0) { passed = true; } } else { LOGGER.info("Expected passed tests count: " + expectedMethodsCount); if (tla.getPassedTests().size() == expectedMethodsCount && tla.getFailedTests().size() == 0 && tla.getSkippedTests().size() == 0) { passed = true; } } if (passed) { LOGGER.info("HealthCheck suite '" + className + "' is finished successfully."); } else { throw new SkipException("Skip test(s) due to health check failures for '" + className + "'"); } } } private List<XmlInclude> constructIncludes(String... methodNames) { List<XmlInclude> includes = new ArrayList<XmlInclude>(); for (String eachMethod : methodNames) { includes.add(new XmlInclude(eachMethod)); } return includes; } /* * Parse TestNG <suite ...> tag and return any attribute * @param ISuite suite * @param IString attribute * @return String attribute value or empty string * */ private String getAttributeValue(ISuite suite, String attribute) { String res = ""; if (suite.getXmlSuite() == null || suite.getXmlSuite().getFileName() == null) { // #1514 Unable to execute the test classes from maven command line return res; } File file = new File(suite.getXmlSuite().getFileName()); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setValidating(false); documentBuilderFactory.setNamespaceAware(true); try { documentBuilderFactory.setFeature("http://xml.org/sax/features/namespaces", false); documentBuilderFactory.setFeature("http://xml.org/sax/features/validation", false); documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(file); for (int i = 0; i < document.getChildNodes().getLength(); i++) { NamedNodeMap nodeMapAttributes = document.getChildNodes().item(i).getAttributes(); if (nodeMapAttributes == null) { continue; } // get "name" from suite element // <suite verbose="1" name="Carina Demo Tests - API Sample" thread-count="3" > Node nodeName = nodeMapAttributes.getNamedItem("name"); if (nodeName == null) { continue; } if (suite.getName().equals(nodeName.getNodeValue())) { // valid suite node detected Node nodeAttribute = nodeMapAttributes.getNamedItem(attribute); if (nodeAttribute != null) { res = nodeAttribute.getNodeValue(); break; } } } } catch (Exception e) { LOGGER.warn("Unable to get attribute '" + attribute +"' from suite: " + suite.getXmlSuite().getFileName(), e); } return res; } private void setThreadCount(ISuite suite) { //Reuse default thread-count value from suite TestNG file if it is not overridden in _config.properties /* * WARNING! We coudn't override default thread-count="5" and data-provider-thread-count="10"! * suite.getXmlSuite().toXml() add those default values anyway even if the absent in suite xml file declaraton. * To make possible to parse correctly we had to reuse external parser and private getAttributeValue */ if (SpecialKeywords.CUSTOM.equalsIgnoreCase(R.CONFIG.get(Parameter.THREAD_COUNT.getKey()))) { LOGGER.info("Custom thread count manipulation is enabled. Carina will skip any updates with thread count..."); return; } if (Configuration.getThreadCount()>= 1) { // use thread-count from config.properties suite.getXmlSuite().setThreadCount(Configuration.getThreadCount()); LOGGER.debug("Updated thread-count=" + suite.getXmlSuite().getThreadCount()); } else { String suiteThreadCount = getAttributeValue(suite, "thread-count"); LOGGER.debug("thread-count from suite: " + suiteThreadCount); if (suiteThreadCount.isEmpty()) { LOGGER.info("Set thread-count=1"); R.CONFIG.put(Parameter.THREAD_COUNT.getKey(), "1"); suite.getXmlSuite().setThreadCount(1); } else { // reuse value from suite xml file LOGGER.debug("Synching thread-count with values from suite xml file..."); R.CONFIG.put(Parameter.THREAD_COUNT.getKey(), suiteThreadCount); LOGGER.info("Use thread-count='" + suite.getXmlSuite().getThreadCount() + "' from suite file."); } } if (Configuration.getDataProviderThreadCount() >= 1) { // use thread-count from config.properties suite.getXmlSuite().setDataProviderThreadCount(Configuration.getDataProviderThreadCount()); LOGGER.debug("Updated data-provider-thread-count=" + suite.getXmlSuite().getDataProviderThreadCount()); } else { String suiteDataProviderThreadCount = getAttributeValue(suite, "data-provider-thread-count"); LOGGER.debug("data-provider-thread-count from suite: " + suiteDataProviderThreadCount); if (suiteDataProviderThreadCount.isEmpty()) { LOGGER.info("Set data-provider-thread-count=1"); R.CONFIG.put(Parameter.DATA_PROVIDER_THREAD_COUNT.getKey(), "1"); suite.getXmlSuite().setDataProviderThreadCount(1); } else { // reuse value from suite xml file LOGGER.debug("Synching data-provider-thread-count with values from suite xml file..."); R.CONFIG.put(Parameter.DATA_PROVIDER_THREAD_COUNT.getKey(), suiteDataProviderThreadCount); LOGGER.info("Use data-provider-thread-count='" + suite.getXmlSuite().getDataProviderThreadCount() + "' from suite file."); } } } private String getCarinaVersion() { String carinaVersion = ""; try { Class<CarinaListener> theClass = CarinaListener.class; String classPath = theClass.getResource(theClass.getSimpleName() + ".class").toString(); LOGGER.debug("Class: " + classPath); Pattern pattern = Pattern.compile(".*\\/(.*)\\/.*!"); Matcher matcher = pattern.matcher(classPath); if (matcher.find()) { carinaVersion = matcher.group(1); } } catch (Exception e) { LOGGER.debug(e); } return carinaVersion; } private void attachTestLabels(ITestResult result) { // register testrail cases... Set<String> trCases = getTestRailCasesUuid(result); for (String trCase : trCases) { TestRail.setCaseId(trCase); } // register qtest cases... Set<String> qtestCases = getQTestCasesUuid(result); if (qtestCases.size() > 0) { Label.attachToTest(SpecialKeywords.QTEST_TESTCASE_UUID, Arrays.copyOf(qtestCases.toArray(), qtestCases.size(), String[].class)); } } private void attachTestRunLabels(ISuite suite) { String trSuite = getTestRailSuiteId(suite); if (!trSuite.isEmpty()) { TestRail.setSuiteId(trSuite); } // read command line argument to improve test rail integration capabilities. if (!Configuration.getBoolean(Parameter.TESTRAIL_ENABLED)) { LOGGER.debug("disable TestRail integration!"); TestRail.disableSync(); } if (Configuration.getBoolean(Parameter.INCLUDE_ALL)) { LOGGER.info("enable include_all for TestRail integration!"); TestRail.includeAllTestCasesInNewRun(); } String milestone = Configuration.get(Parameter.MILESTONE); if (!milestone.isEmpty()) { LOGGER.info("Set TestRail milestone name: " + milestone); TestRail.setMilestone(milestone); } String runName = Configuration.get(Parameter.RUN_NAME); if (!runName.isEmpty()) { LOGGER.info("Set TestRail run name: " + runName); TestRail.setRunName(runName); } String assignee = Configuration.get(Parameter.ASSIGNEE); if (!assignee.isEmpty()) { LOGGER.info("Set TestRail assignee: " + assignee); TestRail.setAssignee(assignee); } String qtestProject = getQTestProjectId(suite); if (!qtestProject.isEmpty()){ Label.attachToTestRun(SpecialKeywords.QTEST_PROJECT_ID, qtestProject); } } private String takeScreenshot(String msg) { return takeScreenshot(msg, true); } private String takeScreenshot(String msg, boolean isFullSize) { String screenId = ""; ConcurrentHashMap<String, CarinaDriver> drivers = getDrivers(); try { for (Map.Entry<String, CarinaDriver> entry : drivers.entrySet()) { String driverName = entry.getKey(); WebDriver drv = entry.getValue().getDriver(); if (drv instanceof EventFiringWebDriver) { drv = ((EventFiringWebDriver) drv).getWrappedDriver(); } if (Screenshot.isEnabled()) { screenId = Screenshot.capture(drv, driverName + ": " + msg, isFullSize); // in case of failure } } } catch (Throwable thr) { LOGGER.error("Failure detected on screenshot generation after failure: ", thr); } return screenId; } public static class ShutdownHook extends Thread { private static final Logger LOGGER = Logger.getLogger(ShutdownHook.class); private void quitAllDriversOnHook() { // as it is shutdown hook just try to quit all existing drivers one by one for (CarinaDriver carinaDriver : driversPool) { // it is expected that all drivers are killed in appropriate AfterMethod/Class/Suite blocks String name = carinaDriver.getName(); LOGGER.warn("Trying to quit driver '" + name + "' on shutdown hook action!"); carinaDriver.getDevice().disconnectRemote(); ProxyPool.stopProxy(); try { LOGGER.debug("Driver closing..." + name); carinaDriver.getDriver().close(); LOGGER.debug("Driver exiting..." + name); carinaDriver.getDriver().quit(); LOGGER.debug("Driver exited..." + name); } catch (Exception e) { // do nothing } } } @Override public void run() { LOGGER.debug("Running shutdown hook"); if (!Configuration.getBoolean(Parameter.FORCIBLY_DISABLE_DRIVER_QUIT)) { quitAllDriversOnHook(); } } } }
/* * 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. */ package com.google.ads.googleads.v5.services; import com.google.ads.googleads.v5.resources.SharedSet; import com.google.ads.googleads.v5.services.SharedSetServiceGrpc.SharedSetServiceImplBase; import com.google.api.core.BetaApi; import com.google.protobuf.AbstractMessage; import io.grpc.stub.StreamObserver; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; @javax.annotation.Generated("by GAPIC") @BetaApi public class MockSharedSetServiceImpl extends SharedSetServiceImplBase { private List<AbstractMessage> requests; private Queue<Object> responses; public MockSharedSetServiceImpl() { requests = new ArrayList<>(); responses = new LinkedList<>(); } public List<AbstractMessage> getRequests() { return requests; } public void addResponse(AbstractMessage response) { responses.add(response); } public void setResponses(List<AbstractMessage> responses) { this.responses = new LinkedList<Object>(responses); } public void addException(Exception exception) { responses.add(exception); } public void reset() { requests = new ArrayList<>(); responses = new LinkedList<>(); } @Override public void getSharedSet( GetSharedSetRequest request, StreamObserver<SharedSet> responseObserver) { Object response = responses.remove(); if (response instanceof SharedSet) { requests.add(request); responseObserver.onNext((SharedSet) response); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError((Exception) response); } else { responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); } } @Override public void mutateSharedSets( MutateSharedSetsRequest request, StreamObserver<MutateSharedSetsResponse> responseObserver) { Object response = responses.remove(); if (response instanceof MutateSharedSetsResponse) { requests.add(request); responseObserver.onNext((MutateSharedSetsResponse) response); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError((Exception) response); } else { responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); } } }
/* * 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.aliyuncs.xingzhen.model.v20191121; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; /** * @author auto create * @version */ public class GetAlertSubscriberRequest extends RpcAcsRequest<GetAlertSubscriberResponse> { private Long cONFIGId; public GetAlertSubscriberRequest() { super("Xingzhen", "2019-11-21", "GetAlertSubscriber"); setMethod(MethodType.POST); } public Long getCONFIGId() { return this.cONFIGId; } public void setCONFIGId(Long cONFIGId) { this.cONFIGId = cONFIGId; if(cONFIGId != null){ putQueryParameter("CONFIGId", cONFIGId.toString()); } } @Override public Class<GetAlertSubscriberResponse> getResponseClass() { return GetAlertSubscriberResponse.class; } }
package org.gradle.test.performance.mediummonolithicjavaproject.p9; import org.gradle.test.performance.mediummonolithicjavaproject.p8.Production177; import org.junit.Test; import static org.junit.Assert.*; public class Test186 { Production186 objectUnderTest = new Production186(); @Test public void testProperty0() { Production177 value = new Production177(); objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { Production181 value = new Production181(); objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { Production185 value = new Production185(); 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()); } }
package com.aoto.systemutil.domainms.repository.dao; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import com.aoto.systemutil.domainms.repository.pojo.Domain; @Mapper public interface IDomainIbaitsDao{ @Select("select * from sys_domains where businesstype=#{type}") public List<Domain> queryDomainByBusinessType(@Param("type") String type); }
/* * Copyright 2018, Oath Inc. * Licensed under the terms of the Apache License, Version 2.0. * See the LICENSE file associated with the project for terms. */ package com.yahoo.bullet.bql.tree; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static com.yahoo.bullet.bql.tree.DereferenceExpression.from; import static com.yahoo.bullet.bql.tree.DereferenceExpression.getQualifiedName; import static com.yahoo.bullet.bql.util.QueryUtil.identifier; import static java.util.Collections.singletonList; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; public class DereferenceExpressionTest { private Expression base; private Identifier field; private DereferenceExpression dereference; @BeforeClass public void setUp() { base = identifier("aaa"); field = identifier("bbb"); dereference = new DereferenceExpression(base, field); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "base is null") public void testConstructorNullBase() { new DereferenceExpression(null, field); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "fieldName is null") public void testConstructorNullField() { new DereferenceExpression(base, null); } @Test public void testGetChildren() { assertEquals(dereference.getChildren(), singletonList(base)); } @Test public void testFrom() { QualifiedName qualifiedName = QualifiedName.of("AAA", "BBB"); Expression expression = from(qualifiedName); assertEquals(dereference, expression); } @Test public void testGetQualifiedName() { QualifiedName qualifiedName = QualifiedName.of("aaa", "bbb"); assertEquals(getQualifiedName(dereference), qualifiedName); Expression base = new NullLiteral(); DereferenceExpression dereferenceNullLiteralBase = new DereferenceExpression(base, field); assertNull(getQualifiedName(dereferenceNullLiteralBase)); DereferenceExpression dereferenceDereferenceBase = new DereferenceExpression(dereference, field); assertEquals(getQualifiedName(dereferenceDereferenceBase), QualifiedName.of("aaa", "bbb", "bbb")); DereferenceExpression dereferenceInvalidDereferenceBase = new DereferenceExpression(dereferenceNullLiteralBase, field); assertNull(getQualifiedName(dereferenceInvalidDereferenceBase)); } @Test public void testEquals() { DereferenceExpression dereferenceCopy = dereference; assertTrue(dereference.equals(dereferenceCopy)); assertFalse(dereference.equals(null)); assertFalse(dereference.equals(base)); DereferenceExpression sameDereference = new DereferenceExpression(identifier("aaa"), field); assertTrue(dereference.equals(sameDereference)); DereferenceExpression dereferenceDiffBase = new DereferenceExpression(identifier("bbb"), field); assertFalse(dereference.equals(dereferenceDiffBase)); DereferenceExpression dereferenceDiffField = new DereferenceExpression(base, identifier("aaa")); assertFalse(dereference.equals(dereferenceDiffField)); } }
/* * The MIT License (MIT) * * Copyright (c) 2014-2017 abel533@gmail.com * * 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 tk.mybatis.mapper.mapperhelper; import tk.mybatis.mapper.annotation.Version; import tk.mybatis.mapper.entity.EntityColumn; import tk.mybatis.mapper.entity.IDynamicTableName; import tk.mybatis.mapper.util.StringUtil; import tk.mybatis.mapper.version.VersionException; import java.util.Set; /** * 拼常用SQL的工具类 * * @author liuzh * @since 2015-11-03 22:40 */ public class SqlHelper { /** * 获取表名 - 支持动态表名 * * @param entityClass * @param tableName * @return */ public static String getDynamicTableName(Class<?> entityClass, String tableName) { if (IDynamicTableName.class.isAssignableFrom(entityClass)) { StringBuilder sql = new StringBuilder(); sql.append("<choose>"); sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@isDynamicParameter(_parameter) and dynamicTableName != null and dynamicTableName != ''\">"); sql.append("${dynamicTableName}\n"); sql.append("</when>"); //不支持指定列的时候查询全部列 sql.append("<otherwise>"); sql.append(tableName); sql.append("</otherwise>"); sql.append("</choose>"); return sql.toString(); } else { return tableName; } } /** * 获取表名 - 支持动态表名,该方法用于多个入参时,通过parameterName指定入参中实体类的@Param的注解值 * * @param entityClass * @param tableName * @param parameterName * @return */ public static String getDynamicTableName(Class<?> entityClass, String tableName, String parameterName) { if (IDynamicTableName.class.isAssignableFrom(entityClass)) { if (StringUtil.isNotEmpty(parameterName)) { StringBuilder sql = new StringBuilder(); sql.append("<choose>"); sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@isDynamicParameter(" + parameterName + ") and " + parameterName + ".dynamicTableName != null and " + parameterName + ".dynamicTableName != ''\">"); sql.append("${" + parameterName + ".dynamicTableName}"); sql.append("</when>"); //不支持指定列的时候查询全部列 sql.append("<otherwise>"); sql.append(tableName); sql.append("</otherwise>"); sql.append("</choose>"); return sql.toString(); } else { return getDynamicTableName(entityClass, tableName); } } else { return tableName; } } /** * <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" /> * * @param column * @return */ public static String getBindCache(EntityColumn column) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\""); sql.append(column.getProperty()).append("_cache\" "); sql.append("value=\"").append(column.getProperty()).append("\"/>"); return sql.toString(); } /** * <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" /> * * @param column * @return */ public static String getBindValue(EntityColumn column, String value) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\""); sql.append(column.getProperty()).append("_bind\" "); sql.append("value='").append(value).append("'/>"); return sql.toString(); } /** * <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" /> * * @param column * @return */ public static String getIfCacheNotNull(EntityColumn column, String contents) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"").append(column.getProperty()).append("_cache != null\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); } /** * 如果_cache == null * * @param column * @return */ public static String getIfCacheIsNull(EntityColumn column, String contents) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"").append(column.getProperty()).append("_cache == null\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); } /** * 判断自动!=null的条件结构 * * @param column * @param contents * @param empty * @return */ public static String getIfNotNull(EntityColumn column, String contents, boolean empty) { return getIfNotNull(null, column, contents, empty); } /** * 判断自动==null的条件结构 * * @param column * @param contents * @param empty * @return */ public static String getIfIsNull(EntityColumn column, String contents, boolean empty) { return getIfIsNull(null, column, contents, empty); } /** * 判断自动!=null的条件结构 * * @param entityName * @param column * @param contents * @param empty * @return */ public static String getIfNotNull(String entityName, EntityColumn column, String contents, boolean empty) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\""); if (StringUtil.isNotEmpty(entityName)) { sql.append(entityName).append("."); } sql.append(column.getProperty()).append(" != null"); if (empty && column.getJavaType().equals(String.class)) { sql.append(" and "); if (StringUtil.isNotEmpty(entityName)) { sql.append(entityName).append("."); } sql.append(column.getProperty()).append(" != '' "); } sql.append("\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); } /** * 判断自动==null的条件结构 * * @param entityName * @param column * @param contents * @param empty * @return */ public static String getIfIsNull(String entityName, EntityColumn column, String contents, boolean empty) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\""); if (StringUtil.isNotEmpty(entityName)) { sql.append(entityName).append("."); } sql.append(column.getProperty()).append(" == null"); if (empty && column.getJavaType().equals(String.class)) { sql.append(" or "); if (StringUtil.isNotEmpty(entityName)) { sql.append(entityName).append("."); } sql.append(column.getProperty()).append(" == '' "); } sql.append("\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); } /** * 获取所有查询列,如id,name,code... * * @param entityClass * @return */ public static String getAllColumns(Class<?> entityClass) { Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); StringBuilder sql = new StringBuilder(); for (EntityColumn entityColumn : columnSet) { sql.append("`"+entityColumn.getColumn()+"`").append(","); } return sql.substring(0, sql.length() - 1); } /** * select xxx,xxx... * * @param entityClass * @return */ public static String selectAllColumns(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("SELECT "); sql.append(getAllColumns(entityClass)); sql.append(" "); return sql.toString(); } /** * select count(x) * * @param entityClass * @return */ public static String selectCount(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("SELECT "); Set<EntityColumn> pkColumns = EntityHelper.getPKColumns(entityClass); if (pkColumns.size() == 1) { sql.append("COUNT(").append(pkColumns.iterator().next().getColumn()).append(") "); } else { sql.append("COUNT(*) "); } return sql.toString(); } /** * select case when count(x) > 0 then 1 else 0 end * * @param entityClass * @return */ public static String selectCountExists(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("SELECT CASE WHEN "); Set<EntityColumn> pkColumns = EntityHelper.getPKColumns(entityClass); if (pkColumns.size() == 1) { sql.append("COUNT(").append(pkColumns.iterator().next().getColumn()).append(") "); } else { sql.append("COUNT(*) "); } sql.append(" > 0 THEN 1 ELSE 0 END AS result "); return sql.toString(); } /** * from tableName - 动态表名 * * @param entityClass * @param defaultTableName * @return */ public static String fromTable(Class<?> entityClass, String defaultTableName) { StringBuilder sql = new StringBuilder(); sql.append(" FROM "); sql.append(getDynamicTableName(entityClass, defaultTableName)); sql.append(" "); return sql.toString(); } /** * update tableName - 动态表名 * * @param entityClass * @param defaultTableName * @return */ public static String updateTable(Class<?> entityClass, String defaultTableName) { return updateTable(entityClass, defaultTableName, null); } /** * update tableName - 动态表名 * * @param entityClass * @param defaultTableName 默认表名 * @param entityName 别名 * @return */ public static String updateTable(Class<?> entityClass, String defaultTableName, String entityName) { StringBuilder sql = new StringBuilder(); sql.append("UPDATE "); sql.append(getDynamicTableName(entityClass, defaultTableName, entityName)); sql.append(" "); return sql.toString(); } /** * delete tableName - 动态表名 * * @param entityClass * @param defaultTableName * @return */ public static String deleteFromTable(Class<?> entityClass, String defaultTableName) { StringBuilder sql = new StringBuilder(); sql.append("DELETE FROM "); sql.append(getDynamicTableName(entityClass, defaultTableName)); sql.append(" "); return sql.toString(); } /** * insert into tableName - 动态表名 * * @param entityClass * @param defaultTableName * @return */ public static String insertIntoTable(Class<?> entityClass, String defaultTableName) { StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO "); sql.append(getDynamicTableName(entityClass, defaultTableName)); sql.append(" "); return sql.toString(); } /** * insert table()列 * * @param entityClass * @param skipId 是否从列中忽略id类型 * @param notNull 是否判断!=null * @param notEmpty 是否判断String类型!='' * @return */ public static String insertColumns(Class<?> entityClass, boolean skipId, boolean notNull, boolean notEmpty) { StringBuilder sql = new StringBuilder(); sql.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">"); //获取全部列 Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); //当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值 for (EntityColumn column : columnSet) { if (!column.isInsertable()) { continue; } if (skipId && column.isId()) { continue; } if (notNull) { sql.append(SqlHelper.getIfNotNull(column, "`"+column.getColumn() + "`,", notEmpty)); } else { sql.append("`"+column.getColumn() + "`,"); } } sql.append("</trim>"); return sql.toString(); } /** * insert-values()列 * * @param entityClass * @param skipId 是否从列中忽略id类型 * @param notNull 是否判断!=null * @param notEmpty 是否判断String类型!='' * @return */ public static String insertValuesColumns(Class<?> entityClass, boolean skipId, boolean notNull, boolean notEmpty) { StringBuilder sql = new StringBuilder(); sql.append("<trim prefix=\"VALUES (\" suffix=\")\" suffixOverrides=\",\">"); //获取全部列 Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); //当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值 for (EntityColumn column : columnSet) { if (!column.isInsertable()) { continue; } if (skipId && column.isId()) { continue; } if (notNull) { sql.append(SqlHelper.getIfNotNull(column, column.getColumnHolder() + ",", notEmpty)); } else { sql.append(column.getColumnHolder() + ","); } } sql.append("</trim>"); return sql.toString(); } /** * update set列 * * @param entityClass * @param entityName 实体映射名 * @param notNull 是否判断!=null * @param notEmpty 是否判断String类型!='' * @return */ public static String updateSetColumns(Class<?> entityClass, String entityName, boolean notNull, boolean notEmpty) { StringBuilder sql = new StringBuilder(); sql.append("<set>"); //获取全部列 Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); //对乐观锁的支持 EntityColumn versionColumn = null; //当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值 for (EntityColumn column : columnSet) { if (column.getEntityField().isAnnotationPresent(Version.class)) { if (versionColumn != null) { throw new VersionException(entityClass.getCanonicalName() + " 中包含多个带有 @Version 注解的字段,一个类中只能存在一个带有 @Version 注解的字段!"); } versionColumn = column; } if (!column.isId() && column.isUpdatable()) { if (column == versionColumn) { Version version = versionColumn.getEntityField().getAnnotation(Version.class); String versionClass = version.nextVersion().getCanonicalName(); //version = ${@tk.mybatis.mapper.version@nextVersionClass("versionClass", version)} sql.append(column.getColumn()) .append(" = ${@tk.mybatis.mapper.version.VersionUtil@nextVersion(") .append("@").append(versionClass).append("@class, ") .append(column.getProperty()).append(")},"); } else if (notNull) { sql.append(SqlHelper.getIfNotNull(entityName, column, column.getColumnEqualsHolder(entityName) + ",", notEmpty)); } else { sql.append(column.getColumnEqualsHolder(entityName) + ","); } } else if(column.isId() && column.isUpdatable()){ //set id = id, sql.append(column.getColumn()).append(" = ").append(column.getColumn()).append(","); } } sql.append("</set>"); return sql.toString(); } /** * 不是所有参数都是 null 的检查 * * @param parameterName 参数名 * @param columnSet 需要检查的列 * @return */ public static String notAllNullParameterCheck(String parameterName, Set<EntityColumn> columnSet) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\"notAllNullParameterCheck\" value=\"@tk.mybatis.mapper.util.OGNL@notAllNullParameterCheck("); sql.append(parameterName).append(", '"); StringBuilder fields = new StringBuilder(); for (EntityColumn column : columnSet) { if(fields.length() > 0){ fields.append(","); } fields.append(column.getProperty()); } sql.append(fields); sql.append("')\"/>"); return sql.toString(); } /** * Example 中包含至少 1 个查询条件 * * @param parameterName 参数名 * @return */ public static String exampleHasAtLeastOneCriteriaCheck(String parameterName) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\"exampleHasAtLeastOneCriteriaCheck\" value=\"@tk.mybatis.mapper.util.OGNL@exampleHasAtLeastOneCriteriaCheck("); sql.append(parameterName).append(")\"/>"); return sql.toString(); } /** * where主键条件 * * @param entityClass * @return */ public static String wherePKColumns(Class<?> entityClass) { return wherePKColumns(entityClass, false); } /** * where主键条件 * * @param entityClass * @param useVersion * @return */ public static String wherePKColumns(Class<?> entityClass, boolean useVersion) { return wherePKColumns(entityClass, null, useVersion); } /** * where主键条件 * * @param entityClass * @param entityName * @param useVersion * @return */ public static String wherePKColumns(Class<?> entityClass,String entityName, boolean useVersion) { StringBuilder sql = new StringBuilder(); sql.append("<where>"); //获取全部列 Set<EntityColumn> columnSet = EntityHelper.getPKColumns(entityClass); //当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值 for (EntityColumn column : columnSet) { sql.append(" AND " + column.getColumnEqualsHolder(entityName)); } if (useVersion) { sql.append(whereVersion(entityClass)); } sql.append("</where>"); return sql.toString(); } /** * where所有列的条件,会判断是否!=null * * @param entityClass * @param empty * @return */ public static String whereAllIfColumns(Class<?> entityClass, boolean empty) { return whereAllIfColumns(entityClass, empty, false); } /** * where所有列的条件,会判断是否!=null * * @param entityClass * @param empty * @param useVersion * @return */ public static String whereAllIfColumns(Class<?> entityClass, boolean empty, boolean useVersion) { StringBuilder sql = new StringBuilder(); sql.append("<where>"); //获取全部列 Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); //当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值 for (EntityColumn column : columnSet) { if (!useVersion || !column.getEntityField().isAnnotationPresent(Version.class)) { sql.append(getIfNotNull(column, " AND " + column.getColumnEqualsHolder(), empty)); } } if (useVersion) { sql.append(whereVersion(entityClass)); } sql.append("</where>"); return sql.toString(); } /** * 乐观锁字段条件 * * @param entityClass * @return */ public static String whereVersion(Class<?> entityClass) { Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); boolean hasVersion = false; String result = ""; for (EntityColumn column : columnSet) { if (column.getEntityField().isAnnotationPresent(Version.class)) { if (hasVersion) { throw new VersionException(entityClass.getCanonicalName() + " 中包含多个带有 @Version 注解的字段,一个类中只能存在一个带有 @Version 注解的字段!"); } hasVersion = true; result = " AND " + column.getColumnEqualsHolder(); } } return result; } /** * 获取默认的orderBy,通过注解设置的 * * @param entityClass * @return */ public static String orderByDefault(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); String orderByClause = EntityHelper.getOrderByClause(entityClass); if (orderByClause.length() > 0) { sql.append(" ORDER BY "); sql.append(orderByClause); } return sql.toString(); } /** * example支持查询指定列时 * * @return */ public static String exampleSelectColumns(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<choose>"); sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@hasSelectColumns(_parameter)\">"); sql.append("<foreach collection=\"_parameter.selectColumns\" item=\"selectColumn\" separator=\",\">"); sql.append("${selectColumn}"); sql.append("</foreach>"); sql.append("</when>"); //不支持指定列的时候查询全部列 sql.append("<otherwise>"); sql.append(getAllColumns(entityClass)); sql.append("</otherwise>"); sql.append("</choose>"); return sql.toString(); } /** * example支持查询指定列时 * * @return */ public static String exampleCountColumn(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<choose>"); sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@hasCountColumn(_parameter)\">"); sql.append("COUNT(<if test=\"distinct\">distinct </if>${countColumn})"); sql.append("</when>"); sql.append("<otherwise>"); sql.append("COUNT(*)"); sql.append("</otherwise>"); sql.append("</choose>"); return sql.toString(); } /** * example查询中的orderBy条件,会判断默认orderBy * * @return */ public static String exampleOrderBy(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"orderByClause != null\">"); sql.append("order by ${orderByClause}"); sql.append("</if>"); String orderByClause = EntityHelper.getOrderByClause(entityClass); if (orderByClause.length() > 0) { sql.append("<if test=\"orderByClause == null\">"); sql.append("ORDER BY " + orderByClause); sql.append("</if>"); } return sql.toString(); } /** * example查询中的orderBy条件,会判断默认orderBy * * @return */ public static String exampleOrderBy(String entityName, Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"").append(entityName).append(".orderByClause != null\">"); sql.append("order by ${").append(entityName).append(".orderByClause}"); sql.append("</if>"); String orderByClause = EntityHelper.getOrderByClause(entityClass); if (orderByClause.length() > 0) { sql.append("<if test=\"").append(entityName).append(".orderByClause == null\">"); sql.append("ORDER BY " + orderByClause); sql.append("</if>"); } return sql.toString(); } /** * example 支持 for update * * @return */ public static String exampleForUpdate() { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"@tk.mybatis.mapper.util.OGNL@hasForUpdate(_parameter)\">"); sql.append("FOR UPDATE"); sql.append("</if>"); return sql.toString(); } /** * example 支持 for update * * @return */ public static String exampleCheck(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\"checkExampleEntityClass\" value=\"@tk.mybatis.mapper.util.OGNL@checkExampleEntityClass(_parameter, '"); sql.append(entityClass.getCanonicalName()); sql.append("')\"/>"); return sql.toString(); } /** * Example查询中的where结构,用于只有一个Example参数时 * * @return */ public static String exampleWhereClause() { return "<if test=\"_parameter != null\">" + "<where>\n" + " <foreach collection=\"oredCriteria\" item=\"criteria\">\n" + " <if test=\"criteria.valid\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criteria)}" + " <trim prefix=\"(\" prefixOverrides=\"and |or \" suffix=\")\">\n" + " <foreach collection=\"criteria.criteria\" item=\"criterion\">\n" + " <choose>\n" + " <when test=\"criterion.noValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" + " </when>\n" + " <when test=\"criterion.singleValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value}\n" + " </when>\n" + " <when test=\"criterion.betweenValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value} and #{criterion.secondValue}\n" + " </when>\n" + " <when test=\"criterion.listValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" + " <foreach close=\")\" collection=\"criterion.value\" item=\"listItem\" open=\"(\" separator=\",\">\n" + " #{listItem}\n" + " </foreach>\n" + " </when>\n" + " </choose>\n" + " </foreach>\n" + " </trim>\n" + " </if>\n" + " </foreach>\n" + "</where>" + "</if>"; } /** * Example-Update中的where结构,用于多个参数时,Example带@Param("example")注解时 * * @return */ public static String updateByExampleWhereClause() { return "<where>\n" + " <foreach collection=\"example.oredCriteria\" item=\"criteria\">\n" + " <if test=\"criteria.valid\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criteria)}" + " <trim prefix=\"(\" prefixOverrides=\"and |or \" suffix=\")\">\n" + " <foreach collection=\"criteria.criteria\" item=\"criterion\">\n" + " <choose>\n" + " <when test=\"criterion.noValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" + " </when>\n" + " <when test=\"criterion.singleValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value}\n" + " </when>\n" + " <when test=\"criterion.betweenValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value} and #{criterion.secondValue}\n" + " </when>\n" + " <when test=\"criterion.listValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" + " <foreach close=\")\" collection=\"criterion.value\" item=\"listItem\" open=\"(\" separator=\",\">\n" + " #{listItem}\n" + " </foreach>\n" + " </when>\n" + " </choose>\n" + " </foreach>\n" + " </trim>\n" + " </if>\n" + " </foreach>\n" + "</where>"; } }
/* * Copyright (C) 2017-2019 Dremio 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 com.dremio.sabot.driver; import java.lang.reflect.Constructor; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.Set; import com.dremio.common.exceptions.ExecutionSetupException; import com.dremio.common.exceptions.UserException; import com.dremio.common.scanner.persistence.ScanResult; import com.dremio.exec.physical.base.PhysicalOperator; import com.dremio.sabot.exec.context.OperatorContext; import com.dremio.sabot.exec.fragment.FragmentExecutionContext; import com.dremio.sabot.exec.rpc.TunnelProvider; import com.dremio.sabot.op.spi.BatchStreamProvider; import com.dremio.sabot.op.spi.DualInputOperator; import com.dremio.sabot.op.spi.ProducerOperator; import com.dremio.sabot.op.spi.SingleInputOperator; import com.dremio.sabot.op.spi.TerminalOperator; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; @SuppressWarnings("unchecked") public class OperatorCreatorRegistry implements OperatorCreator { static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OperatorCreatorRegistry.class); @SuppressWarnings("rawtypes") private final ImmutableMap<Class<?>, SingleInputOperator.Creator> singleInputCreators; @SuppressWarnings("rawtypes") private final ImmutableMap<Class<?>, DualInputOperator.Creator> dualInputCreators; @SuppressWarnings("rawtypes") private final ImmutableMap<Class<?>, ProducerOperator.Creator> producerCreators; @SuppressWarnings("rawtypes") private final ImmutableMap<Class<?>, ProducerOperator.ReceiverCreator> receiverCreators; @SuppressWarnings("rawtypes") private final ImmutableMap<Class<?>, TerminalOperator.Creator> terminalCreators; public OperatorCreatorRegistry(ScanResult scanResult) { this.singleInputCreators = getImplementors(scanResult, SingleInputOperator.Creator.class); this.dualInputCreators = getImplementors(scanResult, DualInputOperator.Creator.class); this.producerCreators = getImplementors(scanResult, ProducerOperator.Creator.class); this.receiverCreators = getImplementors(scanResult, ProducerOperator.ReceiverCreator.class); this.terminalCreators = getImplementors(scanResult, TerminalOperator.Creator.class); } @Override public <T extends PhysicalOperator> SingleInputOperator getSingleInputOperator(OperatorContext context, T operator) throws ExecutionSetupException { SingleInputOperator.Creator<T> creator = (SingleInputOperator.Creator<T>) singleInputCreators .get(operator.getClass()); Preconditions.checkNotNull(creator, "Unable to find creator for operator of type %s with configuration %s", operator.getClass().getName(), operator.toString()); return creator.create(context, (T) operator); } @Override public <T extends PhysicalOperator> DualInputOperator getDualInputOperator(OperatorContext context, T operator) throws ExecutionSetupException { DualInputOperator.Creator<T> creator = (DualInputOperator.Creator<T>) dualInputCreators.get(operator.getClass()); Preconditions.checkNotNull(creator, "Unable to find creator for operator of type %s with configuration %s", operator.getClass().getName(), operator.toString()); return creator.create(context, (T) operator); } @Override public <T extends PhysicalOperator> TerminalOperator getTerminalOperator(TunnelProvider provider, OperatorContext context, T operator) throws ExecutionSetupException { TerminalOperator.Creator<T> creator = (TerminalOperator.Creator<T>) terminalCreators.get(operator.getClass()); Preconditions.checkNotNull(creator, "Unable to find creator for operator of type %s with configuration %s", operator.getClass().getName(), operator.toString()); return creator.create(provider, context, (T) operator); } @Override public <T extends PhysicalOperator> ProducerOperator getProducerOperator(FragmentExecutionContext fec, OperatorContext context, T operator) throws ExecutionSetupException { ProducerOperator.Creator<T> creator = (ProducerOperator.Creator<T>) producerCreators.get(operator.getClass()); Preconditions.checkNotNull(creator, "Unable to find creator for operator of type %s with configuration %s", operator.getClass().getName(), operator.toString()); return creator.create(fec, context, (T) operator); } @Override public <T extends PhysicalOperator> ProducerOperator getReceiverOperator(BatchStreamProvider buffers, OperatorContext context, T operator) throws ExecutionSetupException { ProducerOperator.ReceiverCreator<T> creator = (ProducerOperator.ReceiverCreator<T>) receiverCreators.get(operator.getClass()); Preconditions.checkNotNull(creator, "Unable to find creator for operator of type %s with configuration %s", operator.getClass().getName(), operator.toString()); return creator.create(buffers, context, (T) operator); } private <T> ImmutableMap<Class<?>, T> getImplementors(ScanResult scanResult, Class<T> baseInterface) { final Map<Class<?>, T> map = new HashMap<>(); Set<Class<? extends T>> providerClasses = scanResult.getImplementations(baseInterface); for (Class<?> c : providerClasses) { Class<?> operatorClass = c; boolean interfaceFound = false; while (!interfaceFound && !(c.equals(java.lang.Object.class))) { final Type[] ifaces = c.getGenericInterfaces(); // never returns null for (Type iface : ifaces) { if (!(iface instanceof ParameterizedType && ((ParameterizedType) iface).getRawType().equals(baseInterface))) { continue; } final Type[] args = ((ParameterizedType) iface).getActualTypeArguments(); interfaceFound = true; boolean constructorFound = false; for (Constructor<?> constructor : operatorClass.getConstructors()) { Class<?>[] params = constructor.getParameterTypes(); if (params.length == 0) { try { T newInstance = (T) constructor.newInstance(); Object old = map.put((Class<?>) args[0], newInstance); if (old != null) { throw UserException.functionError() .message("Duplicate OperatorCreator [%s, %s] found for PhysicalOperator %s", old.getClass().getCanonicalName(), operatorClass.getCanonicalName(), ((Class<?>) args[0]).getCanonicalName()) .build(logger); } constructorFound = true; } catch (Exception ex) { logger.warn("Failure while creating OperatorCreator. Constructor declaring class {}.", constructor.getDeclaringClass().getName(), ex); } } } if (!constructorFound) { logger.debug("Skipping registration of OperatorCreator {} as it doesn't have a default constructor", operatorClass.getCanonicalName()); } } c = c.getSuperclass(); } } return ImmutableMap.copyOf(map); } }
package com.moreetech.ke.laundryussd.Entity; import com.fasterxml.jackson.annotation.JsonProperty; import com.moreetech.ke.laundryussd.Utils.MenuOptionAction; import lombok.Data; /** * @author momondi on 9/26/2021 **/ @Data public class MenuOption { private String type;// helps to determine if the next step should return a response or serve a different menu private String response;// response text to be returned @JsonProperty("next_menu_level") private String nextMenuLevel;// next Menu to be displayed if the type should return a menu private MenuOptionAction action;// action router .i.e. What process should be performed to retrieve the correct set of data for display }
package com.aequilibrium.transformers.model.dto; import java.util.List; import javax.validation.constraints.NotEmpty; import org.springframework.validation.annotation.Validated; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Builder @AllArgsConstructor @NoArgsConstructor @Data @Validated @JsonInclude(Include.NON_EMPTY) public class BattleRequestDTO { @NotEmpty(message = "{notempty.battleRequest.transfomersids}") List<Long> transformersIds; }
// // Informa -- RSS Library for Java // Copyright (c) 2002 by Niko Schmuck // // 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 // package de.nava.informa.utils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.*; /** * Utility class providing some convenience methods when handling files. */ public final class FileUtils { private static Log logger = LogFactory.getLog(FileUtils.class); private FileUtils() { } public static boolean compare(String nameExpected, String nameActual) throws IOException { return compare(new File(nameExpected), new File(nameActual)); } public static boolean compare(File fileExpected, File fileActual) throws IOException { BufferedReader readExpected; try { logger.debug("Comparing golden file " + fileExpected + " to " + fileActual); readExpected = new BufferedReader(new FileReader(fileExpected)); } catch (IOException e) { logger.error("Could not read baseline: " + e); return false; } BufferedReader readActual = new BufferedReader(new FileReader(fileActual)); return compare(readExpected, readActual); } private static boolean compare(BufferedReader readerExpected, BufferedReader readerActual) throws IOException { String lineExpected = readerExpected.readLine(); String lineActual = readerActual.readLine(); while (lineExpected != null && lineActual != null) { if (!lineExpected.equals(lineActual)) { return false; } lineExpected = readerExpected.readLine(); lineActual = readerActual.readLine(); } readerExpected.close(); readerActual.close(); return lineExpected == null && lineActual == null; } /** * Copies a file from <code>inFile</code> to <code>outFile</code>. */ public static void copyFile(File inFile, File outFile) { try { logger.debug("Copying file " + inFile + " to " + outFile); InputStream in = new FileInputStream(inFile); OutputStream out = new FileOutputStream(outFile); byte[] buf = new byte[8 * 1024]; int n; while ((n = in.read(buf)) >= 0) { out.write(buf, 0, n); out.flush(); } in.close(); out.close(); } catch (Exception e) { logger.warn("Error occurred while copying file " + inFile + " to " + outFile); e.printStackTrace(); } } }
package com.hcbxwy.wegee.modules.user.service.impl; import cn.hutool.core.util.RandomUtil; import cn.hutool.crypto.SecureUtil; import com.hcbxwy.wegee.modules.user.entity.User; import com.hcbxwy.wegee.modules.user.dao.UserDao; import com.hcbxwy.wegee.modules.user.entity.UserAccount; import com.hcbxwy.wegee.modules.user.enums.AccountType; import com.hcbxwy.wegee.modules.user.service.UserAccountService; import com.hcbxwy.wegee.modules.user.service.UserService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.hcbxwy.wegee.modules.user.vo.RegisterVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * <p> * 用户表 服务实现类 * </p> * * @author Billson * @since 2019-10-14 */ @Service public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService { private final UserAccountService userAccountService; @Autowired public UserServiceImpl(UserAccountService userAccountService) { this.userAccountService = userAccountService; } /** * 用户注册 * * @param registerVO 用户注册信息 * @author Billson * @since 2019/10/14 20:53 */ @Override public void saveUser(RegisterVO registerVO) { // 生成用户记录 User user = new User(); user.setNickname(registerVO.getAccount()); this.save(user); // 生成用户账号 UserAccount userAccount = new UserAccount(); String salt = RandomUtil.randomString(4); userAccount.setUserId(user.getId()) .setAccountType(AccountType.WECHAT) .setAccount(registerVO.getAccount()) .setSalt(salt) .setPassword(SecureUtil.md5(salt + registerVO.getPassword())); userAccountService.save(userAccount); } }
package com.blog.controller; import com.alibaba.fastjson.JSONObject; import com.blog.model.User; import com.blog.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; import java.util.List; /** * @package: com.blog.controller * @Author: 陈淼 * @Date: 2016/6/4 * @Description: 用户的控制类,用于拦截url为/user/*的所有请求 */ @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; //注册,若当前session已有用户信息,则不允许跳转注册页面 @RequestMapping("/register") public String register(HttpSession session) { String loginUsername = (String) session.getAttribute("loginUsername"); if (loginUsername != null && loginUsername != ""){ return null; } return "user/userRegister"; } @RequestMapping("/saveUser") public String saveUser(User user, HttpSession session)throws Exception{ userService.saveUser(user); session.setAttribute("loginUsername", user.getUsername()); return "redirect:/"; } //登陆,若当前session已有用户信息,则不允许跳转登陆页面 @RequestMapping("/login") public String login(HttpSession session){ String loginUsername = (String) session.getAttribute("loginUsername"); if (loginUsername != null && loginUsername != ""){ return null; } return "user/userLogin"; } //判断登陆页面所填写的用户信息是否存在,使用json传递结果 @RequestMapping(value = "/exist", produces = "text/html;charset=UTF-8") public @ResponseBody String existUser(User user, HttpSession session) throws Exception{ JSONObject userLogin = new JSONObject(); //密码在UserService.exitUser中校验了 boolean result = userService.existUser(user); userLogin.put("result", result); if (result){ //result结果为真说明校验通过,获取用户相关信息,并将用户名写入session user = userService.findUserByName(user.getUsername()); session.setAttribute("loginUsername", user.getUsername()); //如果权限存在且权限不为空,则在session写入权限 if (user.getPower() != null && user.getPassword() != ""){ session.setAttribute("power", user.getPower()); } System.out.println(userLogin.toJSONString()); return userLogin.toJSONString(); }else { return userLogin.toJSONString(); } } //编辑用户信息 @RequestMapping("/editUser") public String editUser(@RequestParam(value = "username", required = true) String username, Model model, HttpSession session) throws Exception{ //获取当前session的用户信息,若session内的loginUsername为空,则不允许范围编辑页面 String loginUsername = (String) session.getAttribute("loginUsername"); if (loginUsername != null){ //若session内的loginUsername不为空,判别是否与正在访问的用户信息为同一人,若不是,不允许访问 if (loginUsername.equals(username)){ User user = userService.findUserByName(username); model.addAttribute("user", user); return "user/editUser"; }else { return "redirect:/"; } } return "redirect:/"; } @RequestMapping("/updateUser") public String updateUser(Integer uid, User user)throws Exception{ userService.updateUserById(uid, user); return "user/editUser"; } //安全退出,移除session信息,并将该session设置为过期 @RequestMapping("/userLogout") public String userLogout(HttpSession session){ if (session.getAttribute("loginUsername")!=null){ session.removeAttribute("loginUsername"); session.invalidate(); } return "redirect:/"; } //列出用户列表 @RequestMapping("/listUser") public String listUser(Model model,User user) throws Exception { List<User> users = userService.findUserByList(user); model.addAttribute("users", users); return "user/listUsers"; } }
// Copyright (c) 2021, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.optimize.argumentpropagation.codescanner; import com.android.tools.r8.graph.AppView; import com.android.tools.r8.graph.DexType; import com.android.tools.r8.ir.analysis.value.AbstractValue; import com.android.tools.r8.shaking.AppInfoWithLiveness; import com.android.tools.r8.utils.Action; public class UnknownParameterState extends NonEmptyParameterState { private static final UnknownParameterState INSTANCE = new UnknownParameterState(); private UnknownParameterState() {} public static UnknownParameterState get() { return INSTANCE; } @Override public AbstractValue getAbstractValue(AppView<AppInfoWithLiveness> appView) { return AbstractValue.unknown(); } @Override public boolean isUnknown() { return true; } @Override public ParameterState mutableCopy() { return this; } @Override public ParameterState mutableJoin( AppView<AppInfoWithLiveness> appView, ParameterState parameterState, DexType parameterType, StateCloner cloner, Action onChangedAction) { return this; } }
/* * Copyright (C) 2014-present, Wei Chou(weichou2010@gmail.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 hobby.wei.c.persist.db; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; import java.sql.SQLException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import hobby.chenai.nakam.basis.TAG; import hobby.wei.c.L; /** * @author Wei Chou(weichou2010@gmail.com) */ public abstract class AbsOrmLiteHelper extends OrmLiteSqliteOpenHelper { public static TAG.LogTag TAG = new TAG.LogTag(AbsOrmLiteHelper.class.getName()); private boolean mCreatingOrUpgrading = false; /** * 如果用OpenHelperManager.getHelper(this, DBHelper.class),则应该在子类中增加这样的构造方法: * <pre> * public AbsOrmLiteHelper(Context context) { * super(context, dbName, dbVersion); * } * </pre> */ public AbsOrmLiteHelper(Context context, String dbName, int dbVersion) { super(context, dbName, null, dbVersion); } protected abstract IUpgradeStrategy getUpgradeStrategy(); protected abstract Set<Table<?, ?>> getTables(); private Set<Class<?>> getTableClasses() { Set<Class<?>> tableClazs = new HashSet<>(); Set<Table<?, ?>> tables = getTables(); if (tables != null) { for (Table<?, ?> table : tables) { tableClazs.add(table.clazz); } } return tableClazs; } protected void onCreateOthers(SQLiteDatabase database, ConnectionSource connSource) { } protected Set<String> onUpgradeOthers(SQLiteDatabase database, ConnectionSource connSource, int oldVersion, int newVersion, Map<String, String> oldTableSqls) { return Collections.emptySet(); } @Override public synchronized SQLiteDatabase getReadableDatabase() { checkIsInitializing(); return super.getReadableDatabase(); } @Override public synchronized SQLiteDatabase getWritableDatabase() { checkIsInitializing(); return super.getWritableDatabase(); } @Override public ConnectionSource getConnectionSource() { checkIsInitializing(); return super.getConnectionSource(); } private void checkIsInitializing() { // 此时外部不可以操作数据库,因为还没有创建或升级完成,创建表的时候更不可以调用get方法获取连接,而应该使用方法携带的参数。 if (mCreatingOrUpgrading) throw new IllegalStateException("不能在`onCreate()`或`onUpgrade()`未结束的时候调用本方法。"); } @Override public void onCreate(SQLiteDatabase database, ConnectionSource connSource) { L.d(TAG, "onCreate--------"); mCreatingOrUpgrading = true; // 先创建其它的,比如 Api 缓存表。 onCreateOthers(database, connSource); /* 过滤接口数据缓存表(虽然无法创建与接口数据缓存表相同的类名,但是可以通过注解指定相同的表名称。 * 下面的创建语句已经实现了过滤,这里省略)*/ for (Class<?> clazz : getTableClasses()) { try { TableUtils.createTableIfNotExists(connSource, clazz); } catch (SQLException e) { e.printStackTrace(); } } mCreatingOrUpgrading = false; L.d(TAG, "onCreate------END"); } @Override public void onUpgrade(SQLiteDatabase database, ConnectionSource connSource, int oldVersion, int newVersion) { mCreatingOrUpgrading = true; L.i(TAG, "Tables In DB: "); // 读取旧表信息 Map<String, String> oldTableSqls = getOldTableSqls(database, false, null); // 没有旧表,直接创建 if (oldTableSqls == null || oldTableSqls.size() == 0) { onCreate(database, connSource); } else { // 先升级其它的,比如 Api 缓存表。 Set<String> otherTableNames = onUpgradeOthers(database, connSource, oldVersion, newVersion, oldTableSqls); if (otherTableNames != null) for (String other : otherTableNames) { oldTableSqls.remove(other); } L.i(TAG, "New Tables: "); Set<Class<?>> tables = getTableClasses(); if (tables == null || tables.size() == 0) { // 删除所有旧表 deleteTables(database, oldTableSqls.keySet().toArray(new String[oldTableSqls.size()])); L.w(TAG, "更新版本:新数据库表列表为空,将清空所有旧表。oldVersion: %s, newVersion: %s.", oldVersion, newVersion); } else { Map<String, Class<?>> newTables = new HashMap<>(tables.size()); Map<String, String> newTableSqls = new HashMap<>(tables.size()); makeNewTableSqls(connSource, tables, newTables, newTableSqls, true, otherTableNames); L.i(TAG, "Upgrade Tables: "); Set<String> nameKeys = newTableSqls.keySet(); String createSql, oldSql; final IUpgradeStrategy upgradeStrategy = getUpgradeStrategy(); for (String name : nameKeys) { createSql = newTableSqls.get(name); oldSql = oldTableSqls.remove(name); if (oldSql == null) { // 简化处理,只有表名相同的才进行升级,最终没有匹配的旧表将被删除,新表会全部创建 // 旧表不存在。这里先不创建新表,最后一次性创建 continue; } if (createSql.equals(oldSql)) { //表结构没有变更,不用导数据 L.i(TAG, "Upgrade Tables。表结构没有变更: %s.", L.s(name)); // newTableSqls不删除,需要在最后再执行一遍创建,因为TableUtils.getCreateTableStatements()返回是是一个list。 continue; // 表结构相同,不用执行升级操作 } else { if (upgradeStrategy.needSaveOldTableData(oldVersion, name, newTables.get(name))) { // 导数据 upgradeTable(database, connSource, newTables.get(name), name, oldSql, createSql); upgradeStrategy.onTableUpgraded(name, false); } else { // 删除旧表 deleteTable(database, name); upgradeStrategy.onTableUpgraded(name, true); } } } // 删除多余的旧表 deleteTables(database, oldTableSqls.keySet().toArray(new String[oldTableSqls.size()])); // 创建所有没有创建的表,避免遗漏 onCreate(database, connSource); } } mCreatingOrUpgrading = false; } private Map<String, String> getOldTableSqls(SQLiteDatabase database, boolean except, Set<String> exceptTableNames) { Map<String, String> sqls = null; String createSql; String tableName; Cursor cursor = database.query("sqlite_master", new String[]{"sql"}, "type='table'", null, null, null, "tbl_name"); if (cursor != null) { sqls = new HashMap<>(cursor.getCount()); while (cursor.moveToNext()) { createSql = cursor.getString(0).trim(); tableName = parseTableNameInSql(createSql, except, exceptTableNames); if (tableName == null) continue; //注意有些是系统表 sqls.put(tableName, createSql); L.i(TAG, "TableName: %s, SQL: %s.", L.s(tableName), L.s(createSql)); } cursor.close(); } return sqls; } private void makeNewTableSqls(ConnectionSource connSource, Set<Class<?>> tables, Map<String, Class<?>> newTables, Map<String, String> newTableSqls, boolean except, Set<String> exceptTableNames) { List<String> statements; String tableName; for (Class<?> clazz : tables) { try { // 为什么是个List,暂时忽略,测试只看到一个元素,即创建表的语句。 statements = TableUtils.getCreateTableStatements(connSource, clazz); if (statements != null) { for (String sql : statements) { sql = sql.trim(); //trim()很重要 tableName = parseTableNameInSql(sql, except, exceptTableNames); if (tableName == null) continue; newTableSqls.put(tableName, sql); newTables.put(tableName, clazz); L.i(TAG, "Table Class: %s, TableName: %s, SQL: %s.", L.s(clazz.getSimpleName()), L.s(tableName), L.s(sql)); } } } catch (SQLException e) { L.e(TAG, e, "Table Class: %s.", L.s(clazz.getSimpleName())); } } } /** * 导数据。查询数据到内存,删除旧表,创建新表,写入数据。 */ protected static void upgradeTable(SQLiteDatabase database, ConnectionSource connSource, Class<?> tableClazz, String name, String oldSql, String createSql) { L.i(TAG, "[upgradeTable start]Table: %s.", L.s(name)); String[] fields = getSameFields(oldSql, createSql); if (fields == null || fields.length == 0) return; StringBuilder fstr = new StringBuilder(); boolean b = false; for (String s : fields) { if (b) { fstr.append(", "); } else { b = true; } fstr.append(DOT); fstr.append(s); fstr.append(DOT); } String name_backup = DOT + name + "_backup" + DOT; name = DOT + name + DOT; // 以下事务是官方写法 database.beginTransaction(); try { // 导入有效数据 // database.execSQL("CREATE TEMPORARY TABLE " + name_backup + "(" + fstr + ")"); // database.execSQL("INSERT INTO " + name_backup + " SELECT " + fstr + " FROM " + name); // database.execSQL("DROP TABLE " + name); database.execSQL("ALTER TABLE " + name + " RENAME TO " + name_backup); TableUtils.createTable(connSource, tableClazz); database.execSQL("INSERT INTO " + name + "(" + fstr + ")" + " SELECT " + fstr + " FROM " + name_backup); database.execSQL("DROP TABLE " + name_backup); database.setTransactionSuccessful(); L.i(TAG, "[upgradeTable Successful]Table: %s.", L.s(name)); } catch (Exception e) { database.execSQL("DROP TABLE " + name); L.i(TAG, e, "[upgradeTable Exception][SQL]DROP TABLE %s.", L.s(name)); } finally { database.endTransaction(); } } protected static void deleteTables(SQLiteDatabase database, String[] tableNames) { for (String table : tableNames) { deleteTable(database, table); } } protected static void deleteTable(SQLiteDatabase database, String tableName) { tableName = DOT + tableName + DOT; String sql = "DROP TABLE IF EXISTS " + tableName; L.w(TAG, "[deleteTable][SQL]%s.", L.s(sql)); database.execSQL(sql); } protected static String parseTableNameInSql(String createSql, boolean except, Set<String> exceptTableNames) { if (!createSql.substring(0, 12).equalsIgnoreCase("CREATE TABLE")) { L.i(TAG, "[getTableName] not create SQL: %s.", L.s(createSql)); return null; } int $ = createSql.indexOf('('); // 注意有可能是CREATE TABLE IF NOT EXISTS String sys = createSql.substring(0, $); if (sys.contains("android_") || sys.contains("sqlite_") || sys.contains("metadata")) { L.i(TAG, "[getTableName] systable SQL: %s.", L.s(createSql)); return null; } int s = createSql.indexOf(DOT) + 1; int e = createSql.indexOf(DOT, s); if (e <= 0 || e > $) { // 系统表中没有这些字符 L.i(TAG, "[getTableName]Index s: %s, e: %s, SQL: %s.", s, e, L.s(createSql)); return null; } String name = createSql.substring(s, e); if (except && exceptTableNames.contains(name)) { L.i(TAG, "[getTableName] except exceptNames: %s.", exceptTableNames); return null; } return name; } private static String[] getSameFields(String oldSql, String createSql) { List<String> list = new LinkedList<>(); oldSql = oldSql.substring(oldSql.indexOf('(') + 1, oldSql.indexOf(')')); createSql = createSql.substring(createSql.indexOf('(') + 1, createSql.indexOf(')')); String[] oldFields = oldSql.split(","); String[] newFields = createSql.split(","); for (int i = 0; i < 2; i++) { String[] arr = i == 0 ? oldFields : newFields; for (int j = 0; j < arr.length; j++) { arr[j] = arr[j].trim(); } } if (oldFields.length > newFields.length) { String[] arr = newFields; newFields = oldFields; oldFields = arr; } List<String> list2 = new LinkedList<>(); Collections.addAll(list2, oldFields); String fieldName; for (String s : newFields) { for (int i = 0, len = list2.size(); i < len; i++) { if (s.equalsIgnoreCase(list2.get(i))) { fieldName = parseFieldName(s); if (fieldName != null && fieldName.length() > 0) list.add(fieldName); list2.remove(i); break; } } } return list.toArray(new String[list.size()]); } private static String parseFieldName(String field) { String result; int index = field.indexOf(DOT); if (index >= 0) { int $index = field.indexOf('('); if ($index >= 0 && $index < index) { // PRIMARY KEY (`key_param`) result = null; L.i(TAG, "[parseFieldName] 带有括号(``): %s.", L.s(field)); } else { index++; result = field.substring(index, field.indexOf(DOT, index)); } } else { char firstChar = field.charAt(0); if (firstChar >= 'A' && firstChar <= 'Z') { // 数据库关键字 result = null; L.i(TAG, "[parseFieldName] 数据库关键字开头:%s.", firstChar); } else { result = field.split(" ")[0].trim(); } } L.i(TAG, "[parseFieldName] result: %s.", L.s(result)); return result; } public static char DOT = '`'; }
/* * Constellation - An open source and standard compliant SDI * http://www.constellation-sdi.org * * Copyright 2018 Geomatys. * * 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.constellation.dto; import java.io.Serializable; import java.util.Date; import java.util.Objects; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Guilhem Legal (Geomatys) */ @XmlRootElement public class Data implements Serializable { private Integer id; private String name; private String namespace; private Integer providerId; private String type; private String subtype; private Boolean included; private Boolean sensorable; private Date date; private Integer ownerId; private String metadata; private Integer datasetId; private String statsResult; private Boolean rendered; private String statsState; private Boolean hidden; public Data() { } public Data( Integer id, String name, String namespace, Integer providerId, String type, String subtype, Boolean included, Boolean sensorable, Date date, Integer ownerId, String metadata, Integer datasetId, String statsResult, Boolean rendered, String statsState, Boolean hidden) { this.id = id; this.name = name; this.namespace = namespace; this.providerId = providerId; this.type = type; this.subtype = subtype; this.included = included; this.sensorable = sensorable; this.date = date; this.ownerId = ownerId; this.metadata = metadata; this.datasetId = datasetId; this.statsResult = statsResult; this.rendered = rendered; this.statsState = statsState; this.hidden = hidden; } public Data(Data data) { if (data != null) { this.id = data.id; this.name = data.name; this.namespace = data.namespace; this.providerId = data.providerId; this.type = data.type; this.subtype = data.subtype; this.included = data.included; this.sensorable = data.sensorable; this.date = data.date; this.ownerId = data.ownerId; this.metadata = data.metadata; this.datasetId = data.datasetId; this.statsResult = data.statsResult; this.rendered = data.rendered; this.statsState = data.statsState; this.hidden = data.hidden; } } /** * @return the id */ public Integer getId() { return id; } /** * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the namespace */ public String getNamespace() { return namespace; } /** * @param namespace the namespace to set */ public void setNamespace(String namespace) { this.namespace = namespace; } /** * @return the provider */ public Integer getProviderId() { return providerId; } /** * @param providerId the provider identifier to set */ public void setProviderId(Integer providerId) { this.providerId = providerId; } /** * @return the type */ public String getType() { return type; } /** * @param type the type to set */ public void setType(String type) { this.type = type; } /** * @return the subtype */ public String getSubtype() { return subtype; } /** * @param subtype the subtype to set */ public void setSubtype(String subtype) { this.subtype = subtype; } /** * @return the included */ public Boolean getIncluded() { return included; } /** * @param included the included to set */ public void setIncluded(Boolean included) { this.included = included; } /** * @return the sensorable */ public Boolean getSensorable() { return sensorable; } /** * @param sensorable the sensorable to set */ public void setSensorable(Boolean sensorable) { this.sensorable = sensorable; } /** * @return the date */ public Date getDate() { return date; } /** * @param date the date to set */ public void setDate(Date date) { this.date = date; } /** * @return the owner */ public Integer getOwnerId() { return ownerId; } /** * @param ownerId the owner Identifier to set */ public void setOwnerId(Integer ownerId) { this.ownerId = ownerId; } /** * @return the metadata */ public String getMetadata() { return metadata; } /** * @param metadata the metadata to set */ public void setMetadata(String metadata) { this.metadata = metadata; } /** * @return the datasetId */ public Integer getDatasetId() { return datasetId; } /** * @param datasetId the datasetId to set */ public void setDatasetId(Integer datasetId) { this.datasetId = datasetId; } /** * @return the statsResult */ public String getStatsResult() { return statsResult; } /** * @param statsResult the statsResult to set */ public void setStatsResult(String statsResult) { this.statsResult = statsResult; } /** * @return the rendered */ public Boolean getRendered() { return rendered; } /** * @param rendered the rendered to set */ public void setRendered(Boolean rendered) { this.rendered = rendered; } /** * @return the statsState */ public String getStatsState() { return statsState; } /** * @param statsState the statsState to set */ public void setStatsState(String statsState) { this.statsState = statsState; } /** * @return the hidden */ public Boolean getHidden() { return hidden; } /** * @param hidden the hidden to set */ public void setHidden(Boolean hidden) { this.hidden = hidden; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Data) { Data that = (Data) obj; return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name) && Objects.equals(this.namespace, that.namespace) && Objects.equals(this.providerId, that.providerId) && Objects.equals(this.type, that.type) && Objects.equals(this.subtype, that.subtype) && Objects.equals(this.included, that.included) && Objects.equals(this.sensorable, that.sensorable) && Objects.equals(this.date, that.date) && Objects.equals(this.ownerId, that.ownerId) && Objects.equals(this.metadata, that.metadata) && Objects.equals(this.datasetId, that.datasetId) && Objects.equals(this.statsResult, that.statsResult) && Objects.equals(this.rendered, that.rendered) && Objects.equals(this.statsState, that.statsState) && Objects.equals(this.hidden, that.hidden); } return false; } @Override public int hashCode() { int hash = 7; hash = 71 * hash + Objects.hashCode(this.id); hash = 71 * hash + Objects.hashCode(this.name); hash = 71 * hash + Objects.hashCode(this.namespace); hash = 71 * hash + Objects.hashCode(this.providerId); hash = 71 * hash + Objects.hashCode(this.type); hash = 71 * hash + Objects.hashCode(this.subtype); hash = 71 * hash + Objects.hashCode(this.included); hash = 71 * hash + Objects.hashCode(this.sensorable); hash = 71 * hash + Objects.hashCode(this.date); hash = 71 * hash + Objects.hashCode(this.ownerId); hash = 71 * hash + Objects.hashCode(this.metadata); hash = 71 * hash + Objects.hashCode(this.datasetId); hash = 71 * hash + Objects.hashCode(this.statsResult); hash = 71 * hash + Objects.hashCode(this.rendered); hash = 71 * hash + Objects.hashCode(this.statsState); hash = 71 * hash + Objects.hashCode(this.hidden); return hash; } }
package io.aurorasolutions.assertions.contracts; public interface ComplexClassTester<Self, ObjectCreationModelType> extends ClassTester<Self> { Self createObjectUsingModel(ObjectCreationModelType model); }
package org.knowm.xchange.deribit.v2.service; import java.io.IOException; import java.math.BigDecimal; import java.util.Date; import java.util.List; import org.knowm.xchange.deribit.v2.DeribitExchange; import org.knowm.xchange.deribit.v2.dto.trade.AdvancedOptions; import org.knowm.xchange.deribit.v2.dto.trade.Order; import org.knowm.xchange.deribit.v2.dto.trade.OrderPlacement; import org.knowm.xchange.deribit.v2.dto.trade.OrderType; import org.knowm.xchange.deribit.v2.dto.trade.TimeInForce; import org.knowm.xchange.deribit.v2.dto.trade.Trigger; import org.knowm.xchange.deribit.v2.dto.trade.UserTrades; public class DeribitTradeServiceRaw extends DeribitBaseService { public DeribitTradeServiceRaw(DeribitExchange exchange) { super(exchange); } public OrderPlacement buy( String instrumentName, BigDecimal amount, OrderType type, String label, BigDecimal price, TimeInForce timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, Trigger trigger, AdvancedOptions advanced) throws IOException { return deribitAuthenticated .buy( instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced, deribitAuth) .getResult(); } public OrderPlacement sell( String instrumentName, BigDecimal amount, OrderType type, String label, BigDecimal price, TimeInForce timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, Trigger trigger, AdvancedOptions advanced) throws IOException { return deribitAuthenticated .sell( instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced, deribitAuth) .getResult(); } public Order cancel(String orderId) throws IOException { return deribitAuthenticated.cancel(orderId, deribitAuth).getResult(); } public List<Order> getOpenOrdersByInstrument(String instrumentName, String type) throws IOException { return deribitAuthenticated .getOpenOrdersByInstrument(instrumentName, type, deribitAuth) .getResult(); } public UserTrades getUserTradesByInstrument( String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting) throws IOException { return deribitAuthenticated .getUserTradesByInstrument( instrumentName, startSeq, endSeq, count, includeOld, sorting, deribitAuth) .getResult(); } public UserTrades getUserTradesByInstrumentAndTime( String instrumentName, Date startTimestsamp, Date endTimestamp, Integer count, Boolean includeOld, String sorting) throws IOException { return deribitAuthenticated .getUserTradesByInstrumentAndTime( instrumentName, startTimestsamp.getTime(), endTimestamp.getTime(), count, includeOld, sorting, deribitAuth) .getResult(); } }
package designpattern.statuspatern.work; /** * 事件定义 * 用来驱动流程流转 */ public enum Event { NEXT_STEP("下一步"), PREVIOUS_STEP("上一步"), APPROVE("同意"), REFUSE("拒绝"); private String value; Event(String value) { this.value = value; } public String getValue() { return value; } }
package com.ggbwallet.app.service; import android.Manifest; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.media.AudioAttributes; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import androidx.core.app.NotificationCompat; import androidx.core.content.ContextCompat; import com.ggbwallet.app.C; import com.ggbwallet.app.R; import com.ggbwallet.app.ui.HomeActivity; /** * Created by James on 25/04/2019. * Stormbird in Sydney */ public class NotificationService { private final Context context; private final String CHANNEL_ID = "ALPHAWALLET CHANNEL"; private final int NOTIFICATION_ID = 314151024; public static final String AWSTARTUP = "AW://"; public NotificationService(Context ctx) { context = ctx; createNotificationChannel(); } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); AudioAttributes attr = new AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .setUsage(AudioAttributes.USAGE_NOTIFICATION) .build(); CharSequence name = context.getString(R.string.app_name); String description = context.getString(R.string.channel_description); int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); channel.setDescription(description); channel.setSound(notification, attr); // Register the channel with the system; you can't change the importance // or other notification behaviors after this NotificationManager notificationManager = context.getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } } void DisplayNotification(String title, String content, int priority) { checkNotificationPermission(); int color = context.getColor(R.color.holo_blue); Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Intent openAppIntent = new Intent(context, HomeActivity.class); openAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); //openAppIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); openAppIntent.setData(Uri.parse(AWSTARTUP + content)); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, openAppIntent, PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_alpha_notification) .setColor(color) .setContentTitle(title) .setContentText(content) .setSound(notification, 1) .setAutoCancel(true) .setOngoing(true) .setCategory(NotificationCompat.CATEGORY_EVENT) .setContentIntent(contentIntent) .setPriority(priority); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) notificationManager.notify(NOTIFICATION_ID, builder.build()); } private void checkNotificationPermission() { if (!(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_NOTIFICATION_POLICY) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_NOTIFICATION_POLICY) != PackageManager.PERMISSION_DENIED)) { Intent intent = new Intent(C.REQUEST_NOTIFICATION_ACCESS); context.sendBroadcast(intent); } } }
package ee.joonasvali.mirrors.scene; import java.awt.*; public class Accelerator extends RoundPhysical implements Collidable { private double acceleration; public Accelerator(double x, double y, double rotation, double radius, double acceleration) { super(x, y, rotation, radius); this.acceleration = acceleration; } @Override public boolean isCollision(Particle particle) { return CollisionUtil.areColliding(this, particle.getX(), particle.getY()); } @Override public void actCollision(Particle particle, Model model) { particle.setSpeed(particle.getSpeed() + acceleration); } @Override public void render(Graphics2D g) { if (acceleration > 0) { g.setColor(Color.green); } else g.setColor(Color.yellow); g.drawOval((int) getX(), (int) getY(), (int) getWidth(), (int) getHeight()); g.drawString(String.format("%.1f", acceleration), (float) getCenterX() - 10, (float) getCenterY() - 10); } }
package org.liberty.android.fantastischmemo.dao; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.DatabaseTableConfig; import org.liberty.android.fantastischmemo.entity.Setting; import java.sql.SQLException; public class SettingDaoImpl extends AbstractHelperDaoImpl<Setting, Integer> implements SettingDao { public SettingDaoImpl(ConnectionSource connectionSource, DatabaseTableConfig<Setting> config) throws SQLException { super(connectionSource, config); } public SettingDaoImpl(ConnectionSource connectionSource, Class<Setting> clazz) throws SQLException { super(connectionSource, clazz); } public void replaceSetting(Setting settings) { try { deleteById(1); create(settings); updateId(settings, 1); } catch (SQLException e) { throw new RuntimeException("Error replacing settings", e); } } }
package fr.smartberry; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; //@SpringBootApplication //public class Main { // // public static void main(String[] args) { // SpringApplication.run(Main.class, args); // } //}
/* * Copyright 2016 Dhatim. * * 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.dhatim.fastexcel.benchmarks; import com.monitorjbl.xlsx.StreamingReader; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable; import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler; import org.apache.poi.xssf.model.StylesTable; import org.apache.poi.xssf.usermodel.XSSFComment; import org.dhatim.fastexcel.reader.ReadableWorkbook; import org.dhatim.fastexcel.reader.Row; import org.dhatim.fastexcel.reader.Sheet; import org.openjdk.jmh.annotations.Benchmark; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.IOException; import java.io.InputStream; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static org.junit.jupiter.api.Assertions.assertEquals; public class ReaderBenchmark extends BenchmarkLauncher { private static final long RESULT = 2147385345; private static class SheetContentHandler implements XSSFSheetXMLHandler.SheetContentsHandler { private long result = 0; @Override public void startRow(int rowNum) { //Do nothing } @Override public void endRow(int rowNum) { //Do nothing } @Override public void cell(String cellReference, String formattedValue, XSSFComment comment) { CellReference ref = new CellReference(cellReference); if (ref.getRow() > 0 && ref.getCol() == 0) { result += Double.parseDouble(formattedValue); } } @Override public void headerFooter(String text, boolean isHeader, String tagName) { //Do nothing } } private static final String FILE = "/xlsx/calendar_stress_test.xlsx"; @Benchmark public long apachePoi() throws IOException { try (Workbook wb = WorkbookFactory.create(openResource(FILE))) { org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(0); long sum = StreamSupport.stream( Spliterators.spliteratorUnknownSize(sheet.rowIterator(), Spliterator.ORDERED), false ).skip(1).mapToLong(r -> (long) r.getCell(0).getNumericCellValue()).sum(); assertEquals(RESULT, sum); return sum; } } @Benchmark public long fastExcelReader() throws IOException { try (InputStream is = openResource(FILE); ReadableWorkbook wb = new ReadableWorkbook(is)) { Sheet sheet = wb.getFirstSheet(); try (Stream<Row> rows = sheet.openStream()) { long sum = rows.skip(1).mapToLong(r -> r.getCell(0).asNumber().longValue()).sum(); assertEquals(RESULT, sum); return sum; } } } @Benchmark public int streamingApachePoi() throws IOException, OpenXML4JException, SAXException { try (OPCPackage pkg = OPCPackage.open(openResource(FILE))) { ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(pkg); XSSFReader reader = new XSSFReader(pkg); StylesTable styles = reader.getStylesTable(); XSSFReader.SheetIterator iterator = (XSSFReader.SheetIterator) reader.getSheetsData(); int sheetIndex = 0; while (iterator.hasNext()) { try (InputStream sheetStream = iterator.next()) { if (sheetIndex == 0) { SheetContentHandler sheetHandler = new SheetContentHandler(); processSheet(styles, strings, sheetHandler, sheetStream); assertEquals(RESULT, sheetHandler.result); } } sheetIndex++; } return sheetIndex; } } private void processSheet(StylesTable styles, ReadOnlySharedStringsTable strings, XSSFSheetXMLHandler.SheetContentsHandler sheetHandler, InputStream sheetInputStream) throws IOException, SAXException { DataFormatter formatter = new DataFormatter(); InputSource sheetSource = new InputSource(sheetInputStream); SAXParserFactory saxFactory = SAXParserFactory.newInstance(); saxFactory.setNamespaceAware(true); try { SAXParser saxParser = saxFactory.newSAXParser(); XMLReader sheetParser = saxParser.getXMLReader(); ContentHandler handler = new XSSFSheetXMLHandler( styles, null, strings, sheetHandler, formatter, false); sheetParser.setContentHandler(handler); sheetParser.parse(sheetSource); } catch (ParserConfigurationException e) { throw new IllegalStateException("SAX parser appears to be broken - " + e.getMessage()); } } @Benchmark public long monitorjbl() throws IOException { long sum = 0; try (InputStream is = openResource(FILE); org.apache.poi.ss.usermodel.Workbook workbook = StreamingReader.builder().open(is)) { for (org.apache.poi.ss.usermodel.Sheet sheet : workbook) { for (org.apache.poi.ss.usermodel.Row r : sheet) { if (r.getRowNum() == 0) { continue; } sum += r.getCell(0).getNumericCellValue(); } } } assertEquals(RESULT, sum); return sum; } private static InputStream openResource(String name) { InputStream result = ReaderBenchmark.class.getResourceAsStream(name); if (result == null) { throw new IllegalStateException("Cannot read resource " + name); } return result; } }
package com.nai.gulimall.order.controller; import com.nai.gulimall.common.utils.PageUtils; import com.nai.gulimall.common.utils.R; import com.nai.gulimall.order.entity.OrderSettingEntity; import com.nai.gulimall.order.service.OrderSettingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Arrays; import java.util.Map; /** * 订单配置信息 * * @author TheNai * @email TheNai@gmail.com * @date 2021-02-06 22:44:51 */ @RestController @RequestMapping("order/orderSetting") public class OrderSettingController { @Autowired private OrderSettingService orderSettingService; /** * 列表 */ @RequestMapping("/list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = orderSettingService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") public R info(@PathVariable("id") Long id){ OrderSettingEntity orderSetting = orderSettingService.getById(id); return R.ok().put("orderSetting", orderSetting); } /** * 保存 */ @RequestMapping("/save") public R save(@RequestBody OrderSettingEntity orderSetting){ orderSettingService.save(orderSetting); return R.ok(); } /** * 修改 */ @RequestMapping("/update") public R update(@RequestBody OrderSettingEntity orderSetting){ orderSettingService.updateById(orderSetting); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") public R delete(@RequestBody Long[] ids){ orderSettingService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
import java.util.List; import java.util.*; class BuilderGenericMethod<T> { public <N extends Number> Map<N, T> foo(int a, long b) { return null; } @java.lang.SuppressWarnings("all") public class MapBuilder<N extends Number> { @java.lang.SuppressWarnings("all") private int a; @java.lang.SuppressWarnings("all") private long b; @java.lang.SuppressWarnings("all") MapBuilder() { } @java.lang.SuppressWarnings("all") public MapBuilder<N> a(final int a) { this.a = a; return this; } @java.lang.SuppressWarnings("all") public MapBuilder<N> b(final long b) { this.b = b; return this; } @java.lang.SuppressWarnings("all") public Map<N, T> build() { return BuilderGenericMethod.this.<N>foo(a, b); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "BuilderGenericMethod.MapBuilder(a=" + this.a + ", b=" + this.b + ")"; } } @java.lang.SuppressWarnings("all") public <N extends Number> MapBuilder<N> builder() { return new MapBuilder<N>(); } }
/* * Copyright (c) 2016, baihw (javakf@163.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.yoya.sql.impl; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import com.yoya.sql.IRecord; import org.apache.commons.dbutils.ResultSetHandler; /** * Created by baihw on 16-4-20. * * Record结果集处理器。 */ final class RecordHandler implements ResultSetHandler<IRecord>{ @Override public IRecord handle( ResultSet rs ) throws SQLException{ ResultSetMetaData rsmd = rs.getMetaData(); int cols = rsmd.getColumnCount(); if( rs.next() ){ IRecord record = new SimpleRecord(); for( int i = 1; i <= cols; i++ ){ String columnName = rsmd.getColumnLabel( i ); if( null == columnName || 0 == columnName.length() ){ columnName = rsmd.getColumnName( i ); } record.put( columnName, rs.getObject( i ) ); } return record; } return null; } }
package me.caprei.crazyctf.classes; public class Soldier extends CTFClass { public Soldier(){ } @Override public void setWearableItems() { } @Override public void setInventoryItems() { // TODO Auto-generated method stub } @Override public void setAbilities() { // TODO Auto-generated method stub } }
package com.laegler.openbanking.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.*; /** * Set of elements used to provide details of a generic number value related to the statement resource. */ @ApiModel(description = "Set of elements used to provide details of a generic number value related to the statement resource.") @Validated @javax.annotation.Generated(value = "class com.laegler.openbanking.codegen.language.OpenbankingModelCodegen", date = "2019-10-19T07:45:56.431+13:00") public class OBStatement2StatementValue { @JsonProperty("Type") private String type = null; @JsonProperty("Value") private String value = null; public OBStatement2StatementValue type(String type) { this.type = type; return this; } /** * Get type * @return type **/ @ApiModelProperty(required = true, value = "") @NotNull @Size(min=1,max=40) public String getType() { return type; } public void setType(String type) { this.type = type; } public OBStatement2StatementValue value(String value) { this.value = value; return this; } /** * Get value * @return value **/ @ApiModelProperty(required = true, value = "") @NotNull public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OBStatement2StatementValue obStatement2StatementValue = (OBStatement2StatementValue) o; return Objects.equals(this.type, obStatement2StatementValue.type) && Objects.equals(this.value, obStatement2StatementValue.value); } @Override public int hashCode() { return Objects.hash(type, value); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OBStatement2StatementValue {\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" value: ").append(toIndentedString(value)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.jbpm.process.instance; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.impl.StatefulKnowledgeSessionImpl; import org.drools.core.runtime.process.ProcessRuntimeFactoryService; public class ProcessRuntimeFactoryServiceImpl implements ProcessRuntimeFactoryService { public InternalProcessRuntime newProcessRuntime(InternalWorkingMemory workingMemory) { return new ProcessRuntimeImpl(workingMemory); } }
/** * Copyright 2019 ForgeRock AS. * * 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. */ /* * Payment Initiation API * Swagger for Payment Initiation API Specification * * OpenAPI spec version: v3.1.3-RC1 * Contact: ServiceDesk@openbanking.org.uk * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package uk.org.openbanking.datamodel.payment; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * OBWriteInternationalScheduledResponse4Data */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2020-05-19T11:45:24.725+01:00") public class OBWriteInternationalScheduledResponse4Data { @JsonProperty("InternationalScheduledPaymentId") private String internationalScheduledPaymentId = null; @JsonProperty("ConsentId") private String consentId = null; @JsonProperty("CreationDateTime") private DateTime creationDateTime = null; /** * Specifies the status of the payment order resource. */ public enum StatusEnum { CANCELLED("Cancelled"), INITIATIONCOMPLETED("InitiationCompleted"), INITIATIONFAILED("InitiationFailed"), INITIATIONPENDING("InitiationPending"); private String value; StatusEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static StatusEnum fromValue(String text) { for (StatusEnum b : StatusEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } } @JsonProperty("Status") private StatusEnum status = null; @JsonProperty("StatusUpdateDateTime") private DateTime statusUpdateDateTime = null; @JsonProperty("ExpectedExecutionDateTime") private DateTime expectedExecutionDateTime = null; @JsonProperty("ExpectedSettlementDateTime") private DateTime expectedSettlementDateTime = null; @JsonProperty("Charges") private List<OBWriteDomesticConsentResponse3DataCharges> charges = null; @JsonProperty("ExchangeRateInformation") private OBWriteInternationalConsentResponse4DataExchangeRateInformation exchangeRateInformation = null; @JsonProperty("Initiation") private OBWriteInternationalScheduled3DataInitiation initiation = null; @JsonProperty("MultiAuthorisation") private OBWriteDomesticResponse3DataMultiAuthorisation multiAuthorisation = null; public OBWriteInternationalScheduledResponse4Data internationalScheduledPaymentId(String internationalScheduledPaymentId) { this.internationalScheduledPaymentId = internationalScheduledPaymentId; return this; } /** * OB: Unique identification as assigned by the ASPSP to uniquely identify the international scheduled payment resource. * * @return internationalScheduledPaymentId **/ @NotNull @Size(min = 1, max = 40) @ApiModelProperty(required = true, value = "OB: Unique identification as assigned by the ASPSP to uniquely identify the international scheduled payment resource.") public String getInternationalScheduledPaymentId() { return internationalScheduledPaymentId; } public void setInternationalScheduledPaymentId(String internationalScheduledPaymentId) { this.internationalScheduledPaymentId = internationalScheduledPaymentId; } public OBWriteInternationalScheduledResponse4Data consentId(String consentId) { this.consentId = consentId; return this; } /** * OB: Unique identification as assigned by the ASPSP to uniquely identify the consent resource. * * @return consentId **/ @NotNull @Size(min = 1, max = 128) @ApiModelProperty(required = true, value = "OB: Unique identification as assigned by the ASPSP to uniquely identify the consent resource.") public String getConsentId() { return consentId; } public void setConsentId(String consentId) { this.consentId = consentId; } public OBWriteInternationalScheduledResponse4Data creationDateTime(DateTime creationDateTime) { this.creationDateTime = creationDateTime; return this; } /** * Date and time at which the message was created.All dates in the JSON payloads are represented in ISO 8601 date-time format. All date-time fields in responses must include the timezone. An example is below: 2017-04-05T10:43:07+00:00 * * @return creationDateTime **/ @NotNull @Valid @ApiModelProperty(required = true, value = "Date and time at which the message was created.All dates in the JSON payloads are represented in ISO 8601 date-time format. All date-time fields in responses must include the timezone. An example is below: 2017-04-05T10:43:07+00:00") public DateTime getCreationDateTime() { return creationDateTime; } public void setCreationDateTime(DateTime creationDateTime) { this.creationDateTime = creationDateTime; } public OBWriteInternationalScheduledResponse4Data status(StatusEnum status) { this.status = status; return this; } /** * Specifies the status of the payment order resource. * * @return status **/ @NotNull @ApiModelProperty(required = true, value = "Specifies the status of the payment order resource.") public StatusEnum getStatus() { return status; } public void setStatus(StatusEnum status) { this.status = status; } public OBWriteInternationalScheduledResponse4Data statusUpdateDateTime(DateTime statusUpdateDateTime) { this.statusUpdateDateTime = statusUpdateDateTime; return this; } /** * Date and time at which the resource status was updated.All dates in the JSON payloads are represented in ISO 8601 date-time format. All date-time fields in responses must include the timezone. An example is below: 2017-04-05T10:43:07+00:00 * * @return statusUpdateDateTime **/ @NotNull @Valid @ApiModelProperty(required = true, value = "Date and time at which the resource status was updated.All dates in the JSON payloads are represented in ISO 8601 date-time format. All date-time fields in responses must include the timezone. An example is below: 2017-04-05T10:43:07+00:00") public DateTime getStatusUpdateDateTime() { return statusUpdateDateTime; } public void setStatusUpdateDateTime(DateTime statusUpdateDateTime) { this.statusUpdateDateTime = statusUpdateDateTime; } public OBWriteInternationalScheduledResponse4Data expectedExecutionDateTime(DateTime expectedExecutionDateTime) { this.expectedExecutionDateTime = expectedExecutionDateTime; return this; } /** * Expected execution date and time for the payment resource.All dates in the JSON payloads are represented in ISO 8601 date-time format. All date-time fields in responses must include the timezone. An example is below: 2017-04-05T10:43:07+00:00 * * @return expectedExecutionDateTime **/ @Valid @ApiModelProperty(value = "Expected execution date and time for the payment resource.All dates in the JSON payloads are represented in ISO 8601 date-time format. All date-time fields in responses must include the timezone. An example is below: 2017-04-05T10:43:07+00:00") public DateTime getExpectedExecutionDateTime() { return expectedExecutionDateTime; } public void setExpectedExecutionDateTime(DateTime expectedExecutionDateTime) { this.expectedExecutionDateTime = expectedExecutionDateTime; } public OBWriteInternationalScheduledResponse4Data expectedSettlementDateTime(DateTime expectedSettlementDateTime) { this.expectedSettlementDateTime = expectedSettlementDateTime; return this; } /** * Expected settlement date and time for the payment resource.All dates in the JSON payloads are represented in ISO 8601 date-time format. All date-time fields in responses must include the timezone. An example is below: 2017-04-05T10:43:07+00:00 * * @return expectedSettlementDateTime **/ @Valid @ApiModelProperty(value = "Expected settlement date and time for the payment resource.All dates in the JSON payloads are represented in ISO 8601 date-time format. All date-time fields in responses must include the timezone. An example is below: 2017-04-05T10:43:07+00:00") public DateTime getExpectedSettlementDateTime() { return expectedSettlementDateTime; } public void setExpectedSettlementDateTime(DateTime expectedSettlementDateTime) { this.expectedSettlementDateTime = expectedSettlementDateTime; } public OBWriteInternationalScheduledResponse4Data charges(List<OBWriteDomesticConsentResponse3DataCharges> charges) { this.charges = charges; return this; } public OBWriteInternationalScheduledResponse4Data addChargesItem(OBWriteDomesticConsentResponse3DataCharges chargesItem) { if (this.charges == null) { this.charges = new ArrayList<OBWriteDomesticConsentResponse3DataCharges>(); } this.charges.add(chargesItem); return this; } /** * Get charges * * @return charges **/ @Valid @ApiModelProperty(value = "") public List<OBWriteDomesticConsentResponse3DataCharges> getCharges() { return charges; } public void setCharges(List<OBWriteDomesticConsentResponse3DataCharges> charges) { this.charges = charges; } public OBWriteInternationalScheduledResponse4Data exchangeRateInformation(OBWriteInternationalConsentResponse4DataExchangeRateInformation exchangeRateInformation) { this.exchangeRateInformation = exchangeRateInformation; return this; } /** * Get exchangeRateInformation * * @return exchangeRateInformation **/ @Valid @ApiModelProperty(value = "") public OBWriteInternationalConsentResponse4DataExchangeRateInformation getExchangeRateInformation() { return exchangeRateInformation; } public void setExchangeRateInformation(OBWriteInternationalConsentResponse4DataExchangeRateInformation exchangeRateInformation) { this.exchangeRateInformation = exchangeRateInformation; } public OBWriteInternationalScheduledResponse4Data initiation(OBWriteInternationalScheduled3DataInitiation initiation) { this.initiation = initiation; return this; } /** * Get initiation * * @return initiation **/ @NotNull @Valid @ApiModelProperty(required = true, value = "") public OBWriteInternationalScheduled3DataInitiation getInitiation() { return initiation; } public void setInitiation(OBWriteInternationalScheduled3DataInitiation initiation) { this.initiation = initiation; } public OBWriteInternationalScheduledResponse4Data multiAuthorisation(OBWriteDomesticResponse3DataMultiAuthorisation multiAuthorisation) { this.multiAuthorisation = multiAuthorisation; return this; } /** * Get multiAuthorisation * * @return multiAuthorisation **/ @Valid @ApiModelProperty(value = "") public OBWriteDomesticResponse3DataMultiAuthorisation getMultiAuthorisation() { return multiAuthorisation; } public void setMultiAuthorisation(OBWriteDomesticResponse3DataMultiAuthorisation multiAuthorisation) { this.multiAuthorisation = multiAuthorisation; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OBWriteInternationalScheduledResponse4Data obWriteInternationalScheduledResponse4Data = (OBWriteInternationalScheduledResponse4Data) o; return Objects.equals(this.internationalScheduledPaymentId, obWriteInternationalScheduledResponse4Data.internationalScheduledPaymentId) && Objects.equals(this.consentId, obWriteInternationalScheduledResponse4Data.consentId) && Objects.equals(this.creationDateTime, obWriteInternationalScheduledResponse4Data.creationDateTime) && Objects.equals(this.status, obWriteInternationalScheduledResponse4Data.status) && Objects.equals(this.statusUpdateDateTime, obWriteInternationalScheduledResponse4Data.statusUpdateDateTime) && Objects.equals(this.expectedExecutionDateTime, obWriteInternationalScheduledResponse4Data.expectedExecutionDateTime) && Objects.equals(this.expectedSettlementDateTime, obWriteInternationalScheduledResponse4Data.expectedSettlementDateTime) && Objects.equals(this.charges, obWriteInternationalScheduledResponse4Data.charges) && Objects.equals(this.exchangeRateInformation, obWriteInternationalScheduledResponse4Data.exchangeRateInformation) && Objects.equals(this.initiation, obWriteInternationalScheduledResponse4Data.initiation) && Objects.equals(this.multiAuthorisation, obWriteInternationalScheduledResponse4Data.multiAuthorisation); } @Override public int hashCode() { return Objects.hash(internationalScheduledPaymentId, consentId, creationDateTime, status, statusUpdateDateTime, expectedExecutionDateTime, expectedSettlementDateTime, charges, exchangeRateInformation, initiation, multiAuthorisation); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OBWriteInternationalScheduledResponse4Data {\n"); sb.append(" internationalScheduledPaymentId: ").append(toIndentedString(internationalScheduledPaymentId)).append("\n"); sb.append(" consentId: ").append(toIndentedString(consentId)).append("\n"); sb.append(" creationDateTime: ").append(toIndentedString(creationDateTime)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" statusUpdateDateTime: ").append(toIndentedString(statusUpdateDateTime)).append("\n"); sb.append(" expectedExecutionDateTime: ").append(toIndentedString(expectedExecutionDateTime)).append("\n"); sb.append(" expectedSettlementDateTime: ").append(toIndentedString(expectedSettlementDateTime)).append("\n"); sb.append(" charges: ").append(toIndentedString(charges)).append("\n"); sb.append(" exchangeRateInformation: ").append(toIndentedString(exchangeRateInformation)).append("\n"); sb.append(" initiation: ").append(toIndentedString(initiation)).append("\n"); sb.append(" multiAuthorisation: ").append(toIndentedString(multiAuthorisation)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package com.example.newepisodenotifier; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.curate; import java.sql.SQLException; import org.apache.commons.cli.ParseException; import org.dspace.core.Context; import org.dspace.eperson.EPerson; /** * This is the CLI version of the {@link Curation} script. * This will only be called when the curate script is called from a commandline instance. */ public class CurationCli extends Curation { /** * This is the overridden instance of the {@link Curation#assignCurrentUserInContext()} method in the parent class * {@link Curation}. * This is done so that the CLI version of the Script is able to retrieve its currentUser from the -e flag given * with the parameters of the Script. * @throws ParseException If the e flag was not given to the parameters when calling the script */ @Override protected void assignCurrentUserInContext() throws ParseException { if (this.commandLine.hasOption('e')) { String ePersonEmail = this.commandLine.getOptionValue('e'); this.context = new Context(Context.Mode.BATCH_EDIT); try { EPerson ePerson = ePersonService.findByEmail(this.context, ePersonEmail); if (ePerson == null) { super.handler.logError("EPerson not found: " + ePersonEmail); throw new IllegalArgumentException("Unable to find a user with email: " + ePersonEmail); } this.context.setCurrentUser(ePerson); } catch (SQLException e) { throw new IllegalArgumentException("SQLException trying to find user with email: " + ePersonEmail); } } else { throw new ParseException("Required parameter -e missing!"); } } }
/* * Copyright (C) 2018 The Sylph 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 ideal.sylph.plugins.mysql; import ideal.sylph.annotation.Description; import ideal.sylph.annotation.Name; import ideal.sylph.etl.Collector; import ideal.sylph.etl.Row; import ideal.sylph.etl.api.RealTimeTransForm; import ideal.sylph.etl.join.JoinContext; import ideal.sylph.etl.join.SelectField; import ideal.sylph.plugins.mysql.utils.JdbcUtils; import org.apache.flink.shaded.guava18.com.google.common.cache.Cache; import org.apache.flink.shaded.guava18.com.google.common.cache.CacheBuilder; import org.apache.flink.shaded.guava18.com.google.common.collect.ImmutableList; import org.apache.flink.shaded.guava18.com.google.common.collect.ImmutableMap; import org.apache.flink.shaded.guava18.com.google.common.collect.ImmutableSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static ideal.sylph.etl.join.JoinContext.JoinType.LEFT; import static org.apache.flink.shaded.guava18.com.google.common.base.Preconditions.checkState; /** * 这个例子研究 AsyncFunction机制 */ @Name("mysql") @Description("this is `join mode` mysql config table") public class MysqlAsyncJoin implements RealTimeTransForm { private static final Logger logger = LoggerFactory.getLogger(MysqlAsyncJoin.class); private final List<SelectField> selectFields; private final Map<Integer, String> joinOnMapping; private final String sql; private final JoinContext.JoinType joinType; private final int selectFieldCnt; private final MyJoinConfig config; private final Row.Schema schema; private Connection connection; private Cache<String, List<Map<String, Object>>> cache; public MysqlAsyncJoin(JoinContext context, MyJoinConfig mysqlConfig) throws Exception { this.config = mysqlConfig; this.schema = context.getSchema(); this.selectFields = context.getSelectFields(); this.selectFieldCnt = context.getSelectFieldCnt(); this.joinType = context.getJoinType(); this.joinOnMapping = context.getJoinOnMapping(); String where = context.getJoinOnMapping().values().stream().map(x -> x + " = ?").collect(Collectors.joining(" and ")); List<String> batchFields = context.getSelectFields().stream().filter(SelectField::isBatchTableField) .map(SelectField::getFieldName).collect(Collectors.toList()); String select = "select %s from %s where %s"; String batchSelectFields = batchFields.isEmpty() ? "true" : String.join(",", batchFields); String jdbcTable = config.getQuery() != null && config.getQuery().trim().length() > 0 ? "(" + config.getQuery() + ") as " + context.getBatchTable() : context.getBatchTable(); this.sql = String.format(select, batchSelectFields, jdbcTable, where); checkMysql(mysqlConfig, jdbcTable, ImmutableSet.<String>builder().addAll(batchFields).addAll(context.getJoinOnMapping().values()).build()); logger.info("batch table join query is [{}]", sql); logger.info("join mapping is {}", context.getJoinOnMapping()); this.cache = CacheBuilder.newBuilder() .maximumSize(mysqlConfig.getCacheMaxNumber()) //max cache 1000 value .expireAfterAccess(mysqlConfig.getCacheTime(), TimeUnit.SECONDS) // .build(); } private static void checkMysql(MyJoinConfig config, String tableName, Set<String> fieldNames) throws SQLException { try (Connection connection = DriverManager.getConnection(config.getJdbcUrl(), config.getUser(), config.getPassword()); ResultSet resultSet = connection.getMetaData().getColumns(null, null, tableName, null); ) { List<Map<String, Object>> tableSchema = JdbcUtils.resultToList(resultSet); List<String> listNames = tableSchema.stream().map(x -> (String) x.get("COLUMN_NAME")).collect(Collectors.toList()); checkState(listNames.containsAll(fieldNames), "mysql table `" + tableName + " fields ` only " + listNames + ", but your is " + fieldNames); } } @Override public void process(Row input, Collector<Row> collector) { try { checkState(connection != null, " connection is null"); StringBuilder builder = new StringBuilder(); for (int index : joinOnMapping.keySet()) { builder.append(input.<Object>getField(index)).append("\u0001"); } List<Map<String, Object>> cacheData = cache.get(builder.toString(), () -> { //-- 这里进行真正的数据库查询 List<Integer> indexs = ImmutableList.copyOf(joinOnMapping.keySet()); try (PreparedStatement statement = connection.prepareStatement(sql)) { for (int i = 0; i < indexs.size(); i++) { statement.setObject(i + 1, input.getField(indexs.get(i))); } if (logger.isDebugEnabled()) { logger.debug("Thread is {}, this {}", Thread.currentThread().getId(), this); } try (ResultSet rs = statement.executeQuery()) { List<Map<String, Object>> result = JdbcUtils.resultToList(rs); if (result.isEmpty() && joinType == LEFT) { // left join and inter join return ImmutableList.of(ImmutableMap.of()); } return result; } } catch (SQLException e) { throw new RuntimeException(e); } }); for (Map<String, Object> map : cacheData) { Object[] row = new Object[selectFieldCnt]; for (int i = 0; i < selectFieldCnt; i++) { SelectField field = selectFields.get(i); if (field.isBatchTableField()) { row[i] = map.get(field.getFieldName()); } else { row[i] = input.getField(field.getFieldIndex()); } } collector.collect(Row.of(row)); } } catch (ExecutionException e) { throw new RuntimeException(e); } } @Override public Row.Schema getSchema() { return schema; } @Override public boolean open(long partitionId, long version) throws Exception { //create connection try { Class.forName("com.mysql.jdbc.Driver"); this.connection = DriverManager.getConnection(config.getJdbcUrl(), config.getUser(), config.getPassword()); return true; } catch (SQLException | ClassNotFoundException e) { throw new SQLException("Mysql connection open fail", e); } } @Override public void close(Throwable errorOrNull) { try (Connection conn = connection) { conn.isClosed(); cache.invalidateAll(); } catch (Exception e) { } if (errorOrNull != null) { logger.error("", errorOrNull); } } public static final class MyJoinConfig { @Name("cache.max.number") @Description("this is max cache number") private int maxNumber = 1000; @Name("cache.expire.number") @Description("this is cache expire SECONDS") private int cacheTime = 300; // 5 minutes @Name("url") @Description("this is mysql jdbc url") private String jdbcUrl = "jdbc:mysql://localhost:3306/pop?characterEncoding=utf-8&useSSL=false"; @Name("userName") @Description("this is mysql userName") private String user = "demo"; @Name("password") @Description("this is mysql password") private String password = "demo"; @Name("query") @Description("this is mysql save query") private String query = null; public int getCacheTime() { return cacheTime; } public int getCacheMaxNumber() { return maxNumber; } public String getJdbcUrl() { return jdbcUrl; } public String getUser() { return user; } public String getPassword() { return password; } public String getQuery() { return query; } } }
/* * Copyright (C) 2011 Everit Kft. (http://www.everit.org) * * 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.everit.json.schema.internal; import org.everit.json.schema.FormatValidator; import org.junit.Test; import java.util.Optional; import static org.everit.json.schema.internal.ValidatorTestSupport.assertFailure; import static org.everit.json.schema.internal.ValidatorTestSupport.assertSuccess; public class DefaultFormatValidatorTest { private static final String THERE_IS_NO_PLACE_LIKE = "127.0.0.1"; private static final String IPV6_ADDR = "2001:db8:85a3:0:0:8a2e:370:7334"; @Test public void dateTimeExceedingLimits() { assertFailure("1996-60-999T16:39:57-08:00", new DateTimeFormatValidator(), "[1996-60-999T16:39:57-08:00] is not a valid date-time. " + "Expected [yyyy-MM-dd'T'HH:mm:ssZ, yyyy-MM-dd'T'HH:mm:ss.[0-9]{1,9}Z, yyyy-MM-dd'T'HH:mm:ss[+-]HH:mm, yyyy-MM-dd'T'HH:mm:ss.[0-9]{1,9}[+-]HH:mm]"); } @Test public void dateTimeFormatFailure() { assertFailure("2015-03-13T11:00:000", new DateTimeFormatValidator(), "[2015-03-13T11:00:000] is not a valid date-time. " + "Expected [yyyy-MM-dd'T'HH:mm:ssZ, yyyy-MM-dd'T'HH:mm:ss.[0-9]{1,9}Z, yyyy-MM-dd'T'HH:mm:ss[+-]HH:mm, yyyy-MM-dd'T'HH:mm:ss.[0-9]{1,9}[+-]HH:mm]"); } @Test public void dateTimeWithSingleDigitInSecFracSuccess() { assertSuccess("2015-02-28T11:00:00.1Z", new DateTimeFormatValidator()); } @Test public void dateTimeWithTwoDigitsInSecFracSuccess() { assertSuccess("2015-02-28T11:00:00.12Z", new DateTimeFormatValidator()); } @Test public void dateTimeWithThreeDigitsInSecFracSuccess() { assertSuccess("2015-02-28T11:00:00.123Z", new DateTimeFormatValidator()); } @Test public void dateTimeWithFourDigitsInSecFracSuccess() { assertSuccess("2015-02-28T11:00:00.1234Z", new DateTimeFormatValidator()); } @Test public void dateTimeWithFiveDigitsInSecFracSuccess() { assertSuccess("2015-02-28T11:00:00.12345Z", new DateTimeFormatValidator()); } @Test public void dateTimeWithSixDigitsInSecFracSuccess() { assertSuccess("2015-02-28T11:00:00.123456Z", new DateTimeFormatValidator()); } @Test public void dateTimeWithSevenDigitsInSecFracSuccess() { assertSuccess("2015-02-28T11:00:00.1234567Z", new DateTimeFormatValidator()); } @Test public void dateTimeWithEightDigitsInSecFracSuccess() { assertSuccess("2015-02-28T11:00:00.12345678Z", new DateTimeFormatValidator()); } @Test public void dateTimeWithNineDigitsInSecFracSuccess() { assertSuccess("2015-02-28T11:00:00.123456789Z", new DateTimeFormatValidator()); } @Test public void dateTimeWithTenDigitsInSecFracFailure() { assertFailure("2015-02-28T11:00:00.1234567890Z", new DateTimeFormatValidator(), "[2015-02-28T11:00:00.1234567890Z] is not a valid date-time. " + "Expected [yyyy-MM-dd'T'HH:mm:ssZ, yyyy-MM-dd'T'HH:mm:ss.[0-9]{1,9}Z, yyyy-MM-dd'T'HH:mm:ss[+-]HH:mm, yyyy-MM-dd'T'HH:mm:ss.[0-9]{1,9}[+-]HH:mm]"); } @Test public void dateTimeSuccess() { assertSuccess("2015-03-13T11:00:00+00:00", new DateTimeFormatValidator()); } @Test public void dateTimeZSuccess() { assertSuccess("2015-02-28T11:00:00Z", new DateTimeFormatValidator()); } @Test public void dateFailure() { assertFailure("06/19/1963", new DateFormatValidator(), "[06/19/1963] is not a valid date. Expected [yyyy-MM-dd]"); } @Test public void dateSuccess() { assertSuccess("1963-06-19", new DateFormatValidator()); } @Test public void timeFailure() { assertFailure("08:30:06 PST", new TimeFormatValidator(), "[08:30:06 PST] is not a valid time. " + "Expected [HH:mm:ssZ, HH:mm:ss.[0-9]{1,9}Z, HH:mm:ss[+-]HH:mm, HH:mm:ss.[0-9]{1,9}[+-]HH:mm]"); } @Test public void timeSuccess() { assertSuccess("11:00:00+00:00", new TimeFormatValidator()); } @Test public void timeZSuccess() { assertSuccess("11:00:00Z", new TimeFormatValidator()); } @Test public void timeWithSingleDigitInSecFracSuccess() { assertSuccess("11:00:00.1Z", new TimeFormatValidator()); } @Test public void timeWithTwoDigitsInSecFracSuccess() { assertSuccess("11:00:00.12Z", new TimeFormatValidator()); } @Test public void timeWithThreeDigitsInSecFracSuccess() { assertSuccess("11:00:00.123Z", new TimeFormatValidator()); } @Test public void timeWithFourDigitsInSecFracSuccess() { assertSuccess("11:00:00.1234Z", new TimeFormatValidator()); } @Test public void timeWithFiveDigitsInSecFracSuccess() { assertSuccess("11:00:00.12345Z", new TimeFormatValidator()); } @Test public void timeWithSixDigitsInSecFracSuccess() { assertSuccess("11:00:00.123456Z", new TimeFormatValidator()); } @Test public void timeimeWithSevenDigitsInSecFracSuccess() { assertSuccess("11:00:00.1234567Z", new TimeFormatValidator()); } @Test public void timeWithEightDigitsInSecFracSuccess() { assertSuccess("11:00:00.12345678Z", new TimeFormatValidator()); } @Test public void timeWithNineDigitsInSecFracSuccess() { assertSuccess("11:00:00.123456789Z", new TimeFormatValidator()); } @Test public void timeWithTenDigitsInSecFracFailure() { assertFailure("11:00:00.1234567890Z", new TimeFormatValidator(), "[11:00:00.1234567890Z] is not a valid time. " + "Expected [HH:mm:ssZ, HH:mm:ss.[0-9]{1,9}Z, HH:mm:ss[+-]HH:mm, HH:mm:ss.[0-9]{1,9}[+-]HH:mm]"); } @Test public void emailFailure() { assertFailure("a.@b.com", new EmailFormatValidator(), "[a.@b.com] is not a valid email address"); } @Test public void emailSuccess() { assertSuccess("a@b.com", new EmailFormatValidator()); } @Test public void hostnameLengthFailure() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 256; ++i) { sb.append('a'); } String subject = sb.toString(); assertFailure(subject, new HostnameFormatValidator(), "[" + subject + "] is not a valid hostname"); } @Test public void hostnameNullFailure() { assertFailure(null, new HostnameFormatValidator(), "[null] is not a valid hostname"); } @Test public void hostnameSuccess() { assertSuccess("localhost", new HostnameFormatValidator()); } @Test public void hostnameWithUnderscoresFailure() { assertFailure("not_a_valid_host_name", new HostnameFormatValidator(), "[not_a_valid_host_name] is not a valid hostname"); } @Test public void ipv4Failure() { assertFailure("asd", new IPV4Validator(), "[asd] is not a valid ipv4 address"); } @Test public void ipv4LengthFailure() { assertFailure(IPV6_ADDR, new IPV4Validator(), "[2001:db8:85a3:0:0:8a2e:370:7334] is not a valid ipv4 address"); } @Test public void ipv4NullFailure() { assertFailure(null, new IPV4Validator(), "[null] is not a valid ipv4 address"); } @Test public void ipv4Success() { assertSuccess(THERE_IS_NO_PLACE_LIKE, new IPV4Validator()); } @Test public void ipv6Failure() { assertFailure("asd", new IPV6Validator(), "[asd] is not a valid ipv6 address"); } @Test public void ipv6LengthFailure() { assertFailure(THERE_IS_NO_PLACE_LIKE, new IPV6Validator(), "[127.0.0.1] is not a valid ipv6 address"); } @Test public void ipv6NullFailure() { assertFailure(null, new IPV6Validator(), "[null] is not a valid ipv6 address"); } @Test public void ipv6Success() { assertSuccess(IPV6_ADDR, new IPV6Validator()); } // Tests for abckward compartibility public class IPV4ValidatorOld extends IPAddressValidator implements FormatValidator { private static final int IPV4_LENGTH = 4; @Override public Optional<String> validate(final String subject) { return checkIpAddress(subject, IPV4_LENGTH, "[%s] is not a valid ipv4 address"); } @Override public String formatName() { return "ipv4"; } } @Test public void ipv4OldFailure() { assertFailure("asd", new IPV4ValidatorOld(), "[asd] is not a valid ipv4 address"); } @Test public void ipv4OldLengthFailure() { assertFailure(IPV6_ADDR, new IPV4ValidatorOld(), "[2001:db8:85a3:0:0:8a2e:370:7334] is not a valid ipv4 address"); } @Test public void ipv4OldNullFailure() { assertFailure(null, new IPV4ValidatorOld(), "[null] is not a valid ipv4 address"); } @Test public void ipv4OldSuccess() { assertSuccess(THERE_IS_NO_PLACE_LIKE, new IPV4ValidatorOld()); } @Test public void uriFailure() { assertFailure("12 34", new URIFormatValidator(), "[12 34] is not a valid URI"); } @Test public void relativeURIRefFailsInDraft6() { assertFailure("abc", new URIFormatValidator(), "[abc] is not a valid URI"); } @Test public void relativeURIRefSucceedsInDraft4() { assertSuccess("abc", new URIV4FormatValidator()); } @Test public void protocolRelativeURIsCanBeDisabled() { assertFailure("//example.com", new URIFormatValidator(false), "[//example.com] is not a valid URI"); } // // @Test // public void protocolRelativeUriSuccess() { // assertSuccess("//foo.bar/?baz=qux#quux", new URIFormatValidator()); // } @Test public void uriNullFailure() { assertFailure(null, new URIFormatValidator(), "[null] is not a valid URI"); } @Test public void uriSuccess() { assertSuccess("http://example.org:8080/example.html", new URIFormatValidator()); } @Test public void regexSuccess() { assertSuccess("([abc])+\\s+$", new RegexFormatValidator()); } @Test public void regexFailure() { assertFailure("^(abc]", new RegexFormatValidator(), "[^(abc]] is not a valid regular expression"); } }
package com.haxademic.demo.draw.image; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.app.config.AppSettings; import com.haxademic.core.app.config.Config; import com.haxademic.core.draw.image.ImageCyclerBuffer; import com.haxademic.core.media.DemoAssets; import processing.core.PImage; public class Demo_ImageCyclerBuffer extends PAppletHax { public static void main(String args[]) { arguments = args; PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); } protected ImageCyclerBuffer imageCycler; protected void config() { Config.setProperty( AppSettings.WIDTH, 720 ); Config.setProperty( AppSettings.HEIGHT, 720 ); Config.setProperty( AppSettings.FULLSCREEN, false ); Config.setProperty( AppSettings.SMOOTHING, AppSettings.SMOOTH_HIGH ); } protected void firstFrame() { PImage[] images = new PImage[] { DemoAssets.squareTexture(), DemoAssets.smallTexture(), DemoAssets.textureNebula(), DemoAssets.textureJupiter(), }; // imageCycler = new ImageCyclerBuffer(640, 280, images, 100, 99, p.color(0,255,0), false); // imageCycler = new ImageCyclerBuffer(640, 280, images, 100, 99, -1, false, ImageCyclerBuffer.directional_wipe); imageCycler = new ImageCyclerBuffer(640, 280, images, 100, 99, -1, false, ImageCyclerBuffer.circle_open); } protected void drawApp() { p.background(255,0,0); imageCycler.update(); p.image(imageCycler.image(), 20, 20); } }
package com.midup.bedwars.game.action.actions; import com.midup.bedwars.Main; import com.midup.bedwars.game.action.Action; import com.midup.bedwars.generator.models.GeneratorType; import org.bukkit.Bukkit; public class UPDiamond2 extends Action { public UPDiamond2() { super("Diamante FULL", 360); } @Override public void run() { Main.getGeneratorManager().getGenerators().forEach(generator -> { if (generator.getType() == GeneratorType.DIAMOND) { generator.setLevel(3); generator.setSpawnTime(20); generator.setupHologram(); } }); Bukkit.broadcastMessage("§eO gerador de diamante está no nivel máximo"); } }
/** * */ package com.kancolle.server.model.po.common.handler; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.Feature; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.function.Function; /** * @author J.K.SAGE * @Date 2015年5月30日 * */ public class JsonObjectHandler extends BaseTypeHandler<JSONObject> { private static final Function<String, JSONObject> toJsonObject = str -> JSON.parseObject(str, Feature.OrderedField); @Override public JSONObject getNullableResult(ResultSet rs, String columnName) throws SQLException { return toJsonObject.apply(rs.getString(columnName)); } @Override public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return toJsonObject.apply(rs.getString(columnIndex)); } @Override public JSONObject getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return toJsonObject.apply(cs.getString(columnIndex)); } @Override public void setNonNullParameter(PreparedStatement ps, int columnIndex, JSONObject value, JdbcType jdbcType) throws SQLException { ps.setString(columnIndex, value.toJSONString()); } }
// Copyright (c) 2019, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.ir.optimize.inliner; import static com.android.tools.r8.utils.codeinspector.CodeMatchers.accessesField; import static com.android.tools.r8.utils.codeinspector.Matchers.isPresent; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import com.android.tools.r8.NeverInline; import com.android.tools.r8.NoVerticalClassMerging; import com.android.tools.r8.TestBase; import com.android.tools.r8.TestParameters; import com.android.tools.r8.TestParametersCollection; import com.android.tools.r8.utils.StringUtils; import com.android.tools.r8.utils.codeinspector.ClassSubject; import com.android.tools.r8.utils.codeinspector.CodeInspector; import com.android.tools.r8.utils.codeinspector.MethodSubject; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class InliningFromCurrentClassTest extends TestBase { private final TestParameters parameters; @Parameterized.Parameters(name = "{0}") public static TestParametersCollection data() { return getTestParameters().withAllRuntimesAndApiLevels().build(); } public InliningFromCurrentClassTest(TestParameters parameters) { this.parameters = parameters; } @Test public void test() throws Exception { String expectedOutput = StringUtils.lines( "In A.<clinit>()", "In B.<clinit>()", "In A.inlineable1()", "In B.inlineable2()", "In C.<clinit>()", "In C.inlineableWithInitClass()"); testForJvm().addTestClasspath().run(TestClass.class).assertSuccessWithOutput(expectedOutput); CodeInspector inspector = testForR8(parameters.getBackend()) .addInnerClasses(InliningFromCurrentClassTest.class) .addKeepMainRule(TestClass.class) .enableInliningAnnotations() .enableNoVerticalClassMergingAnnotations() .setMinApi(parameters.getApiLevel()) .run(parameters.getRuntime(), TestClass.class) .assertSuccessWithOutput(expectedOutput) .inspector(); ClassSubject classA = inspector.clazz(A.class); assertThat(classA, isPresent()); ClassSubject classB = inspector.clazz(B.class); assertThat(classB, isPresent()); ClassSubject classC = inspector.clazz(C.class); assertThat(classC, isPresent()); MethodSubject testMethod = classB.uniqueMethodWithName("test"); assertThat(testMethod, isPresent()); MethodSubject inlineable1Method = classA.uniqueMethodWithName("inlineable1"); assertThat(inlineable1Method, not(isPresent())); MethodSubject inlineable2Method = classB.uniqueMethodWithName("inlineable2"); assertThat(inlineable2Method, not(isPresent())); MethodSubject inlineableWithInitClassMethod = classC.uniqueMethodWithName("inlineableWithInitClass"); assertThat(inlineableWithInitClassMethod, not(isPresent())); assertThat(testMethod, accessesField(classC.uniqueFieldWithName("$r8$clinit"))); } static class TestClass { public static void main(String[] args) { B.test(); } } @NoVerticalClassMerging static class A { static { System.out.println("In A.<clinit>()"); } static void inlineable1() { System.out.println("In A.inlineable1()"); } } @NoVerticalClassMerging static class B extends A { static { System.out.println("In B.<clinit>()"); } @NeverInline static void test() { A.inlineable1(); B.inlineable2(); C.inlineableWithInitClass(); } static void inlineable2() { System.out.println("In B.inlineable2()"); } } static class C extends B { static { System.out.println("In C.<clinit>()"); } static void inlineableWithInitClass() { System.out.println("In C.inlineableWithInitClass()"); } } }
/** * Copyright 2019 LinkedIn Corp. 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. */ package com.github.ambry.cloud.azure; import com.azure.core.http.HttpClient; import com.azure.core.http.ProxyOptions; import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; import com.azure.core.http.rest.Response; import com.azure.core.util.Configuration; import com.azure.core.util.Context; import com.azure.storage.blob.BlobContainerClient; import com.azure.storage.blob.BlobServiceClient; import com.azure.storage.blob.BlobServiceClientBuilder; import com.azure.storage.blob.batch.BlobBatch; import com.azure.storage.blob.batch.BlobBatchClient; import com.azure.storage.blob.batch.BlobBatchClientBuilder; import com.azure.storage.blob.models.BlobErrorCode; import com.azure.storage.blob.models.BlobProperties; import com.azure.storage.blob.models.BlobRequestConditions; import com.azure.storage.blob.models.BlobStorageException; import com.azure.storage.blob.specialized.BlockBlobClient; import com.azure.storage.common.policy.RequestRetryOptions; import com.azure.storage.common.policy.RetryPolicyType; import com.codahale.metrics.Timer; import com.github.ambry.cloud.CloudBlobMetadata; import com.github.ambry.cloud.azure.AzureBlobLayoutStrategy.BlobLayout; import com.github.ambry.commons.BlobId; import com.github.ambry.config.CloudConfig; import com.github.ambry.utils.Utils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UncheckedIOException; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Data accessor class for Azure Blob Storage. */ public class AzureBlobDataAccessor { private static final Logger logger = LoggerFactory.getLogger(AzureBlobDataAccessor.class); private final BlobServiceClient storageClient; private final BlobBatchClient blobBatchClient; private final Configuration storageConfiguration; private final AzureMetrics azureMetrics; private final AzureBlobLayoutStrategy blobLayoutStrategy; // Containers known to exist in the storage account private final Set<String> knownContainers = ConcurrentHashMap.newKeySet(); private ProxyOptions proxyOptions; private final int purgeBatchSize; private final Duration requestTimeout, uploadTimeout, batchTimeout; private final BlobRequestConditions defaultRequestConditions = null; private Callable<?> updateCallback = null; /** * Production constructor * @param cloudConfig the {@link CloudConfig} to use. * @param azureCloudConfig the {@link AzureCloudConfig} to use. * @param blobLayoutStrategy the {@link AzureBlobLayoutStrategy} to use. * @param azureMetrics the {@link AzureMetrics} to use. */ AzureBlobDataAccessor(CloudConfig cloudConfig, AzureCloudConfig azureCloudConfig, AzureBlobLayoutStrategy blobLayoutStrategy, AzureMetrics azureMetrics) { this.blobLayoutStrategy = blobLayoutStrategy; this.azureMetrics = azureMetrics; this.purgeBatchSize = azureCloudConfig.azurePurgeBatchSize; this.storageConfiguration = new Configuration(); // Check for network proxy proxyOptions = (cloudConfig.vcrProxyHost == null) ? null : new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(cloudConfig.vcrProxyHost, cloudConfig.vcrProxyPort)); if (proxyOptions != null) { logger.info("Using proxy: {}:{}", cloudConfig.vcrProxyHost, cloudConfig.vcrProxyPort); } HttpClient client = new NettyAsyncHttpClientBuilder().proxy(proxyOptions).build(); requestTimeout = Duration.ofMillis(cloudConfig.cloudRequestTimeout); uploadTimeout = Duration.ofMillis(cloudConfig.cloudUploadRequestTimeout); batchTimeout = Duration.ofMillis(cloudConfig.cloudBatchRequestTimeout); // Note: retry decisions are made at CloudBlobStore level. Configure storageClient with no retries. RequestRetryOptions noRetries = new RequestRetryOptions(RetryPolicyType.FIXED, 1, null, null, null, null); storageClient = new BlobServiceClientBuilder().connectionString(azureCloudConfig.azureStorageConnectionString) .httpClient(client) .retryOptions(noRetries) .configuration(storageConfiguration) .buildClient(); blobBatchClient = new BlobBatchClientBuilder(storageClient).buildClient(); } /** * Test constructor * @param storageClient the {@link BlobServiceClient} to use. * @param blobBatchClient the {@link BlobBatchClient} to use. * @param clusterName the cluster name to use. * @param azureMetrics the {@link AzureMetrics} to use. */ AzureBlobDataAccessor(BlobServiceClient storageClient, BlobBatchClient blobBatchClient, String clusterName, AzureMetrics azureMetrics) { this.storageClient = storageClient; this.storageConfiguration = new Configuration(); this.blobLayoutStrategy = new AzureBlobLayoutStrategy(clusterName); this.azureMetrics = azureMetrics; this.blobBatchClient = blobBatchClient; this.purgeBatchSize = AzureCloudConfig.DEFAULT_PURGE_BATCH_SIZE; requestTimeout = null; uploadTimeout = null; batchTimeout = null; } /** Visible for testing */ void setUpdateCallback(Callable<?> callback) { this.updateCallback = callback; } /** * Test utility. * @return the network {@link ProxyOptions} used to connect to ABS. */ ProxyOptions getProxyOptions() { return proxyOptions; } /** * Upload the blob to Azure storage if it does not already exist in the designated container. * @param blobId the blobId to upload * @param inputLength the input stream length, if known (-1 if not) * @param cloudBlobMetadata the blob metadata * @param blobInputStream the input stream * @return {@code true} if the upload was successful, {@code false} if the blob already exists. * @throws BlobStorageException for any error on ABS side. * @throws IOException for any error with supplied data stream. */ public boolean uploadIfNotExists(BlobId blobId, long inputLength, CloudBlobMetadata cloudBlobMetadata, InputStream blobInputStream) throws BlobStorageException, IOException { BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setIfNoneMatch("*"); azureMetrics.blobUploadRequestCount.inc(); Timer.Context storageTimer = azureMetrics.blobUploadTime.time(); try { BlockBlobClient blobClient = getBlockBlobClient(blobId, true); Map<String, String> metadata = cloudBlobMetadata.toMap(); blobClient.uploadWithResponse(blobInputStream, inputLength, null, metadata, null, null, blobRequestConditions, uploadTimeout, Context.NONE); logger.debug("Uploaded blob {} to ABS", blobId); azureMetrics.blobUploadSuccessCount.inc(); return true; } catch (UncheckedIOException e) { // error processing input stream throw e.getCause(); } catch (BlobStorageException e) { if (e.getErrorCode() == BlobErrorCode.BLOB_ALREADY_EXISTS) { logger.debug("Skipped upload of existing blob {}", blobId); azureMetrics.blobUploadConflictCount.inc(); return false; } else { throw e; } } finally { storageTimer.stop(); } } /** * Upload a file to blob storage. * @param containerName name of the container where blob is stored. * @param fileName the blob filename. * @param inputStream the input stream to use for upload. * @throws BlobStorageException for any error on ABS side. * @throws IOException for any error with supplied data stream. */ public void uploadFile(String containerName, String fileName, InputStream inputStream) throws BlobStorageException, IOException { try { BlockBlobClient blobClient = getBlockBlobClient(containerName, fileName, true); blobClient.uploadWithResponse(inputStream, inputStream.available(), null, null, null, null, defaultRequestConditions, uploadTimeout, Context.NONE); } catch (UncheckedIOException e) { // error processing input stream throw e.getCause(); } } /** * Download a file from blob storage. * @param containerName name of the container containing blob to download. * @param fileName name of the blob. * @param outputStream the output stream to use for download. * @param errorOnNotFound If {@code true}, throw BlobStorageException on blob not found, otherwise return false. * @return {@code true} if the download was successful, {@code false} if the blob was not found. * @throws BlobStorageException for any error on ABS side. * @throws UncheckedIOException for any error with supplied data stream. */ public boolean downloadFile(String containerName, String fileName, OutputStream outputStream, boolean errorOnNotFound) throws BlobStorageException { try { BlockBlobClient blobClient = getBlockBlobClient(containerName, fileName, false); // Might as well use same timeout for upload and download blobClient.downloadWithResponse(outputStream, null, null, defaultRequestConditions, false, uploadTimeout, Context.NONE); return true; } catch (BlobStorageException e) { if (!errorOnNotFound && isNotFoundError(e.getErrorCode())) { return false; } else { throw e; } } } /** * Perform basic connectivity test. */ void testConnectivity() { try { // TODO: Turn on verbose logging during this call (how to do in v12?) storageClient.getBlobContainerClient("partition-0").existsWithResponse(Duration.ofSeconds(5), Context.NONE); logger.info("Blob storage connection test succeeded."); } catch (BlobStorageException ex) { throw new IllegalStateException("Blob storage connection test failed", ex); } } /** * Download the blob from Azure storage. * @param blobId id of the Ambry blob to be downloaded * @param outputStream outputstream to populate the downloaded data with * @throws BlobStorageException on Azure side error. * @throws UncheckedIOException on error writing to the output stream. */ public void downloadBlob(BlobId blobId, OutputStream outputStream) throws BlobStorageException { azureMetrics.blobDownloadRequestCount.inc(); Timer.Context storageTimer = azureMetrics.blobDownloadTime.time(); try { BlobLayout blobLayout = blobLayoutStrategy.getDataBlobLayout(blobId); downloadFile(blobLayout.containerName, blobLayout.blobFilePath, outputStream, true); azureMetrics.blobDownloadSuccessCount.inc(); } catch (Exception e) { azureMetrics.blobDownloadErrorCount.inc(); throw e; } finally { storageTimer.stop(); } } /** * Retrieve the metadata for the specified blob. * @param blobId The {@link BlobId} to retrieve. * @return The {@link CloudBlobMetadata} if the blob was found, or null otherwise. * @throws BlobStorageException */ public CloudBlobMetadata getBlobMetadata(BlobId blobId) throws BlobStorageException { BlockBlobClient blobClient = getBlockBlobClient(blobId, false); BlobProperties blobProperties = null; try { blobProperties = blobClient.getPropertiesWithResponse(defaultRequestConditions, requestTimeout, Context.NONE).getValue(); if (blobProperties == null) { logger.debug("Blob {} not found.", blobId); return null; } } catch (BlobStorageException e) { if (isNotFoundError(e.getErrorCode())) { logger.debug("Blob {} not found.", blobId); return null; } throw e; } Map<String, String> metadata = blobProperties.getMetadata(); return CloudBlobMetadata.fromMap(metadata); } /** * Update the metadata for the specified blob. * @param blobId The {@link BlobId} to update. * @param updateFields Map of field names and new values to modify. * @return a {@link UpdateResponse} with the updated metadata. * @throws BlobStorageException if the blob does not exist or an error occurred. * @throws IllegalStateException on request timeout. */ public UpdateResponse updateBlobMetadata(BlobId blobId, Map<String, Object> updateFields) throws BlobStorageException { Objects.requireNonNull(blobId, "BlobId cannot be null"); updateFields.keySet() .forEach(field -> Objects.requireNonNull(updateFields.get(field), String.format("%s cannot be null", field))); try { BlockBlobClient blobClient = getBlockBlobClient(blobId, false); Timer.Context storageTimer = azureMetrics.blobUpdateTime.time(); try { BlobProperties blobProperties = blobClient.getPropertiesWithResponse(defaultRequestConditions, requestTimeout, Context.NONE).getValue(); // Note: above throws 404 exception if blob does not exist. String etag = blobProperties.getETag(); Map<String, String> metadata = blobProperties.getMetadata(); // Update only if any of the values have changed Map<String, String> changedFields = updateFields.entrySet() .stream() .filter(entry -> !String.valueOf(entry.getValue()).equals(metadata.get(entry.getKey()))) .collect(Collectors.toMap(Map.Entry::getKey, entry -> String.valueOf(entry.getValue()))); if (changedFields.size() > 0) { changedFields.forEach(metadata::put); if (updateCallback != null) { try { updateCallback.call(); } catch (Exception ex) { logger.error("Error in update callback", ex); } } // Set condition to ensure we don't clobber a concurrent update BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setIfMatch(etag); blobClient.setMetadataWithResponse(metadata, blobRequestConditions, requestTimeout, Context.NONE); return new UpdateResponse(true, metadata); } else { return new UpdateResponse(false, metadata); } } finally { storageTimer.stop(); } } catch (BlobStorageException e) { if (isNotFoundError(e.getErrorCode())) { logger.warn("Blob {} not found, cannot update {}.", blobId, updateFields.keySet()); } if (e.getErrorCode() == BlobErrorCode.CONDITION_NOT_MET) { azureMetrics.blobUpdateConflictCount.inc(); } throw e; } } /** * Permanently delete the specified blobs in Azure storage. * @param blobMetadataList the list of {@link CloudBlobMetadata} referencing the blobs to purge. * @return list of {@link CloudBlobMetadata} referencing the blobs successfully purged. * @throws BlobStorageException if the purge operation fails. * @throws RuntimeException if the request times out before a response is received. */ public List<CloudBlobMetadata> purgeBlobs(List<CloudBlobMetadata> blobMetadataList) throws BlobStorageException { List<CloudBlobMetadata> deletedBlobs = new ArrayList<>(); List<List<CloudBlobMetadata>> partitionedLists = Utils.partitionList(blobMetadataList, purgeBatchSize); for (List<CloudBlobMetadata> batchOfBlobs : partitionedLists) { BlobBatch blobBatch = blobBatchClient.getBlobBatch(); List<Response<Void>> responseList = new ArrayList<>(); for (CloudBlobMetadata blobMetadata : batchOfBlobs) { BlobLayout blobLayout = blobLayoutStrategy.getDataBlobLayout(blobMetadata); responseList.add(blobBatch.deleteBlob(blobLayout.containerName, blobLayout.blobFilePath)); } blobBatchClient.submitBatchWithResponse(blobBatch, false, batchTimeout, Context.NONE); for (int j = 0; j < responseList.size(); j++) { Response<Void> response = responseList.get(j); CloudBlobMetadata blobMetadata = batchOfBlobs.get(j); // Note: Response.getStatusCode() throws exception on any error. try { response.getStatusCode(); } catch (BlobStorageException bex) { int statusCode = bex.getStatusCode(); // Don't worry if blob is already gone if (statusCode != HttpURLConnection.HTTP_NOT_FOUND && statusCode != HttpURLConnection.HTTP_GONE) { logger.error("Deleting blob {} got status {}", blobMetadata.getId(), statusCode); throw bex; } } deletedBlobs.add(blobMetadata); } } return deletedBlobs; } /** * Get the block blob client for the supplied blobid. * @param blobId id of the blob for which {@code BlockBlobClient} is needed. * @param autoCreateContainer flag indicating whether to create the container if it does not exist. * @return {@code BlockBlobClient} reference. */ private BlockBlobClient getBlockBlobClient(BlobId blobId, boolean autoCreateContainer) { BlobLayout blobLayout = blobLayoutStrategy.getDataBlobLayout(blobId); return getBlockBlobClient(blobLayout.containerName, blobLayout.blobFilePath, autoCreateContainer); } /** * Get the block blob client for the supplied Azure container and blob name. * @param containerName name of the Azure container where the blob lives. * @param blobName name of the blob. * @param autoCreateContainer flag indicating whether to create the container if it does not exist. * @return {@code BlockBlobClient} reference. */ private BlockBlobClient getBlockBlobClient(String containerName, String blobName, boolean autoCreateContainer) { BlobContainerClient containerClient = getContainer(containerName, autoCreateContainer); return containerClient.getBlobClient(blobName).getBlockBlobClient(); } /** * Get a reference to an Azure container, creating it if necessary. * @param containerName the container name. * @param autoCreate flag indicating whether to create the container if it does not exist. * @return the created {@link BlobContainerClient}. */ private BlobContainerClient getContainer(String containerName, boolean autoCreate) { BlobContainerClient containerClient = storageClient.getBlobContainerClient(containerName); if (autoCreate) { if (!knownContainers.contains(containerName)) { try { if (!containerClient.exists()) { containerClient.create(); logger.info("Created container {}", containerName); } } catch (BlobStorageException ex) { if (ex.getErrorCode() != BlobErrorCode.CONTAINER_ALREADY_EXISTS) { logger.error("Failed to create container {}", containerName); throw ex; } } knownContainers.add(containerName); } } return containerClient; } /** * Utility to check if an error code corresponds to a not-found condition. * @param errorCode the {@link BlobErrorCode} to check. * @return {@code true} for a not-found error, otherwise {@code false}. */ private static boolean isNotFoundError(BlobErrorCode errorCode) { return (errorCode == BlobErrorCode.BLOB_NOT_FOUND || errorCode == BlobErrorCode.CONTAINER_NOT_FOUND); } /** * Struct returned by updateBlobMetadata that tells the caller whether the metadata was updated * and also returns the (possibly modified) metadata. */ static class UpdateResponse { /** Flag indicating whether the metadata was updated. */ final boolean wasUpdated; /** The resulting metadata map. */ final Map<String, String> metadata; UpdateResponse(boolean wasUpdated, Map<String, String> metadata) { this.wasUpdated = wasUpdated; this.metadata = metadata; } } }
package wayoftime.bloodmagic.potion; import java.util.Random; import net.minecraft.entity.LivingEntity; import net.minecraft.particles.ParticleTypes; import net.minecraft.potion.EffectType; import net.minecraft.world.Explosion; public class PotionFireFuse extends PotionBloodMagic { public PotionFireFuse() { super(EffectType.HARMFUL, 0xFF0000FF); } @Override public void performEffect(LivingEntity entity, int amplifier) { if (entity.world.isRemote) { return; } Random random = entity.world.rand; entity.getEntityWorld().addParticle(ParticleTypes.FLAME, entity.getPosX() + random.nextDouble() * 0.3, entity.getPosY() + random.nextDouble() * 0.3, entity.getPosZ() + random.nextDouble() * 0.3, 0, 0.06d, 0); int radius = amplifier + 1; if (entity.getActivePotionEffect(BloodMagicPotions.FIRE_FUSE).getDuration() <= 3) { Explosion.Mode explosion$mode = net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(entity.world, entity) ? Explosion.Mode.DESTROY : Explosion.Mode.NONE; entity.getEntityWorld().createExplosion(null, entity.getPosX(), entity.getPosY(), entity.getPosZ(), radius, false, explosion$mode); } } @Override public boolean isReady(int duration, int amplifier) { return true; } }
/** * Copyright (C) 2013-2015 all@code-story.net * * 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.codestory.http.testhelpers; import static net.codestory.http.Configuration.NO_ROUTE; import static net.codestory.http.misc.MemoizingSupplier.*; import java.util.function.*; import net.codestory.http.*; import net.codestory.http.misc.*; import org.junit.rules.*; public class ProdWebServerRule extends ExternalResource { private static Supplier<WebServer> server = memoize(() -> new WebServer() { @Override protected Env createEnv() { return Env.prod(); } }.startOnRandomPort()); @Override protected void after() { server.get().configure(NO_ROUTE); } public void configure(Configuration configuration) { server.get().configure(configuration); } public int port() { return server.get().port(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rs.ugligovic.csvparser; import rs.ugligovic.csvparser.exception.BadCsvException; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; /** * @author UrosGligovic */ public class Csv { private Stream<Map<String, String>> stream; private String delimiter = ","; private final Map<Integer, String> columnIndexMap = new HashMap<>(); public Csv(String path) throws BadCsvException, IOException { this(path, null); } public Csv(String path, String userDelimiter) throws BadCsvException, IOException { this(path, userDelimiter, StandardCharsets.UTF_8); } public Csv(String path, String userDelimiter, Charset charset) throws BadCsvException, IOException { String firstLine = Files.lines(Paths.get(path), charset).findFirst().orElse(null); if (firstLine == null || firstLine.equals("")) { System.out.println("First line of the file at " + path + " is empty"); throw new BadCsvException("First line of the file at " + path + " is empty, columns need to be specified"); } if (userDelimiter != null) { delimiter = userDelimiter; } String[] firstLineSplitted = firstLine.split(delimiter); for (int i = 0; i < firstLineSplitted.length; i++) { columnIndexMap.put(i, firstLineSplitted[i]); } this.stream = Files.lines(Paths.get(path), charset) .skip(1) .map(x -> x.split(delimiter)) .map(x -> mapToColumnMap(x)); } public Stream<Map<String, String>> stream() { return this.stream; } public ArrayList<String> getColumns() { return new ArrayList(this.columnIndexMap.values()); } private Map<String, String> mapToColumnMap(String[] row) { Map<String, String> resultMap = new HashMap<>(); for (int i = 0; i < row.length; i++) { resultMap.put(columnIndexMap.get(i), row[i]); } return resultMap; } }
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.google.android.gms.common.api.internal; import android.app.Activity; import java.util.*; // Referenced classes of package com.google.android.gms.common.api.internal: // LifecycleCallback, zaa, LifecycleFragment static class zaa$zaa extends LifecycleCallback { private static zaa$zaa zaa(Activity activity) { activity; // 0 0:aload_0 JVM INSTR monitorenter ; // 1 1:monitorenter zaa$zaa zaa$zaa2; LifecycleFragment lifecyclefragment; lifecyclefragment = getFragment(activity); // 2 2:aload_0 // 3 3:invokestatic #39 <Method LifecycleFragment getFragment(Activity)> // 4 6:astore_3 zaa$zaa2 = (zaa$zaa)lifecyclefragment.getCallbackOrNull("LifecycleObserverOnStop", com/google/android/gms/common/api/internal/zaa$zaa); // 5 7:aload_3 // 6 8:ldc1 #27 <String "LifecycleObserverOnStop"> // 7 10:ldc1 #2 <Class zaa$zaa> // 8 12:invokeinterface #43 <Method LifecycleCallback LifecycleFragment.getCallbackOrNull(String, Class)> // 9 17:checkcast #2 <Class zaa$zaa> // 10 20:astore_2 zaa$zaa zaa$zaa1; zaa$zaa1 = zaa$zaa2; // 11 21:aload_2 // 12 22:astore_1 if(zaa$zaa2 != null) break MISSING_BLOCK_LABEL_36; // 13 23:aload_2 // 14 24:ifnonnull 36 zaa$zaa1 = new zaa$zaa(lifecyclefragment); // 15 27:new #2 <Class zaa$zaa> // 16 30:dup // 17 31:aload_3 // 18 32:invokespecial #44 <Method void zaa$zaa(LifecycleFragment)> // 19 35:astore_1 activity; // 20 36:aload_0 JVM INSTR monitorexit ; // 21 37:monitorexit return zaa$zaa1; // 22 38:aload_1 // 23 39:areturn Exception exception; exception; // 24 40:astore_1 activity; // 25 41:aload_0 JVM INSTR monitorexit ; // 26 42:monitorexit throw exception; // 27 43:aload_1 // 28 44:athrow } static void zaa(zaa$zaa zaa$zaa1, Runnable runnable) { zaa$zaa1.zaa(runnable); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokespecial #48 <Method void zaa(Runnable)> // 3 5:return } private final void zaa(Runnable runnable) { this; // 0 0:aload_0 JVM INSTR monitorenter ; // 1 1:monitorenter zacl.add(((Object) (runnable))); // 2 2:aload_0 // 3 3:getfield #21 <Field List zacl> // 4 6:aload_1 // 5 7:invokeinterface #54 <Method boolean List.add(Object)> // 6 12:pop this; // 7 13:aload_0 JVM INSTR monitorexit ; // 8 14:monitorexit return; // 9 15:return runnable; // 10 16:astore_1 //* 11 17:aload_0 throw runnable; // 12 18:monitorexit // 13 19:aload_1 // 14 20:athrow } static zaa$zaa zab(Activity activity) { return zaa(activity); // 0 0:aload_0 // 1 1:invokestatic #57 <Method zaa$zaa zaa(Activity)> // 2 4:areturn } public void onStop() { this; // 0 0:aload_0 JVM INSTR monitorenter ; // 1 1:monitorenter Object obj; obj = ((Object) (zacl)); // 2 2:aload_0 // 3 3:getfield #21 <Field List zacl> // 4 6:astore_1 zacl = ((List) (new ArrayList())); // 5 7:aload_0 // 6 8:new #16 <Class ArrayList> // 7 11:dup // 8 12:invokespecial #19 <Method void ArrayList()> // 9 15:putfield #21 <Field List zacl> this; // 10 18:aload_0 JVM INSTR monitorexit ; // 11 19:monitorexit for(obj = ((Object) (((List) (obj)).iterator())); ((Iterator) (obj)).hasNext(); ((Runnable)((Iterator) (obj)).next()).run()); // 12 20:aload_1 // 13 21:invokeinterface #62 <Method Iterator List.iterator()> // 14 26:astore_1 // 15 27:aload_1 // 16 28:invokeinterface #68 <Method boolean Iterator.hasNext()> // 17 33:ifeq 53 // 18 36:aload_1 // 19 37:invokeinterface #72 <Method Object Iterator.next()> // 20 42:checkcast #74 <Class Runnable> // 21 45:invokeinterface #77 <Method void Runnable.run()> //* 22 50:goto 27 return; // 23 53:return Exception exception; exception; // 24 54:astore_1 this; // 25 55:aload_0 JVM INSTR monitorexit ; // 26 56:monitorexit throw exception; // 27 57:aload_1 // 28 58:athrow } private List zacl; private zaa$zaa(LifecycleFragment lifecyclefragment) { super(lifecyclefragment); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokespecial #14 <Method void LifecycleCallback(LifecycleFragment)> zacl = ((List) (new ArrayList())); // 3 5:aload_0 // 4 6:new #16 <Class ArrayList> // 5 9:dup // 6 10:invokespecial #19 <Method void ArrayList()> // 7 13:putfield #21 <Field List zacl> mLifecycleFragment.addCallback("LifecycleObserverOnStop", ((LifecycleCallback) (this))); // 8 16:aload_0 // 9 17:getfield #25 <Field LifecycleFragment mLifecycleFragment> // 10 20:ldc1 #27 <String "LifecycleObserverOnStop"> // 11 22:aload_0 // 12 23:invokeinterface #33 <Method void LifecycleFragment.addCallback(String, LifecycleCallback)> // 13 28:return } }
package fi.jussiks.mbrainz.enums; public enum Entity { AREA, ARTIST, EVENT, LABEL, PLACE, RECORDING, RELEASE, RELEASE_GROUP, SERIES, URL, WORK, COLLECTION; public String toString() { return this.name().replaceAll("_", "-").toLowerCase(); } }
package edu.uci.ics.jung.layout.algorithms; import com.google.common.collect.Sets; import edu.uci.ics.jung.layout.spatial.BarnesHutQuadTree; import edu.uci.ics.jung.layout.spatial.ForceObject; import edu.uci.ics.jung.layout.spatial.Node; import java.util.Collections; import java.util.Iterator; import java.util.Set; /** * An iterator over the (logn) force objects to apply to the passed target This approach is slower * than visiting the BarnesHutQuadTree, but the results should be identical for each approach. This * exists for testing and verification only. * * <p>package level access for the associated test algorithm implementations only * * @author Tom Nelson */ class ForceObjectIterator<T> implements Iterator<ForceObject<T>> { private BarnesHutQuadTree<T> tree; private ForceObject<T> target; private ForceObject<T> next; private Set<ForceObject<T>> forceObjects; private Iterator<ForceObject<T>> iterator; public ForceObjectIterator(BarnesHutQuadTree<T> tree, ForceObject<T> target) { this.tree = tree; this.target = target; this.forceObjects = getForceObjectsFor(Sets.newLinkedHashSet(), target); this.iterator = forceObjects.iterator(); } @Override public boolean hasNext() { return this.iterator.hasNext(); } @Override public ForceObject<T> next() { return this.iterator.next(); } private Set<ForceObject<T>> getForceObjectsFor( Set<ForceObject<T>> forceObjects, ForceObject<T> target) { Node<T> root = tree.getRoot(); if (root != null && root.getForceObject() != target) { return getForceObjectsFor(forceObjects, target, root); } else { return Collections.emptySet(); } } private Set<ForceObject<T>> getForceObjectsFor( Set<ForceObject<T>> forceObjects, ForceObject<T> target, Node<T> from) { double THETA = 0.5; if (from.getForceObject() == null || target.equals(from.getForceObject())) { forceObjects.add(target); } if (from.isLeaf()) { forceObjects.add(from.getForceObject()); } else { // not a leaf // this node is an internal node // calculate s/d double s = from.getArea().width; // distance between the incoming node's position and // the center of mass for this node double d = from.getForceObject().p.distance(target.p); if (s / d < THETA) { // this node is sufficiently far away // just use this node's forces forceObjects.add(from.getForceObject()); } else { // down the tree we go getForceObjectsFor(forceObjects, target, from.getNW()); getForceObjectsFor(forceObjects, target, from.getNE()); getForceObjectsFor(forceObjects, target, from.getSW()); getForceObjectsFor(forceObjects, target, from.getSE()); } } return forceObjects; } }
package external_module_0323.a; import javax.lang.model.*; import javax.management.*; import javax.naming.directory.*; /** * Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut * labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. * Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. * * @see java.nio.file.FileStore * @see java.sql.Array * @see java.util.logging.Filter */ @SuppressWarnings("all") public abstract class Foo1<R> extends external_module_0323.a.Foo0<R> implements external_module_0323.a.IFoo1<R> { java.util.zip.Deflater f0 = null; javax.annotation.processing.Completion f1 = null; javax.lang.model.AnnotatedConstruct f2 = null; public R element; public static Foo1 instance; public static Foo1 getInstance() { return instance; } public static <T> T create(java.util.List<T> input) { return external_module_0323.a.Foo0.create(input); } public String getName() { return external_module_0323.a.Foo0.getInstance().getName(); } public void setName(String string) { external_module_0323.a.Foo0.getInstance().setName(getName()); return; } public R get() { return (R)external_module_0323.a.Foo0.getInstance().get(); } public void set(Object element) { this.element = (R)element; external_module_0323.a.Foo0.getInstance().set(this.element); } public R call() throws Exception { return (R)external_module_0323.a.Foo0.getInstance().call(); } }
/* * Copyright (c) 2018-2019 Qualcomm Technologies, Inc. * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of Qualcomm Technologies, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment is required by displaying the trademark/log as per the details provided here: [https://www.qualcomm.com/documents/dirbs-logo-and-brand-guidelines] * Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. * This notice may not be removed or altered from any source distribution. * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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 HOLDER 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 com.qualcomm.dvsauthorized.mUtils; import android.annotation.SuppressLint; import android.net.Uri; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import net.openid.appauth.Preconditions; import net.openid.appauth.connectivity.ConnectionBuilder; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * An example implementation of {@link ConnectionBuilder} that permits connecting to http * links, and ignores certificates for https connections. *THIS SHOULD NOT BE USED IN PRODUCTION * CODE*. It is intended to facilitate easier testing of AppAuth against development servers * only. */ public final class ConnectionBuilderForTesting implements ConnectionBuilder { static final ConnectionBuilderForTesting INSTANCE = new ConnectionBuilderForTesting(); private static final String TAG = "ConnBuilder"; private static final int CONNECTION_TIMEOUT_MS = (int) TimeUnit.SECONDS.toMillis(15); private static final int READ_TIMEOUT_MS = (int) TimeUnit.SECONDS.toMillis(10); private static final String HTTP = "http"; private static final String HTTPS = "https"; @SuppressLint("TrustAllX509TrustManager") private static final TrustManager[] ANY_CERT_MANAGER = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; @SuppressLint("BadHostnameVerifier") private static final HostnameVerifier ANY_HOSTNAME_VERIFIER = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; @Nullable private static final SSLContext TRUSTING_CONTEXT; static { SSLContext context; try { context = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException e) { Log.e("ConnBuilder", "Unable to acquire SSL context"); context = null; } SSLContext initializedContext = null; if (context != null) { try { context.init(null, ANY_CERT_MANAGER, new java.security.SecureRandom()); initializedContext = context; } catch (KeyManagementException e) { Log.e(TAG, "Failed to initialize trusting SSL context"); } } TRUSTING_CONTEXT = initializedContext; } private ConnectionBuilderForTesting() { // no need to construct new instances } @NonNull @Override public HttpURLConnection openConnection(@NonNull Uri uri) throws IOException { Preconditions.checkNotNull(uri, "url must not be null"); Preconditions.checkArgument(HTTP.equals(uri.getScheme()) || HTTPS.equals(uri.getScheme()), "scheme or uri must be http or https"); HttpURLConnection conn = (HttpURLConnection) new URL(uri.toString()).openConnection(); conn.setConnectTimeout(CONNECTION_TIMEOUT_MS); conn.setReadTimeout(READ_TIMEOUT_MS); conn.setInstanceFollowRedirects(false); if (conn instanceof HttpsURLConnection && TRUSTING_CONTEXT != null) { HttpsURLConnection httpsConn = (HttpsURLConnection) conn; httpsConn.setSSLSocketFactory(TRUSTING_CONTEXT.getSocketFactory()); httpsConn.setHostnameVerifier(ANY_HOSTNAME_VERIFIER); } return conn; } }
package io.swisschain.crypto.transaction.signing.exceptions; public class TransactionSignException extends Exception { public TransactionSignException(String message) { super(message); } }
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.instrumentation.tomcat.common; import static io.opentelemetry.instrumentation.api.servlet.ServerSpanNaming.Source.CONTAINER; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.AttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanStatusExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpServerAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpServerMetrics; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanStatusExtractor; import io.opentelemetry.instrumentation.api.instrumenter.net.NetServerAttributesExtractor; import io.opentelemetry.instrumentation.api.servlet.AppServerBridge; import io.opentelemetry.instrumentation.api.servlet.ServerSpanNaming; import io.opentelemetry.instrumentation.servlet.ServletAccessor; import io.opentelemetry.javaagent.instrumentation.servlet.ServletErrorCauseExtractor; import org.apache.coyote.Request; import org.apache.coyote.Response; public final class TomcatInstrumenterFactory { private TomcatInstrumenterFactory() {} public static <REQUEST, RESPONSE> Instrumenter<Request, Response> create( String instrumentationName, ServletAccessor<REQUEST, RESPONSE> accessor, TomcatServletEntityProvider<REQUEST, RESPONSE> servletEntityProvider) { HttpServerAttributesExtractor<Request, Response> httpAttributesExtractor = new TomcatHttpAttributesExtractor(); SpanNameExtractor<Request> spanNameExtractor = HttpSpanNameExtractor.create(httpAttributesExtractor); SpanStatusExtractor<Request, Response> spanStatusExtractor = HttpSpanStatusExtractor.create(httpAttributesExtractor); NetServerAttributesExtractor<Request, Response> netAttributesExtractor = new TomcatNetAttributesExtractor(); AttributesExtractor<Request, Response> additionalAttributeExtractor = new TomcatAdditionalAttributesExtractor<>(accessor, servletEntityProvider); return Instrumenter.<Request, Response>builder( GlobalOpenTelemetry.get(), instrumentationName, spanNameExtractor) .setSpanStatusExtractor(spanStatusExtractor) .setErrorCauseExtractor(new ServletErrorCauseExtractor<>(accessor)) .addAttributesExtractor(httpAttributesExtractor) .addAttributesExtractor(netAttributesExtractor) .addAttributesExtractor(additionalAttributeExtractor) .addContextCustomizer( (context, request, attributes) -> { context = ServerSpanNaming.init(context, CONTAINER); return AppServerBridge.init(context); }) .addRequestMetrics(HttpServerMetrics.get()) .newServerInstrumenter(TomcatRequestGetter.INSTANCE); } }
import java.util.Scanner; public class TriangleArea { public static void main(String[] args) { Scanner in = new Scanner(System.in); int aX = in.nextInt(); int aY = in.nextInt(); int bX = in.nextInt(); int bY = in.nextInt(); int cX = in.nextInt(); int cY = in.nextInt(); int result = (aX*(bY-cY)+ bX*(cY-aY)+cX*(aY-bY))/2; System.out.println(Math.abs(result)); } }
package vn.techmaster.vincinema.service; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import vn.techmaster.vincinema.model.Cinema; import vn.techmaster.vincinema.model.Room; import vn.techmaster.vincinema.repository.CinemaRepository; @Service public class RoomService { @PersistenceContext private EntityManager em; @Autowired private CinemaRepository cinemaRepo; @Transactional public void generateRooms() { Cinema cgvVinComBaTrieu = cinemaRepo.findByNameContaining("Vincom Center Bà Triệu"); Cinema cgvVinComRoyalCity = cinemaRepo.findByNameContaining("Vincom Royal City"); Cinema cgvVinComNguyenChiThanh = cinemaRepo.findByNameContaining("Vincom Nguyễn Chí Thanh"); Room r01BaTrieu = Room.builder() .name("01") .cinema(cgvVinComBaTrieu) .rowPattern("A:10,B:10,C:12,D:14,E:16") .build() .generateSeats(); Room r02BaTrieu = Room.builder() .name("02") .cinema(cgvVinComBaTrieu) .rowPattern("A:12,B:10,C:10,D:12,E:14") .build() .generateSeats(); Room r01Royal = Room.builder() .name("01") .cinema(cgvVinComRoyalCity) .rowPattern("A:10,B:10,C:12,D:14,E:16") .build() .generateSeats(); Room r02Royal = Room.builder() .name("02") .cinema(cgvVinComRoyalCity) .rowPattern("A:12,B:12,C:12,D:14,E:16") .build() .generateSeats(); Room r01NguyenChiThanh = Room.builder() .name("01") .cinema(cgvVinComNguyenChiThanh) .rowPattern("A:12,B:12,C:12,D:14,E:16") .build() .generateSeats(); Room r08NguyenChiThanh = Room.builder() .name("08") .cinema(cgvVinComNguyenChiThanh) .rowPattern("A:8,B:8,C:10,D:10,E:16") .build() .generateSeats(); em.persist(r01BaTrieu); em.persist(r02BaTrieu); em.persist(r01Royal); em.persist(r02Royal); em.persist(r01NguyenChiThanh); em.persist(r08NguyenChiThanh); } }
/* * 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.kylin.cube; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.IOException; import org.apache.kylin.common.util.LocalFileMetadataTestCase; import org.apache.kylin.metadata.model.PartitionDesc; import org.apache.kylin.metadata.model.SegmentStatusEnum; import org.junit.After; import org.junit.Before; import org.junit.Test; public class CubeSegmentsTest extends LocalFileMetadataTestCase { @Before public void setUp() throws Exception { this.createTestMetadata(); } @After public void after() throws Exception { this.cleanupTestMetadata(); } @Test public void testAppendNonPartitioned() throws IOException { CubeManager mgr = mgr(); CubeInstance cube = mgr.getCube("test_kylin_cube_without_slr_empty"); // override partition desc cube.getDataModelDesc().setPartitionDesc(new PartitionDesc()); // first append, creates a new & single segment CubeSegment seg = mgr.appendSegment(cube); assertEquals(0, seg.getDateRangeStart()); assertEquals(Long.MAX_VALUE, seg.getDateRangeEnd()); assertEquals(0, seg.getSourceOffsetStart()); assertEquals(Long.MAX_VALUE, seg.getSourceOffsetEnd()); assertEquals(1, cube.getSegments().size()); // second append, throw IllegalStateException because the first segment is not built try { mgr.appendSegment(cube); fail(); } catch (IllegalStateException ex) { // good } } @Test public void testAppendNonPartitioned2() throws IOException { CubeManager mgr = mgr(); CubeInstance cube = mgr.getCube("test_kylin_cube_without_slr_ready"); // override partition desc cube.getDataModelDesc().setPartitionDesc(new PartitionDesc()); // assert one ready segment assertEquals(1, cube.getSegments().size()); CubeSegment seg = cube.getSegments(SegmentStatusEnum.READY).get(0); assertEquals(SegmentStatusEnum.READY, seg.getStatus()); // append again, for non-partitioned cube, it becomes a full refresh CubeSegment seg2 = mgr.appendSegment(cube); assertEquals(0, seg2.getDateRangeStart()); assertEquals(Long.MAX_VALUE, seg2.getDateRangeEnd()); assertEquals(0, seg2.getSourceOffsetStart()); assertEquals(Long.MAX_VALUE, seg2.getSourceOffsetEnd()); assertEquals(2, cube.getSegments().size()); // non-partitioned cannot merge, throw exception try { mgr.mergeSegments(cube, 0, 0, 0, Long.MAX_VALUE, false); fail(); } catch (IllegalStateException ex) { // good } } @Test public void testPartitioned() throws IOException { CubeManager mgr = mgr(); CubeInstance cube = mgr.getCube("test_kylin_cube_with_slr_left_join_empty"); // no segment at first assertEquals(0, cube.getSegments().size()); // append first CubeSegment seg1 = mgr.appendSegment(cube, 0, 1000, 0, 0); seg1.setStatus(SegmentStatusEnum.READY); // append second CubeSegment seg2 = mgr.appendSegment(cube, 0, 2000, 0, 0); assertEquals(2, cube.getSegments().size()); assertEquals(1000, seg2.getDateRangeStart()); assertEquals(2000, seg2.getDateRangeEnd()); assertEquals(1000, seg2.getSourceOffsetStart()); assertEquals(2000, seg2.getSourceOffsetEnd()); assertEquals(SegmentStatusEnum.NEW, seg2.getStatus()); seg2.setStatus(SegmentStatusEnum.READY); // merge first and second CubeSegment merge = mgr.mergeSegments(cube, 0, 2000, 0, 0, true); assertEquals(3, cube.getSegments().size()); assertEquals(0, merge.getDateRangeStart()); assertEquals(2000, merge.getDateRangeEnd()); assertEquals(0, merge.getSourceOffsetStart()); assertEquals(2000, merge.getSourceOffsetEnd()); assertEquals(SegmentStatusEnum.NEW, merge.getStatus()); // segments are strictly ordered assertEquals(seg1, cube.getSegments().get(0)); assertEquals(merge, cube.getSegments().get(1)); assertEquals(seg2, cube.getSegments().get(2)); // drop the merge cube.getSegments().remove(merge); // try merge at start/end at middle of segments try { mgr.mergeSegments(cube, 500, 2500, 0, 0, true); fail(); } catch (IllegalArgumentException ex) { // good } CubeSegment merge2 = mgr.mergeSegments(cube, 0, 2500, 0, 0, true); assertEquals(3, cube.getSegments().size()); assertEquals(0, merge2.getDateRangeStart()); assertEquals(2000, merge2.getDateRangeEnd()); assertEquals(0, merge2.getSourceOffsetStart()); assertEquals(2000, merge2.getSourceOffsetEnd()); } @Test public void testAllowGap() throws IOException { CubeManager mgr = mgr(); CubeInstance cube = mgr.getCube("test_kylin_cube_without_slr_left_join_empty"); // no segment at first assertEquals(0, cube.getSegments().size()); // append the first CubeSegment seg1 = mgr.appendSegment(cube, 0, 1000, 0, 0); seg1.setStatus(SegmentStatusEnum.READY); assertEquals(1, cube.getSegments().size()); // append the third CubeSegment seg3 = mgr.appendSegment(cube, 2000, 3000, 0, 0); seg3.setStatus(SegmentStatusEnum.READY); assertEquals(2, cube.getSegments().size()); // reject overlap try { mgr.appendSegment(cube, 1000, 2500, 0, 0); fail(); } catch (IllegalStateException ex) { // good } // append the second CubeSegment seg2 = mgr.appendSegment(cube, 1000, 2000, 0, 0); seg2.setStatus(SegmentStatusEnum.READY); assertEquals(3, cube.getSegments().size()); } private CubeManager mgr() { return CubeManager.getInstance(getTestConfig()); } }
/** * * Copyright (c) 2006-2019, Speedment, Inc. 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 com.speedment.tool.config; import com.speedment.runtime.config.Project; import com.speedment.runtime.core.internal.util.ImmutableListUtil; import com.speedment.tool.config.component.DocumentPropertyComponent; import com.speedment.tool.config.mutator.DocumentPropertyMutator; import com.speedment.tool.config.mutator.ProjectPropertyMutator; import com.speedment.tool.config.trait.*; import com.speedment.tool.config.util.DocumentMerger; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.StringProperty; import javafx.collections.ObservableList; import javafx.util.StringConverter; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import static java.util.Collections.singletonList; /** * * @author Emil Forslund * @since 2.3.0 */ public final class ProjectProperty extends AbstractRootDocumentProperty<ProjectProperty> implements Project, HasEnabledProperty, HasExpandedProperty, HasIdProperty, HasNameProperty, HasPackageNameProperty, HasNameProtectedProperty { public void merge(DocumentPropertyComponent documentPropertyComponent, Project project) { DocumentMerger.merge(this, project, (parent, key) -> ((AbstractDocumentProperty<?>) parent).createChild(documentPropertyComponent, key) ); } @Override public String getName() { // Must implement getName because Project does not have any parent. return getAsString(NAME) .orElse(DEFAULT_PROJECT_NAME); } @Override public boolean isNameProtectedByDefault() { return false; } public StringProperty companyNameProperty() { return stringPropertyOf(COMPANY_NAME, Project.super::getCompanyName); } @Override public String getCompanyName() { return getAsString(COMPANY_NAME).orElse(DEFAULT_COMPANY_NAME); } public StringProperty packageLocationProperty() { return stringPropertyOf(PACKAGE_LOCATION, Project.super::getPackageLocation); } @Override public String getPackageLocation() { return packageLocationProperty().get(); } public ObjectProperty<Path> configPathProperty() { final ObjectProperty<Path> pathProperty = new SimpleObjectProperty<>(); Bindings.bindBidirectional( stringPropertyOf(CONFIG_PATH, () -> null), pathProperty, PATH_CONVERTER ); return pathProperty; } @Override public Optional<Path> getConfigPath() { return Optional.ofNullable(configPathProperty().get()); } public ObservableList<DbmsProperty> dbmsesProperty() { return observableListOf(DBMSES); } @Override public Stream<DbmsProperty> dbmses() { return dbmsesProperty().stream(); } @Override public ProjectPropertyMutator mutator() { return DocumentPropertyMutator.of(this); } @Override protected List<String> keyPathEndingWith(String key) { return singletonList(key); } private final static StringConverter<Path> PATH_CONVERTER = new StringConverter<Path>() { @Override public String toString(Path p) { if (p == null) { return null; } else { return p.toString(); } } @Override public Path fromString(String string) { if (string == null) { return null; } else { return Paths.get(string); } } }; }
/** * Copyright 2014 伊永飞 * * 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.ea.core.cache; /** * 缓存池,具体池参数参看IPoolConfig的说明 * * @author yiyongfei * */ public interface ICachePool { public void setMaxTotal(int maxTotal); public void setMaxIdle(int maxIdle); public void setMaxWaitMillis(long maxWaitMillis); public void setTestOnBorrow(boolean testOnBorrow); public void setTestOnReturn(boolean testOnReturn); public void setLifo(boolean lifo); public void setMaxConnectMillis(long maxConnectMillis); public void setEnableHealSession(boolean enableHealSession); public void setHealSessionInterval(long healSessionInterval); public void setFailureMode(boolean failureMode); public void addServer(String address); public ICacheCommands getResource() throws Exception; public void returnResource(ICacheCommands jedis) throws Exception; }
/* * Copyright (C) 2010 ZXing 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 com.sitech.oncon.barcode.core; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.BatteryManager; import android.util.Log; import com.sitech.oncon.barcode.executor.AsyncTaskExecInterface; import com.sitech.oncon.barcode.executor.AsyncTaskExecManager; /** * Finishes an activity after a period of inactivity if the device is on battery * power. */ final class InactivityTimer { private static final String TAG = InactivityTimer.class.getSimpleName(); private static final long INACTIVITY_DELAY_MS = 5 * 60 * 1000L; private final Activity activity; private final AsyncTaskExecInterface taskExec; private final BroadcastReceiver powerStatusReceiver; private InactivityAsyncTask inactivityTask; InactivityTimer(Activity activity) { this.activity = activity; taskExec = new AsyncTaskExecManager().build(); powerStatusReceiver = new PowerStatusReceiver(); onActivity(); } synchronized void onActivity() { cancel(); inactivityTask = new InactivityAsyncTask(); taskExec.execute(inactivityTask); } public void onPause() { cancel(); activity.unregisterReceiver(powerStatusReceiver); } public void onResume() { activity.registerReceiver(powerStatusReceiver, new IntentFilter( Intent.ACTION_BATTERY_CHANGED)); onActivity(); } private synchronized void cancel() { AsyncTask<?, ?, ?> task = inactivityTask; if (task != null) { task.cancel(true); inactivityTask = null; } } void shutdown() { cancel(); } private final class PowerStatusReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) { // 0 indicates that we're on battery boolean onBatteryNow = intent.getIntExtra( BatteryManager.EXTRA_PLUGGED, -1) <= 0; if (onBatteryNow) { InactivityTimer.this.onActivity(); } else { InactivityTimer.this.cancel(); } } } } private final class InactivityAsyncTask extends AsyncTask<Object, Object, Object> { @Override protected Object doInBackground(Object... objects) { try { Thread.sleep(INACTIVITY_DELAY_MS); Log.i(TAG, "Finishing activity due to inactivity"); activity.finish(); } catch (InterruptedException e) { // continue without killing } return null; } } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.jrt; import java.nio.ByteBuffer; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ValuesTest { @org.junit.Test public void testEmpty() { Values src = new Values(); assertEquals(src.bytes(), 4); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), 4); Values dst = new Values(); dst.decode(buf); assertEquals(dst.bytes(), 4); } void checkSingleValue(Values v, byte type, int bytes) { assertEquals(v.size(), 1); assertEquals(v.get(0).type(), type); assertEquals(v.bytes(), bytes); } @org.junit.Test public void testInt8() { int byteSize = 4 + 1 + 1; Values src = new Values(); src.add(new Int8Value((byte)1)); checkSingleValue(src, Value.INT8, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.INT8, byteSize); assertEquals(dst.get(0).asInt8(), (byte)1); } @org.junit.Test public void testInt8Array() { int byteSize = 4 + 1 + 4 + 4; Values src = new Values(); byte[] val = { 1, 2, 3, 4 }; src.add(new Int8Array(val)); checkSingleValue(src, Value.INT8_ARRAY, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.INT8_ARRAY, byteSize); assertTrue(Arrays.equals(dst.get(0).asInt8Array(), val)); } @org.junit.Test public void testInt16() { int byteSize = 4 + 1 + 2; Values src = new Values(); src.add(new Int16Value((short)2)); checkSingleValue(src, Value.INT16, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.INT16, byteSize); assertEquals(dst.get(0).asInt16(), (short)2); } @org.junit.Test public void testInt16Array() { int byteSize = 4 + 1 + 4 + 4 * 2; Values src = new Values(); short[] val = { 2, 4, 6, 8 }; src.add(new Int16Array(val)); checkSingleValue(src, Value.INT16_ARRAY, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.INT16_ARRAY, byteSize); assertTrue(Arrays.equals(dst.get(0).asInt16Array(), val)); } @org.junit.Test public void testInt32() { int byteSize = 4 + 1 + 4; Values src = new Values(); src.add(new Int32Value(4)); checkSingleValue(src, Value.INT32, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.INT32, byteSize); assertEquals(dst.get(0).asInt32(), 4); } @org.junit.Test public void testInt32Array() { int byteSize = 4 + 1 + 4 + 4 * 4; Values src = new Values(); int[] val = { 4, 8, 12, 16 }; src.add(new Int32Array(val)); checkSingleValue(src, Value.INT32_ARRAY, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.INT32_ARRAY, byteSize); assertTrue(Arrays.equals(dst.get(0).asInt32Array(), val)); } @org.junit.Test public void testInt64() { int byteSize = 4 + 1 + 8; Values src = new Values(); src.add(new Int64Value(8)); checkSingleValue(src, Value.INT64, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.INT64, byteSize); assertEquals(dst.get(0).asInt64(), 8); } @org.junit.Test public void testInt64Array() { int byteSize = 4 + 1 + 4 + 4 * 8; Values src = new Values(); long[] val = { 8, 16, 24, 32 }; src.add(new Int64Array(val)); checkSingleValue(src, Value.INT64_ARRAY, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.INT64_ARRAY, byteSize); assertTrue(Arrays.equals(dst.get(0).asInt64Array(), val)); } @org.junit.Test public void testFloat() { int byteSize = 4 + 1 + 4; Values src = new Values(); src.add(new FloatValue((float)2.5)); checkSingleValue(src, Value.FLOAT, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.FLOAT, byteSize); assertTrue(dst.get(0).asFloat() == (float)2.5); } @org.junit.Test public void testFloatArray() { int byteSize = 4 + 1 + 4 + 4 * 4; Values src = new Values(); float[] val = { 1.5f, 2.0f, 2.5f, 3.0f }; src.add(new FloatArray(val)); checkSingleValue(src, Value.FLOAT_ARRAY, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.FLOAT_ARRAY, byteSize); assertTrue(Arrays.equals(dst.get(0).asFloatArray(), val)); } @org.junit.Test public void testDouble() { int byteSize = 4 + 1 + 8; Values src = new Values(); src.add(new DoubleValue(3.75)); checkSingleValue(src, Value.DOUBLE, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.DOUBLE, byteSize); assertTrue(dst.get(0).asDouble() == 3.75); } @org.junit.Test public void testDoubleArray() { int byteSize = 4 + 1 + 4 + 4 * 8; Values src = new Values(); double[] val = { 1.25, 1.50, 1.75, 2.00 }; src.add(new DoubleArray(val)); checkSingleValue(src, Value.DOUBLE_ARRAY, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.DOUBLE_ARRAY, byteSize); assertTrue(Arrays.equals(dst.get(0).asDoubleArray(), val)); } @org.junit.Test public void testData() { int byteSize = 4 + 1 + 4 + 4; Values src = new Values(); byte[] val = { 1, 2, 3, 4 }; src.add(new DataValue(val)); checkSingleValue(src, Value.DATA, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.DATA, byteSize); assertTrue(Arrays.equals(dst.get(0).asData(), val)); } @org.junit.Test public void testDataArray() { int byteSize = 4 + 1 + 4 + 4 * (4 + 4); Values src = new Values(); byte[][] val = {{ 1, 0, 1, 0 }, { 0, 2, 0, 2 }, { 3, 0, 3, 0 }, { 0, 4, 0, 4 }}; src.add(new DataArray(val)); checkSingleValue(src, Value.DATA_ARRAY, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.DATA_ARRAY, byteSize); assertTrue(Arrays.equals(dst.get(0).asDataArray()[0], val[0])); assertTrue(Arrays.equals(dst.get(0).asDataArray()[1], val[1])); assertTrue(Arrays.equals(dst.get(0).asDataArray()[2], val[2])); assertTrue(Arrays.equals(dst.get(0).asDataArray()[3], val[3])); } @org.junit.Test public void testString1() { int byteSize = 4 + 1 + 4 + 4; Values src = new Values(); String val = "test"; src.add(new StringValue(val)); checkSingleValue(src, Value.STRING, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.STRING, byteSize); assertTrue(dst.get(0).asString().equals("test")); } @org.junit.Test public void testString2() { int byteSize = 4 + 1 + 4 + 7; Values src = new Values(); String val = "H" + ((char)229) + "vard"; src.add(new StringValue(val)); checkSingleValue(src, Value.STRING, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); byte right[] = new byte[] { 0, 0, 0, 1, 's', 0, 0, 0, 7, 'H', (byte)(0xC0 | (0xE5 >> 6)), (byte)(0x80 | (0xE5 & 0x3F)), 'v', 'a', 'r', 'd' }; for (int ii = 0; ii < buf.remaining(); ++ii) { assertEquals(buf.get(ii), right[ii]); } Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.STRING, byteSize); assertTrue(dst.get(0).asString().equals("H\u00E5vard")); } @org.junit.Test public void testStringArray() { int byteSize = 4 + 1 + 4 + 4 * 4 + 3 + 3 + 5 + 4; Values src = new Values(); String[] val = { "one", "two", "three", "four" }; src.add(new StringArray(val)); checkSingleValue(src, Value.STRING_ARRAY, byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); checkSingleValue(src, Value.STRING_ARRAY, byteSize); assertTrue(dst.get(0).asStringArray()[0].equals("one")); assertTrue(dst.get(0).asStringArray()[1].equals("two")); assertTrue(dst.get(0).asStringArray()[2].equals("three")); assertTrue(dst.get(0).asStringArray()[3].equals("four")); } @org.junit.Test public void testAllValues() { int byteSize = 4 + 16 // typestring + 1 // int8 + 4 + 4 // int8 array + 2 // int16 + 4 + 4 * 2 // int16 array + 4 // int32 + 4 + 4 * 4 // int32 array + 8 // int64 + 4 + 4 * 8 // int64 array + 4 // float + 4 + 4 * 4 // float array + 8 // double + 4 + 4 * 8 // double array + 4 + 4 // data + 4 + 4 * 4 + 4 + 4 + 4 + 4 // data array + 4 + 4 // string + 4 + 4 * 4 + 3 + 3 + 5 + 4; // string array byte[] dataValue = { 1, 2, 3, 4 }; byte[] int8Array = { 1, 2, 3, 4 }; short[] int16Array = { 2, 4, 6, 8 }; int[] int32Array = { 4, 8, 12, 16 }; long[] int64Array = { 8, 16, 24, 32 }; float[] floatArray = { 1.5f, 2.0f, 2.5f, 3.0f }; double[] doubleArray = { 1.25, 1.50, 1.75, 2.00 }; byte[][] dataArray = {{ 1, 0, 1, 0 }, { 0, 2, 0, 2 }, { 3, 0, 3, 0 }, { 0, 4, 0, 4 }}; String[] stringArray = { "one", "two", "three", "four" }; Values src = new Values(); src.add(new Int8Value((byte)1)); src.add(new Int8Array(int8Array)); src.add(new Int16Value((short)2)); src.add(new Int16Array(int16Array)); src.add(new Int32Value(4)); src.add(new Int32Array(int32Array)); src.add(new Int64Value(8)); src.add(new Int64Array(int64Array)); src.add(new FloatValue(2.5f)); src.add(new FloatArray(floatArray)); src.add(new DoubleValue(3.75)); src.add(new DoubleArray(doubleArray)); src.add(new DataValue(dataValue)); src.add(new DataArray(dataArray)); src.add(new StringValue("test")); src.add(new StringArray(stringArray)); assertEquals(src.size(), 16); assertEquals(src.bytes(), byteSize); ByteBuffer buf = ByteBuffer.allocate(src.bytes()); src.encode(buf); buf.flip(); assertEquals(buf.remaining(), byteSize); Values dst = new Values(); dst.decode(buf); assertEquals(dst.get(0).asInt8(), (byte)1); assertTrue(Arrays.equals(dst.get(1).asInt8Array(), int8Array)); assertEquals(dst.get(2).asInt16(), (short)2); assertTrue(Arrays.equals(dst.get(3).asInt16Array(), int16Array)); assertEquals(dst.get(4).asInt32(), 4); assertTrue(Arrays.equals(dst.get(5).asInt32Array(), int32Array)); assertEquals(dst.get(6).asInt64(), 8); assertTrue(Arrays.equals(dst.get(7).asInt64Array(), int64Array)); assertTrue(dst.get(8).asFloat() == (float)2.5); assertTrue(Arrays.equals(dst.get(9).asFloatArray(), floatArray)); assertTrue(dst.get(10).asDouble() == 3.75); assertTrue(Arrays.equals(dst.get(11).asDoubleArray(), doubleArray)); assertTrue(Arrays.equals(dst.get(12).asData(), dataValue)); assertTrue(Arrays.equals(dst.get(13).asDataArray()[0], dataArray[0])); assertTrue(Arrays.equals(dst.get(13).asDataArray()[1], dataArray[1])); assertTrue(Arrays.equals(dst.get(13).asDataArray()[2], dataArray[2])); assertTrue(Arrays.equals(dst.get(13).asDataArray()[3], dataArray[3])); assertTrue(dst.get(14).asString().equals("test")); assertTrue(dst.get(15).asStringArray()[0].equals("one")); assertTrue(dst.get(15).asStringArray()[1].equals("two")); assertTrue(dst.get(15).asStringArray()[2].equals("three")); assertTrue(dst.get(15).asStringArray()[3].equals("four")); } }
package org.smartregister.kdp.pojo; public class UpdateDefaulterForm { private String id; private String baseEntityId; private String visitId; private String phoneTracingOutcome; private String physicalTracingOutcome; private String phoneTracing; private String physicalTracing; private String homeAdministrationDate; private String otherFacilityAdministrationDate; private String otherFacilityName; private String dateToConfirmVaccination; private String modeOfTracing; private String age; private String date; private String createdAt; public UpdateDefaulterForm() { } public UpdateDefaulterForm(String id, String baseEntityId, String visitId, String phoneTracingOutcome, String physicalTracingOutcome, String phoneTracing, String physicalTracing, String homeAdministrationDate, String otherFacilityAdministrationDate, String otherFacilityName, String dateToConfirmVaccination, String modeOfTracing, String age, String date, String createdAt) { this.id = id; this.baseEntityId = baseEntityId; this.visitId = visitId; this.phoneTracingOutcome = phoneTracingOutcome; this.physicalTracingOutcome = physicalTracingOutcome; this.phoneTracing = phoneTracing; this.physicalTracing = physicalTracing; this.homeAdministrationDate = homeAdministrationDate; this.otherFacilityAdministrationDate = otherFacilityAdministrationDate; this.otherFacilityName = otherFacilityName; this.dateToConfirmVaccination = dateToConfirmVaccination; this.modeOfTracing = modeOfTracing; this.age = age; this.date = date; this.createdAt = createdAt; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBaseEntityId() { return baseEntityId; } public void setBaseEntityId(String baseEntityId) { this.baseEntityId = baseEntityId; } public String getVisitId() { return visitId; } public void setVisitId(String visitId) { this.visitId = visitId; } public String getPhoneTracingOutcome() { return phoneTracingOutcome; } public void setPhoneTracingOutcome(String phoneTracingOutcome) { this.phoneTracingOutcome = phoneTracingOutcome; } public String getPhysicalTracingOutcome() { return physicalTracingOutcome; } public void setPhysicalTracingOutcome(String physicalTracingOutcome) { this.physicalTracingOutcome = physicalTracingOutcome; } public String getPhoneTracing() { return phoneTracing; } public void setPhoneTracing(String phoneTracing) { this.phoneTracing = phoneTracing; } public String getPhysicalTracing() { return physicalTracing; } public void setPhysicalTracing(String physicalTracing) { this.physicalTracing = physicalTracing; } public String getHomeAdministrationDate() { return homeAdministrationDate; } public void setHomeAdministrationDate(String homeAdministrationDate) { this.homeAdministrationDate = homeAdministrationDate; } public String getOtherFacilityAdministrationDate() { return otherFacilityAdministrationDate; } public void setOtherFacilityAdministrationDate(String otherFacilityAdministrationDate) { this.otherFacilityAdministrationDate = otherFacilityAdministrationDate; } public String getOtherFacilityName() { return otherFacilityName; } public void setOtherFacilityName(String otherFacilityName) { this.otherFacilityName = otherFacilityName; } public String getDateToConfirmVaccination() { return dateToConfirmVaccination; } public void setDateToConfirmVaccination(String dateToConfirmVaccination) { this.dateToConfirmVaccination = dateToConfirmVaccination; } public String getModeOfTracing() { return modeOfTracing; } public void setModeOfTracing(String modeOfTracing) { this.modeOfTracing = modeOfTracing; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } }
import java.util.Scanner; public class TravelingAtLightSpeed { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double lightYearsCount = Double.parseDouble(scanner.nextLine()); double lightYearKm = 9450000000000.0; double lightSpeed = 300000.0; double totalSeconds = (lightYearKm / lightSpeed) * lightYearsCount; int weeks = (int)totalSeconds / 60 / 60 / 24 / 7; int days = (int)totalSeconds / 60 / 60 / 24 % 7; int hours = (int)totalSeconds / 60 / 60 % 24; int minutes = (int)totalSeconds / 60 % 60; int seconds = (int)totalSeconds % 60; System.out.printf("%d weeks%n%d days%n%d hours%n%d minutes%n%d seconds", weeks, days, hours, minutes, seconds); } }
/** * WSWhereItem.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package org.talend.mdm.webservice; /** * An And or Or or WhereCondition */ public class WSWhereItem implements java.io.Serializable { private org.talend.mdm.webservice.WSWhereCondition whereCondition; private org.talend.mdm.webservice.WSWhereItem[] whereAnd; private org.talend.mdm.webservice.WSWhereItem[] whereOr; public WSWhereItem() { } public WSWhereItem( org.talend.mdm.webservice.WSWhereCondition whereCondition, org.talend.mdm.webservice.WSWhereItem[] whereAnd, org.talend.mdm.webservice.WSWhereItem[] whereOr) { this.whereCondition = whereCondition; this.whereAnd = whereAnd; this.whereOr = whereOr; } /** * Gets the whereCondition value for this WSWhereItem. * * @return whereCondition */ public org.talend.mdm.webservice.WSWhereCondition getWhereCondition() { return whereCondition; } /** * Sets the whereCondition value for this WSWhereItem. * * @param whereCondition */ public void setWhereCondition(org.talend.mdm.webservice.WSWhereCondition whereCondition) { this.whereCondition = whereCondition; } /** * Gets the whereAnd value for this WSWhereItem. * * @return whereAnd */ public org.talend.mdm.webservice.WSWhereItem[] getWhereAnd() { return whereAnd; } /** * Sets the whereAnd value for this WSWhereItem. * * @param whereAnd */ public void setWhereAnd(org.talend.mdm.webservice.WSWhereItem[] whereAnd) { this.whereAnd = whereAnd; } /** * Gets the whereOr value for this WSWhereItem. * * @return whereOr */ public org.talend.mdm.webservice.WSWhereItem[] getWhereOr() { return whereOr; } /** * Sets the whereOr value for this WSWhereItem. * * @param whereOr */ public void setWhereOr(org.talend.mdm.webservice.WSWhereItem[] whereOr) { this.whereOr = whereOr; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof WSWhereItem)) return false; WSWhereItem other = (WSWhereItem) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.whereCondition==null && other.getWhereCondition()==null) || (this.whereCondition!=null && this.whereCondition.equals(other.getWhereCondition()))) && ((this.whereAnd==null && other.getWhereAnd()==null) || (this.whereAnd!=null && java.util.Arrays.equals(this.whereAnd, other.getWhereAnd()))) && ((this.whereOr==null && other.getWhereOr()==null) || (this.whereOr!=null && java.util.Arrays.equals(this.whereOr, other.getWhereOr()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getWhereCondition() != null) { _hashCode += getWhereCondition().hashCode(); } if (getWhereAnd() != null) { for (int i=0; i<java.lang.reflect.Array.getLength(getWhereAnd()); i++) { java.lang.Object obj = java.lang.reflect.Array.get(getWhereAnd(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } if (getWhereOr() != null) { for (int i=0; i<java.lang.reflect.Array.getLength(getWhereOr()); i++) { java.lang.Object obj = java.lang.reflect.Array.get(getWhereOr(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(WSWhereItem.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("urn-com-amalto-xtentis-webservice", "WSWhereItem")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("whereCondition"); elemField.setXmlName(new javax.xml.namespace.QName("", "whereCondition")); elemField.setXmlType(new javax.xml.namespace.QName("urn-com-amalto-xtentis-webservice", "WSWhereCondition")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("whereAnd"); elemField.setXmlName(new javax.xml.namespace.QName("", "whereAnd")); elemField.setXmlType(new javax.xml.namespace.QName("urn-com-amalto-xtentis-webservice", "WSWhereItem")); elemField.setMinOccurs(0); elemField.setNillable(false); elemField.setItemQName(new javax.xml.namespace.QName("", "whereItems")); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("whereOr"); elemField.setXmlName(new javax.xml.namespace.QName("", "whereOr")); elemField.setXmlType(new javax.xml.namespace.QName("urn-com-amalto-xtentis-webservice", "WSWhereItem")); elemField.setMinOccurs(0); elemField.setNillable(false); elemField.setItemQName(new javax.xml.namespace.QName("", "whereItems")); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
package com.stang.tang.zhima.service.impl; import com.stang.tang.zhima.service.TagService; public class TagServiceImpl implements TagService { }
package tree; public class BinarySearchTree<T extends Comparable<T>> { public Node root; public boolean insert(T i) { if (root == null) { root = new Node(i); return true; } Node current = root; while (true) { // 如果 i 比当前结点的值小 if (i.compareTo((T) current.data) < 0) { if (current.left != null) { current = current.left; } else { current.left = new Node(i); break; } } else { if (current.right != null) current = current.right; else { current.right = new Node(i); break; } } } return true; } public boolean contains(T t) { if (t == null) { return false; } Node current = this.root; while (true) { if (t.compareTo((T) current.data) < 0) { if (current.left == null) { return false; } current = current.left; } else if (t.compareTo((T) current.data) > 0) { if (current.right == null) { return false; } current = current.right; } else { return true; } } } public void preOrder(Node<T> n) { if (n == null) { return; } System.out.println(n.data); if (n.left != null) preOrder(n.left); if (n.right != null) preOrder(n.right); } public void midOrder(Node n) { if (n == null) { return; } if (n.left != null) midOrder(n.left); System.out.println(n.data); if (n.right != null) midOrder(n.right); } public void sufOrder(Node n) { if (n == null) { return; } if (n.left != null) sufOrder(n.left); if (n.right != null) sufOrder(n.right); System.out.println(n.data); } }
package rewards; import java.io.Serializable; /** * A summary of a confirmed reward transaction describing a contribution made to an account that was distributed among * the account's beneficiaries. */ @SuppressWarnings("serial") public class RewardConfirmation implements Serializable { private String confirmationNumber; private AccountContribution accountContribution; /** * Creates a new reward confirmation. * @param confirmationNumber the unique confirmation number * @param accountContribution a summary of the account contribution that was made */ public RewardConfirmation(String confirmationNumber, AccountContribution accountContribution) { this.confirmationNumber = confirmationNumber; this.accountContribution = accountContribution; } /** * Returns the confirmation number of the reward transaction. Can be used later to lookup the transaction record. */ public String getConfirmationNumber() { return confirmationNumber; } /** * Returns a summary of the monetary contribution that was made to an account. * @return the account contribution (the details of this reward) */ public AccountContribution getAccountContribution() { return accountContribution; } @Override public String toString() { return String.format("Reward of %s applied to account %s. RewardConfirmation id is: %s", accountContribution.getAmount(), accountContribution.getAccountNumber(), confirmationNumber); } @Override public int hashCode() { return accountContribution.hashCode() + confirmationNumber.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof RewardConfirmation)) { return false; } RewardConfirmation other = (RewardConfirmation) o; // value objects are equal if their attributes are equal return accountContribution.equals(other.accountContribution) && confirmationNumber.equals(other.confirmationNumber); } }
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.gameservices.v1.model; /** * An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud * resources. A `Policy` is a collection of `bindings`. A `binding` binds one or more `members` to a * single `role`. Members can be user accounts, service accounts, Google groups, and domains (such * as G Suite). A `role` is a named list of permissions; each `role` can be an IAM predefined role * or a user-created custom role. For some types of Google Cloud resources, a `binding` can also * specify a `condition`, which is a logical expression that allows access to a resource only if the * expression evaluates to `true`. A condition can add constraints based on attributes of the * request, the resource, or both. To learn which resources support conditions in their IAM * policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource- * policies). **JSON example:** { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", * "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", * "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": * "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { * "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": * "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": * 3 } **YAML example:** bindings: - members: - user:mike@example.com - group:admins@example.com - * domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: * roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: * roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not * grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - * etag: BwWWja0YfJA= - version: 3 For a description of IAM and its features, see the [IAM * documentation](https://cloud.google.com/iam/docs/). * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Game Services API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Policy extends com.google.api.client.json.GenericJson { /** * Specifies cloud audit logging configuration for this policy. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<AuditConfig> auditConfigs; static { // hack to force ProGuard to consider AuditConfig used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(AuditConfig.class); } /** * Associates a list of `members` to a `role`. Optionally, may specify a `condition` that * determines how and when the `bindings` are applied. Each of the `bindings` must contain at * least one member. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Binding> bindings; static { // hack to force ProGuard to consider Binding used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Binding.class); } /** * `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates * of a policy from overwriting each other. It is strongly suggested that systems make use of the * `etag` in the read-modify-write cycle to perform policy updates in order to avoid race * conditions: An `etag` is returned in the response to `getIamPolicy`, and systems are expected * to put that etag in the request to `setIamPolicy` to ensure that their change will be applied * to the same version of the policy. **Important:** If you use IAM Conditions, you must include * the `etag` field whenever you call `setIamPolicy`. If you omit this field, then IAM allows you * to overwrite a version `3` policy with a version `1` policy, and all of the conditions in the * version `3` policy are lost. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String etag; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean iamOwned; /** * If more than one rule is specified, the rules are applied in the following manner: - All * matching LOG rules are always applied. - If any DENY/DENY_WITH_LOG rule matches, permission is * denied. Logging will be applied if one or more matching rule requires logging. - Otherwise, if * any ALLOW/ALLOW_WITH_LOG rule matches, permission is granted. Logging will be applied if one or * more matching rule requires logging. - Otherwise, if no rule applies, permission is denied. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Rule> rules; /** * Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify * an invalid value are rejected. Any operation that affects conditional role bindings must * specify version `3`. This requirement applies to the following operations: * Getting a policy * that includes a conditional role binding * Adding a conditional role binding to a policy * * Changing a conditional role binding in a policy * Removing any role binding, with or without a * condition, from a policy that includes conditions **Important:** If you use IAM Conditions, you * must include the `etag` field whenever you call `setIamPolicy`. If you omit this field, then * IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the * conditions in the version `3` policy are lost. If a policy does not include any conditions, * operations on that policy may specify any valid version or leave the field unset. To learn * which resources support conditions in their IAM policies, see the [IAM * documentation](https://cloud.google.com/iam/help/conditions/resource-policies). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer version; /** * Specifies cloud audit logging configuration for this policy. * @return value or {@code null} for none */ public java.util.List<AuditConfig> getAuditConfigs() { return auditConfigs; } /** * Specifies cloud audit logging configuration for this policy. * @param auditConfigs auditConfigs or {@code null} for none */ public Policy setAuditConfigs(java.util.List<AuditConfig> auditConfigs) { this.auditConfigs = auditConfigs; return this; } /** * Associates a list of `members` to a `role`. Optionally, may specify a `condition` that * determines how and when the `bindings` are applied. Each of the `bindings` must contain at * least one member. * @return value or {@code null} for none */ public java.util.List<Binding> getBindings() { return bindings; } /** * Associates a list of `members` to a `role`. Optionally, may specify a `condition` that * determines how and when the `bindings` are applied. Each of the `bindings` must contain at * least one member. * @param bindings bindings or {@code null} for none */ public Policy setBindings(java.util.List<Binding> bindings) { this.bindings = bindings; return this; } /** * `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates * of a policy from overwriting each other. It is strongly suggested that systems make use of the * `etag` in the read-modify-write cycle to perform policy updates in order to avoid race * conditions: An `etag` is returned in the response to `getIamPolicy`, and systems are expected * to put that etag in the request to `setIamPolicy` to ensure that their change will be applied * to the same version of the policy. **Important:** If you use IAM Conditions, you must include * the `etag` field whenever you call `setIamPolicy`. If you omit this field, then IAM allows you * to overwrite a version `3` policy with a version `1` policy, and all of the conditions in the * version `3` policy are lost. * @see #decodeEtag() * @return value or {@code null} for none */ public java.lang.String getEtag() { return etag; } /** * `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates * of a policy from overwriting each other. It is strongly suggested that systems make use of the * `etag` in the read-modify-write cycle to perform policy updates in order to avoid race * conditions: An `etag` is returned in the response to `getIamPolicy`, and systems are expected * to put that etag in the request to `setIamPolicy` to ensure that their change will be applied * to the same version of the policy. **Important:** If you use IAM Conditions, you must include * the `etag` field whenever you call `setIamPolicy`. If you omit this field, then IAM allows you * to overwrite a version `3` policy with a version `1` policy, and all of the conditions in the * version `3` policy are lost. * @see #getEtag() * @return Base64 decoded value or {@code null} for none * * @since 1.14 */ public byte[] decodeEtag() { return com.google.api.client.util.Base64.decodeBase64(etag); } /** * `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates * of a policy from overwriting each other. It is strongly suggested that systems make use of the * `etag` in the read-modify-write cycle to perform policy updates in order to avoid race * conditions: An `etag` is returned in the response to `getIamPolicy`, and systems are expected * to put that etag in the request to `setIamPolicy` to ensure that their change will be applied * to the same version of the policy. **Important:** If you use IAM Conditions, you must include * the `etag` field whenever you call `setIamPolicy`. If you omit this field, then IAM allows you * to overwrite a version `3` policy with a version `1` policy, and all of the conditions in the * version `3` policy are lost. * @see #encodeEtag() * @param etag etag or {@code null} for none */ public Policy setEtag(java.lang.String etag) { this.etag = etag; return this; } /** * `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates * of a policy from overwriting each other. It is strongly suggested that systems make use of the * `etag` in the read-modify-write cycle to perform policy updates in order to avoid race * conditions: An `etag` is returned in the response to `getIamPolicy`, and systems are expected * to put that etag in the request to `setIamPolicy` to ensure that their change will be applied * to the same version of the policy. **Important:** If you use IAM Conditions, you must include * the `etag` field whenever you call `setIamPolicy`. If you omit this field, then IAM allows you * to overwrite a version `3` policy with a version `1` policy, and all of the conditions in the * version `3` policy are lost. * @see #setEtag() * * <p> * The value is encoded Base64 or {@code null} for none. * </p> * * @since 1.14 */ public Policy encodeEtag(byte[] etag) { this.etag = com.google.api.client.util.Base64.encodeBase64URLSafeString(etag); return this; } /** * @return value or {@code null} for none */ public java.lang.Boolean getIamOwned() { return iamOwned; } /** * @param iamOwned iamOwned or {@code null} for none */ public Policy setIamOwned(java.lang.Boolean iamOwned) { this.iamOwned = iamOwned; return this; } /** * If more than one rule is specified, the rules are applied in the following manner: - All * matching LOG rules are always applied. - If any DENY/DENY_WITH_LOG rule matches, permission is * denied. Logging will be applied if one or more matching rule requires logging. - Otherwise, if * any ALLOW/ALLOW_WITH_LOG rule matches, permission is granted. Logging will be applied if one or * more matching rule requires logging. - Otherwise, if no rule applies, permission is denied. * @return value or {@code null} for none */ public java.util.List<Rule> getRules() { return rules; } /** * If more than one rule is specified, the rules are applied in the following manner: - All * matching LOG rules are always applied. - If any DENY/DENY_WITH_LOG rule matches, permission is * denied. Logging will be applied if one or more matching rule requires logging. - Otherwise, if * any ALLOW/ALLOW_WITH_LOG rule matches, permission is granted. Logging will be applied if one or * more matching rule requires logging. - Otherwise, if no rule applies, permission is denied. * @param rules rules or {@code null} for none */ public Policy setRules(java.util.List<Rule> rules) { this.rules = rules; return this; } /** * Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify * an invalid value are rejected. Any operation that affects conditional role bindings must * specify version `3`. This requirement applies to the following operations: * Getting a policy * that includes a conditional role binding * Adding a conditional role binding to a policy * * Changing a conditional role binding in a policy * Removing any role binding, with or without a * condition, from a policy that includes conditions **Important:** If you use IAM Conditions, you * must include the `etag` field whenever you call `setIamPolicy`. If you omit this field, then * IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the * conditions in the version `3` policy are lost. If a policy does not include any conditions, * operations on that policy may specify any valid version or leave the field unset. To learn * which resources support conditions in their IAM policies, see the [IAM * documentation](https://cloud.google.com/iam/help/conditions/resource-policies). * @return value or {@code null} for none */ public java.lang.Integer getVersion() { return version; } /** * Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify * an invalid value are rejected. Any operation that affects conditional role bindings must * specify version `3`. This requirement applies to the following operations: * Getting a policy * that includes a conditional role binding * Adding a conditional role binding to a policy * * Changing a conditional role binding in a policy * Removing any role binding, with or without a * condition, from a policy that includes conditions **Important:** If you use IAM Conditions, you * must include the `etag` field whenever you call `setIamPolicy`. If you omit this field, then * IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the * conditions in the version `3` policy are lost. If a policy does not include any conditions, * operations on that policy may specify any valid version or leave the field unset. To learn * which resources support conditions in their IAM policies, see the [IAM * documentation](https://cloud.google.com/iam/help/conditions/resource-policies). * @param version version or {@code null} for none */ public Policy setVersion(java.lang.Integer version) { this.version = version; return this; } @Override public Policy set(String fieldName, Object value) { return (Policy) super.set(fieldName, value); } @Override public Policy clone() { return (Policy) super.clone(); } }
package com.himo.app; import java.io.Serializable; import org.springframework.stereotype.Service; @Service public class GreetService implements Serializable { public String greet(String name) { if (name == null || name.isEmpty()) { return "Hello anonymous user"; } else { return "Hello " + name; } } }
/* * Copyright (C) 2009 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.android.inputmethod.pinyin; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.FontMetricsInt; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; /** * View used to show composing string (The Pinyin string for the unselected * syllables and the Chinese string for the selected syllables.) */ public class ComposingView extends View { /** * <p> * There are three statuses for the composing view. * </p> * * <p> * {@link #SHOW_PINYIN} is used to show the current Pinyin string without * highlighted effect. When user inputs Pinyin characters one by one, the * Pinyin string will be shown in this mode. * </p> * <p> * {@link #SHOW_STRING_LOWERCASE} is used to show the Pinyin string in * lowercase with highlighted effect. When user presses UP key and there is * no fixed Chinese characters, composing view will switch from * {@link #SHOW_PINYIN} to this mode, and in this mode, user can press * confirm key to input the lower-case string, so that user can input * English letter in Chinese mode. * </p> * <p> * {@link #EDIT_PINYIN} is used to edit the Pinyin string (shown with * highlighted effect). When current status is {@link #SHOW_PINYIN} and user * presses UP key, if there are fixed Characters, the input method will * switch to {@link #EDIT_PINYIN} thus user can modify some characters in * the middle of the Pinyin string. If the current status is * {@link #SHOW_STRING_LOWERCASE} and user presses LEFT and RIGHT key, it * will also switch to {@link #EDIT_PINYIN}. * </p> * <p> * Whenever user presses down key, the status switches to * {@link #SHOW_PINYIN}. * </p> * <p> * When composing view's status is {@link #SHOW_PINYIN}, the IME's status is * {@link PinyinIME.ImeState#STATE_INPUT}, otherwise, the IME's status * should be {@link PinyinIME.ImeState#STATE_COMPOSING}. * </p> */ public enum ComposingStatus { SHOW_PINYIN, SHOW_STRING_LOWERCASE, EDIT_PINYIN, } private static final int LEFT_RIGHT_MARGIN = 5; /** * Used to draw composing string. When drawing the active and idle part of * the spelling(Pinyin) string, the color may be changed. */ private Paint mPaint; /** * Drawable used to draw highlight effect. */ private Drawable mHlDrawable; /** * Drawable used to draw cursor for editing mode. */ private Drawable mCursor; /** * Used to estimate dimensions to show the string . */ private FontMetricsInt mFmi; private int mStrColor; private int mStrColorHl; private int mStrColorIdle; private int mFontSize; private ComposingStatus mComposingStatus; PinyinIME.DecodingInfo mDecInfo; public ComposingView(Context context, AttributeSet attrs) { super(context, attrs); Resources r = context.getResources(); mHlDrawable = r.getDrawable(R.drawable.composing_hl_bg); mCursor = r.getDrawable(R.drawable.composing_area_cursor); mStrColor = r.getColor(R.color.composing_color); mStrColorHl = r.getColor(R.color.composing_color_hl); mStrColorIdle = r.getColor(R.color.composing_color_idle); mFontSize = r.getDimensionPixelSize(R.dimen.composing_height); mPaint = new Paint(); mPaint.setColor(mStrColor); mPaint.setAntiAlias(true); mPaint.setTextSize(mFontSize); mFmi = mPaint.getFontMetricsInt(); } public void reset() { mComposingStatus = ComposingStatus.SHOW_PINYIN; } /** * Set the composing string to show. If the IME status is * {@link PinyinIME.ImeState#STATE_INPUT}, the composing view's status will * be set to {@link ComposingStatus#SHOW_PINYIN}, otherwise the composing * view will set its status to {@link ComposingStatus#SHOW_STRING_LOWERCASE} * or {@link ComposingStatus#EDIT_PINYIN} automatically. */ public void setDecodingInfo(PinyinIME.DecodingInfo decInfo, PinyinIME.ImeState imeStatus) { mDecInfo = decInfo; if (PinyinIME.ImeState.STATE_INPUT == imeStatus) { mComposingStatus = ComposingStatus.SHOW_PINYIN; mDecInfo.moveCursorToEdge(false); } else { if (decInfo.getFixedLen() != 0 || ComposingStatus.EDIT_PINYIN == mComposingStatus) { mComposingStatus = ComposingStatus.EDIT_PINYIN; } else { mComposingStatus = ComposingStatus.SHOW_STRING_LOWERCASE; } mDecInfo.moveCursor(0); } measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); requestLayout(); invalidate(); } public boolean moveCursor(int keyCode) { if (keyCode != KeyEvent.KEYCODE_DPAD_LEFT && keyCode != KeyEvent.KEYCODE_DPAD_RIGHT) return false; if (ComposingStatus.EDIT_PINYIN == mComposingStatus) { int offset = 0; if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) offset = -1; else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) offset = 1; mDecInfo.moveCursor(offset); } else if (ComposingStatus.SHOW_STRING_LOWERCASE == mComposingStatus) { if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { mComposingStatus = ComposingStatus.EDIT_PINYIN; measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); requestLayout(); } } invalidate(); return true; } public ComposingStatus getComposingStatus() { return mComposingStatus; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { float width; int height; height = mFmi.bottom - mFmi.top + mPaddingTop + mPaddingBottom; if (null == mDecInfo) { width = 0; } else { width = mPaddingLeft + mPaddingRight + LEFT_RIGHT_MARGIN * 2; String str; if (ComposingStatus.SHOW_STRING_LOWERCASE == mComposingStatus) { str = mDecInfo.getOrigianlSplStr().toString(); } else { str = mDecInfo.getComposingStrForDisplay(); } width += mPaint.measureText(str, 0, str.length()); } setMeasuredDimension((int) (width + 0.5f), height); } @Override protected void onDraw(Canvas canvas) { if (ComposingStatus.EDIT_PINYIN == mComposingStatus || ComposingStatus.SHOW_PINYIN == mComposingStatus) { drawForPinyin(canvas); return; } float x, y; x = mPaddingLeft + LEFT_RIGHT_MARGIN; y = -mFmi.top + mPaddingTop; mPaint.setColor(mStrColorHl); mHlDrawable.setBounds(mPaddingLeft, mPaddingTop, getWidth() - mPaddingRight, getHeight() - mPaddingBottom); mHlDrawable.draw(canvas); String splStr = mDecInfo.getOrigianlSplStr().toString(); canvas.drawText(splStr, 0, splStr.length(), x, y, mPaint); } private void drawCursor(Canvas canvas, float x) { mCursor.setBounds((int) x, mPaddingTop, (int) x + mCursor.getIntrinsicWidth(), getHeight() - mPaddingBottom); mCursor.draw(canvas); } private void drawForPinyin(Canvas canvas) { float x, y; x = mPaddingLeft + LEFT_RIGHT_MARGIN; y = -mFmi.top + mPaddingTop; mPaint.setColor(mStrColor); int cursorPos = mDecInfo.getCursorPosInCmpsDisplay(); int cmpsPos = cursorPos; String cmpsStr = mDecInfo.getComposingStrForDisplay(); int activeCmpsLen = mDecInfo.getActiveCmpsDisplayLen(); if (cursorPos > activeCmpsLen) cmpsPos = activeCmpsLen; canvas.drawText(cmpsStr, 0, cmpsPos, x, y, mPaint); x += mPaint.measureText(cmpsStr, 0, cmpsPos); if (cursorPos <= activeCmpsLen) { if (ComposingStatus.EDIT_PINYIN == mComposingStatus) { drawCursor(canvas, x); } canvas.drawText(cmpsStr, cmpsPos, activeCmpsLen, x, y, mPaint); } x += mPaint.measureText(cmpsStr, cmpsPos, activeCmpsLen); if (cmpsStr.length() > activeCmpsLen) { mPaint.setColor(mStrColorIdle); int oriPos = activeCmpsLen; if (cursorPos > activeCmpsLen) { if (cursorPos > cmpsStr.length()) cursorPos = cmpsStr.length(); canvas.drawText(cmpsStr, oriPos, cursorPos, x, y, mPaint); x += mPaint.measureText(cmpsStr, oriPos, cursorPos); if (ComposingStatus.EDIT_PINYIN == mComposingStatus) { drawCursor(canvas, x); } oriPos = cursorPos; } canvas.drawText(cmpsStr, oriPos, cmpsStr.length(), x, y, mPaint); } } }
/* * 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 demoapp.dom.domain.properties.Property.optionality; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.Optionality; import org.apache.isis.applib.annotation.Parameter; import org.apache.isis.applib.annotation.ParameterLayout; import org.apache.isis.applib.annotation.SemanticsOf; import lombok.RequiredArgsConstructor; @Action( semantics = SemanticsOf.IDEMPOTENT ) @ActionLayout( associateWith = "mandatoryPropertyUsingAnnotation" , sequence = "1") @RequiredArgsConstructor public class PropertyOptionalityVm_updateMandatoryWithParameterLayout { private final PropertyOptionalityVm propertyOptionalityVm; //tag::annotation[] public PropertyOptionalityVm act( @Parameter( optionality = Optionality.MANDATORY // <.> ) @ParameterLayout( describedAs = "@Parameter(optionality = MANDATORY)" ) final String mandatoryParameterUsingAnnotation) { propertyOptionalityVm.setMandatoryPropertyUsingAnnotation(mandatoryParameterUsingAnnotation); return propertyOptionalityVm; } //end::annotation[] public String default0Act() { return propertyOptionalityVm.getMandatoryPropertyUsingAnnotation(); } }
/* ### * IP: GHIDRA * * 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 agent.gdb.manager.impl; import static ghidra.dbg.testutil.DummyProc.run; import static org.junit.Assert.*; import static org.junit.Assume.assumeFalse; import java.io.IOException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.*; import java.util.concurrent.*; import java.util.stream.Collectors; import org.junit.*; import com.google.common.collect.*; import agent.gdb.manager.*; import agent.gdb.manager.GdbManager.ExecSuffix; import agent.gdb.manager.breakpoint.GdbBreakpointInfo; import ghidra.async.AsyncReference; import ghidra.dbg.testutil.DummyProc; import ghidra.test.AbstractGhidraHeadlessIntegrationTest; import ghidra.util.Msg; import ghidra.util.SystemUtilities; @Ignore("Need correct version for CI") public abstract class AbstractGdbManagerTest extends AbstractGhidraHeadlessIntegrationTest { protected static final long TIMEOUT_MILLISECONDS = SystemUtilities.isInTestingBatchMode() ? 5000 : Long.MAX_VALUE; protected abstract CompletableFuture<Void> startManager(GdbManager manager); protected void stopManager() throws IOException { // Nothing by default } protected <T> T waitOn(CompletableFuture<T> future) throws Throwable { try { return future.get(TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw e.getCause(); } } @After public void tearDownGdbManagerTest() throws IOException { stopManager(); } @Test public void testAddInferior() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); GdbInferior inferior = waitOn(mgr.addInferior()); assertEquals(2, inferior.getId()); assertEquals(Set.of(1, 2), mgr.getKnownInferiors().keySet()); } } @Test public void testRemoveInferior() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); GdbInferior inf = waitOn(mgr.addInferior()); assertEquals(2, mgr.getKnownInferiors().size()); waitOn(inf.remove()); assertEquals(1, mgr.getKnownInferiors().size()); assertEquals(1, mgr.currentInferior().getId()); assertEquals(Set.of(1), mgr.getKnownInferiors().keySet()); } } @Test public void testRemoveCurrentInferior() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { List<Integer> selEvtIdsTemp = new ArrayList<>(); AsyncReference<List<Integer>, Void> selEvtIds = new AsyncReference<>(List.of()); mgr.addEventsListener(new GdbEventsListenerAdapter() { @Override public void inferiorSelected(GdbInferior inferior, GdbCause cause) { selEvtIdsTemp.add(inferior.getId()); selEvtIds.set(List.copyOf(selEvtIdsTemp), null); } }); waitOn(startManager(mgr)); waitOn(selEvtIds.waitValue(List.of(1))); waitOn(mgr.addInferior()); assertEquals(2, mgr.getKnownInferiors().size()); waitOn(mgr.currentInferior().remove()); assertEquals(1, mgr.getKnownInferiors().size()); assertEquals(2, mgr.currentInferior().getId()); assertEquals(Set.of(2), mgr.getKnownInferiors().keySet()); waitOn(selEvtIds.waitValue(List.of(1, 2))); } } @Test public void testConsoleCapture() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); String out = waitOn(mgr.consoleCapture("echo test")); assertEquals("test", out.trim()); } } @Test public void testListInferiors() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); Map<Integer, GdbInferior> inferiors = waitOn(mgr.listInferiors()); assertEquals(new HashSet<>(Arrays.asList(new Integer[] { 1 })), inferiors.keySet()); } } @Test public void testListAvailableProcesses() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); List<GdbProcessThreadGroup> procs = waitOn(mgr.listAvailableProcesses()); List<Integer> pids = procs.stream().map(p -> p.getPid()).collect(Collectors.toList()); assertTrue(pids.contains(1)); // Weak check, but on Linux, 1 (init) is always running } } @Test public void testInfoOs() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); GdbTable infoThreads = waitOn(mgr.infoOs("threads")); assertEquals(new LinkedHashSet<>(Arrays.asList("pid", "command", "tid", "core")), infoThreads.columns().keySet()); assertTrue(infoThreads.columns().get("command").contains("java")); } } @Test public void testStart() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); waitOn(mgr.currentInferior().fileExecAndSymbols("/usr/bin/echo")); waitOn(mgr.console("break main")); GdbThread thread = waitOn(mgr.currentInferior().run()); assertNotNull(thread.getInferior().getPid()); } } @Test public void testAttachDetach() throws Throwable { try (DummyProc echo = run("dd"); GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); Set<GdbThread> threads = waitOn(mgr.currentInferior().attach(echo.pid)); // Attach stops the process, so no need to wait for STOPPED or prompt for (GdbThread t : threads) { assertEquals(echo.pid, (long) t.getInferior().getPid()); waitOn(t.detach()); } } } @Test @Ignore("At developer's desk only") public void stressTestStartInterrupt() throws Throwable { // Just re-run the testStartInterrupt test many,many times for (int i = 0; i < 100; i++) { testStartInterrupt(); } } @Test public void testStartInterrupt() throws Throwable { assumeFalse("I know no way to get this to pass with these conditions", this instanceof JoinedGdbManagerTest); try (GdbManager mgr = GdbManager.newInstance()) { /* * Not sure the details here, but it seems GDB will give ^running as soon as the process * has started. I suspect there are some nuances between the time the process is started * and the time its signal handlers are installed. It seems waiting for libc to load * guarantees that GDB is ready to interrupt the process. */ CompletableFuture<Void> libcLoaded = new CompletableFuture<>(); mgr.addEventsListener(new GdbEventsListenerAdapter() { @Override public void libraryLoaded(GdbInferior inferior, String name, GdbCause cause) { if (name.contains("libc")) { libcLoaded.complete(null); } } }); waitOn(startManager(mgr)); waitOn(mgr.currentInferior().fileExecAndSymbols("/usr/bin/sleep")); waitOn(mgr.currentInferior().console("set args 3")); waitOn(mgr.currentInferior().run()); waitOn(libcLoaded); Thread.sleep(100); // TODO: Why? Msg.debug(this, "Interrupting"); waitOn(mgr.interrupt()); Msg.debug(this, "Waiting for prompt"); waitOn(mgr.waitForPrompt()); Msg.debug(this, "Testing echo test"); String out = waitOn(mgr.consoleCapture("echo test")); // Check that we have a responsive console, now. // Otherwise, the interrupt failed assertEquals("test", out.trim()); } } @Test public void testSetVarEvaluate() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); waitOn(mgr.currentInferior().fileExecAndSymbols("/usr/bin/echo")); waitOn(mgr.insertBreakpoint("main")); waitOn(mgr.currentInferior().run()); waitOn(mgr.waitForState(GdbState.STOPPED)); waitOn(mgr.waitForPrompt()); waitOn(mgr.currentInferior().setVar("$rax=", "0xdeadbeef")); // Corrupts it String val = waitOn(mgr.currentInferior().evaluate("$rax+1")); assertEquals(0xdeadbeef + 1, Integer.parseUnsignedInt(val)); } } @Test public void testSetVarGetVar() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); String val = waitOn(mgr.currentInferior().getVar("args")); assertEquals(null, val); waitOn(mgr.currentInferior().setVar("args", "test")); val = waitOn(mgr.currentInferior().getVar("args")); assertEquals("test", val); } } @Test public void testInsertListDeleteBreakpoint() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); waitOn(mgr.currentInferior().fileExecAndSymbols("/usr/bin/echo")); GdbBreakpointInfo breakpoint = waitOn(mgr.insertBreakpoint("main")); Map<Long, GdbBreakpointInfo> bl = waitOn(mgr.listBreakpoints()); assertEquals(Map.of(1L, breakpoint), bl); waitOn(mgr.deleteBreakpoints(breakpoint.getNumber())); bl = waitOn(mgr.listBreakpoints()); assertEquals(Map.of(), bl); } } @Test public void testListReadWriteReadRegisters() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); waitOn(mgr.currentInferior().fileExecAndSymbols("/usr/bin/echo")); waitOn(mgr.insertBreakpoint("main")); GdbThread thread = waitOn(mgr.currentInferior().run()); waitOn(mgr.waitForState(GdbState.STOPPED)); waitOn(mgr.waitForPrompt()); GdbRegisterSet regs = waitOn(thread.listRegisters()); Set<GdbRegister> toRead = new HashSet<>(); toRead.add(regs.get("eflags")); toRead.add(regs.get("rax")); Map<GdbRegister, BigInteger> read = waitOn(thread.readRegisters(toRead)); // Verify eflags is rendered numerically assertNotNull(read.get(regs.get("eflags"))); assertNotNull(read.get(regs.get("rax"))); Map<GdbRegister, BigInteger> toWrite = new HashMap<>(); // NOTE: Not all flags are mutable from user-space. // Turns out GDB/MI does not honor this, but CLI does.... toWrite.put(regs.get("eflags"), BigInteger.valueOf(0L)); toWrite.put(regs.get("rax"), BigInteger.valueOf(0x1122334455667788L)); waitOn(thread.writeRegisters(toWrite)); toRead = new HashSet<>(); toRead.add(regs.get("eflags")); // Verify register structure is reflected in API toRead.add(regs.get("eax")); read = waitOn(thread.readRegisters(toRead)); // IF and that other reserved bit cannot be cleared // Verified the same behavior in vanilla GDB at the CLI. assertEquals(0x202L, read.get(regs.get("eflags")).longValue()); assertEquals(0x55667788L, read.get(regs.get("eax")).longValue()); } } @Test public void testWriteReadMemory() throws Throwable { ByteBuffer rBuf = ByteBuffer.allocate(1024); try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); waitOn(mgr.currentInferior().fileExecAndSymbols("/usr/bin/echo")); waitOn(mgr.insertBreakpoint("main")); GdbThread thread = waitOn(mgr.currentInferior().run()); waitOn(mgr.waitForState(GdbState.STOPPED)); waitOn(mgr.waitForPrompt()); String str = waitOn(mgr.currentInferior().evaluate("(long)main")); long addr = Long.parseLong(str); ByteBuffer buf = ByteBuffer.allocate(1024); buf.order(ByteOrder.LITTLE_ENDIAN); for (int i = 0; i < 10; i++) { buf.putInt(i); } buf.flip(); waitOn(thread.writeMemory(addr, buf)); RangeSet<Long> rng = waitOn(thread.readMemory(addr, rBuf)); rBuf.flip(); rBuf.order(ByteOrder.LITTLE_ENDIAN); RangeSet<Long> exp = TreeRangeSet.create(); exp.add(Range.closedOpen(addr, addr + 1024)); assertEquals(exp, rng); for (int i = 0; i < 10; i++) { assertEquals(i, rBuf.getInt()); } } } @Test public void testContinue() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); waitOn(mgr.currentInferior().fileExecAndSymbols("/usr/bin/echo")); waitOn(mgr.insertBreakpoint("main")); GdbThread thread = waitOn(mgr.currentInferior().run()); waitOn(mgr.waitForState(GdbState.STOPPED)); waitOn(mgr.waitForPrompt()); waitOn(thread.cont()); waitOn(mgr.waitForState(GdbState.STOPPED)); assertEquals(0L, (long) mgr.currentInferior().getExitCode()); } } @Test public void testStep() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); waitOn(mgr.currentInferior().fileExecAndSymbols("/usr/bin/echo")); waitOn(mgr.insertBreakpoint("main")); GdbThread thread = waitOn(mgr.currentInferior().run()); waitOn(mgr.waitForState(GdbState.STOPPED)); waitOn(mgr.waitForPrompt()); waitOn(thread.step(ExecSuffix.NEXT_INSTRUCTION)); waitOn(mgr.waitForState(GdbState.STOPPED)); assertNull(mgr.currentInferior().getExitCode()); } } @Test public void testThreadSelect() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); waitOn(mgr.currentInferior().fileExecAndSymbols("/usr/bin/echo")); waitOn(mgr.insertBreakpoint("main")); GdbThread thread = waitOn(mgr.currentInferior().run()); waitOn(mgr.waitForState(GdbState.STOPPED)); waitOn(mgr.waitForPrompt()); waitOn(thread.select()); } } @Test public void testListFrames() throws Throwable { try (GdbManager mgr = GdbManager.newInstance()) { waitOn(startManager(mgr)); waitOn(mgr.currentInferior().fileExecAndSymbols("/usr/bin/echo")); waitOn(mgr.insertBreakpoint("main")); GdbThread thread = waitOn(mgr.currentInferior().run()); waitOn(mgr.waitForState(GdbState.STOPPED)); waitOn(mgr.waitForPrompt()); waitOn(mgr.insertBreakpoint("write")); waitOn(mgr.currentInferior().cont()); waitOn(mgr.waitForState(GdbState.STOPPED)); List<GdbStackFrame> stack = waitOn(thread.listStackFrames()); Msg.debug(this, "Got stack:"); for (GdbStackFrame frame : stack) { Msg.debug(this, " " + frame); } assertEquals("write", stack.get(0).getFunction()); assertEquals("main", stack.get(stack.size() - 1).getFunction()); } } }
class Person { String name; String address; long phoneNo; String email; Person(String n,String ad,long pn,String em) { name=n; address=ad; phoneNo=pn; email=em; } public String toString() { return "**class Person**\n name="+name; } void show() { System.out.println("\nAddress="+address); System.out.println("Phone number="+phoneNo); System.out.println("Email="+email); } } class Student extends Person { String status; Student(String n,String ad,long pn,String em,final String st) { super(n,ad,pn,em); status=st; } public String toString() { return "**class Student**\n name="+name; } void show() { super.show(); System.out.println("Status="+status); } } class Employee extends Person { String office; double salary; String dateHired; Employee(final String n,String ad,long pn,String em,String of,double sal,String dh) { super(n,ad,pn,em); office=of; salary=sal; dateHired=dh; } public String toString() { return "**class Employee**\n name="+name; } void show() { super.show(); System.out.println("Office="+office); System.out.println("Salary="+salary); System.out.println("Date Hired="+dateHired); } } class Faculty extends Employee { double hours; int rank; Faculty(final String n,String ad,long pn,String em,String of,double sal,String dh,double hr,int rk) { super(n,ad,pn,em,of,sal,dh); hours=hr; rank=rk; } public String toString() { return "**class Faculty**\n name="+name; } void show() { super.show(); System.out.println("Hours="+hours); System.out.println("Rank="+rank); } } class Staff extends Employee { String title; Staff(final String n,String ad,long pn,String em,String of,double sal,String dh,String t) { super(n,ad,pn,em,of,sal,dh); title=t; } public String toString() { return "**class Staff**\n name="+name; } void show() { super.show(); System.out.println("Title="+title); } } class MyDate { int year; int month; int day; MyDate(int y,int m,int d) { year=y; month=m; day=d; } public String toString() { return "**class MyDate**\n Year="+year+" Month="+month+" Day="+day; } } class PersonDemo { public static void main(String args[]) { Person p=new Person("Mel","mawlai",1234567890,"are@hm.com"); System.out.println(p.toString()); p.show(); System.out.println(); Student s=new Student("Almo","mawlai",1234567890,"are@hm.com","sophomore"); System.out.println(s.toString()); s.show(); System.out.println(); Employee e=new Employee("Sheak","mawlai",1234567890,"are@hm.com","office1",5000.0,"10-04-2107"); System.out.println(e.toString()); e.show(); System.out.println(); Faculty f=new Faculty("Evan","mawlai",1234567890,"aewre@hm.com","office1",6000.0,"10-04-2107",8.2,8); System.out.println(f.toString()); f.show(); System.out.println(); Staff st=new Staff("Lucy","mawlai",1234567890,"are@hm.com","office1",5000.0,"10-04-2107","clerk"); System.out.println(st.toString()); st.show(); System.out.println(); System.out.println(md.toString()); } }
// ================================================================================================= // // Hammerc Framework // Copyright 2013 hammerc.org All Rights Reserved. // // See LICENSE for full license information. // // ================================================================================================= package org.hammerc.utils; import java.math.BigInteger; /** * Java 本身不支持无符号整型, 本工具类提供无符号整型和字节之间相互转换的功能方便与其它语音通讯. * <p>注: 字节顺序使用 Java 默认的 Big-endian.<p> * @author wizardc */ public class UnsignedUtil { /** * 读取无符号字节. * @param b 对应的字节. * @return 无符号整型. */ public static short readUnsignedByte(byte b) { return (short) (b & 0xff); } /** * 读取无符号短整型. * @param bytes 对应的字节. * @return 无符号整型. */ public static int readUnsignedShort(byte[] bytes) { return ((bytes[0] << 8) & 0xff00) + (bytes[1] & 0xff); } /** * 读取无符号整型. * @param bytes 对应的字节. * @return 无符号整型. */ public static long readUnsignedInt(byte[] bytes) { return ((long) ((bytes[0] << 24 & 0xff000000) + (bytes[1] << 16 & 0xff0000) + (bytes[2] << 8 & 0xff00) + (bytes[3] & 0xff))) & 0xffffffffL; } /** * 读取无符号长整型. * @param bytes 对应的字节. * @return 无符号整型. */ public static BigInteger readUnsignedLong(byte[] bytes) { return new BigInteger(1, bytes); } /** * 转换无符号整型为字节. * @param value 无符号字节. * @return 对应的字节. */ public static byte writeUnsignedByte(short value) { return (byte) value; } /** * 转换无符号整型为字节. * @param value 无符号短整型. * @return 对应的字节. */ public static byte[] writeUnsignedShort(int value) { byte[] bytes = new byte[2]; bytes[1] = (byte) (value & 0xff); bytes[0] = (byte) (value >> 8 & 0xff); return bytes; } /** * 转换无符号整型为字节. * @param value 无符号整型. * @return 对应的字节. */ public static byte[] writeUnsignedInt(long value) { byte[] bytes = new byte[4]; bytes[3] = (byte) (value & 0xff); bytes[2] = (byte) (value >> 8 & 0xff); bytes[1] = (byte) (value >> 16 & 0xff); bytes[0] = (byte) (value >> 24 & 0xff); return bytes; } /** * 转换无符号整型为字节. * @param value 无符号长整型. * @return 对应的字节. */ public static byte[] writeUnsignedLong(BigInteger value) { byte[] bytes = new byte[8]; BigInteger bigInt = new BigInteger("255"); for(int i = 0; i < 8; i++) { bytes[i] = (value.shiftRight((7 - i) * 8).and(bigInt).byteValue()); } return bytes; } }
import java.awt.*; class DataChangeEvent extends Event { public DataChangeEvent(Object target, int id, Object arg) { super(target, id, arg); } }
package theGame; import org.junit.Assert; import org.junit.Test; import thegame.newHope.model.Building; import thegame.newHope.model.Game; import thegame.newHope.model.ResourceType; import thegame.newHope.model.Resources; public class GameTest { Game game; @Test public void canBuyBuildingTest() throws Exception { game = Game.getInstance(); Resources minResources = new Resources(0,0,0, 1,1,1); Resources maxResources = new Resources(1000,1000,1000, 1,1,1); game.resetGame(); game.setResources(minResources); Building toBuyWood = new Building("Sawmill", "Something", 5, 20,30,40,ResourceType.Wood); Assert.assertEquals(game.canBuyBuilding(toBuyWood) , false); game.setResources(maxResources); Assert.assertEquals(game.canBuyBuilding(toBuyWood) , true); game.setResources(minResources); Building toBuyStone = new Building("Stone Quarry", "Something", 5, 20,30,40,ResourceType.Stone); Assert.assertEquals(game.canBuyBuilding(toBuyStone), false); game.setResources(maxResources); Assert.assertEquals(game.canBuyBuilding(toBuyStone), true); game.setResources(minResources); Building toBuyIron = new Building("Iron Mine", "Something", 5, 20,30,40,ResourceType.Iron); Assert.assertEquals(game.canBuyBuilding(toBuyIron) , false); game.setResources(maxResources); Assert.assertEquals(game.canBuyBuilding(toBuyIron) , true); } @Test public void incrementDayTest() { game = game.getInstance(); game.resetGame(); int day = game.getDayCounter(); game.incrementDay(); Assert.assertEquals(game.getDayCounter(),day + 1); } @Test public void resetGameTest() { game = game.getInstance(); game.resetGame(); Assert.assertEquals(10, game.getResources().getWood()); Assert.assertEquals(5, game.getResources().getStone()); Assert.assertEquals(0, game.getResources().getIron()); Assert.assertEquals(10, game.getResources().getIncrementWood()); Assert.assertEquals(5, game.getResources().getIncrementStone()); Assert.assertEquals(2, game.getResources().getIncrementIron()); Assert.assertEquals(1, game.getDayCounter()); } @Test public void subTest() { game = game.getInstance(); game.resetGame(); int wood = game.getResources().getWood(); int stone = game.getResources().getStone(); int iron = game.getResources().getIron(); game.subWood(10); game.subStone(10); game.subIron(10); Assert.assertEquals(game.getResources().getWood(), wood -= 10); Assert.assertEquals(game.getResources().getStone(), stone -= 10); Assert.assertEquals(game.getResources().getIron(), iron -= 10); } @Test public void applyBuildingEffectTest() { game = game.getInstance(); game.resetGame(); int woodIncrement = game.getResources().getIncrementWood(); int stoneIncrement = game.getResources().getIncrementStone(); int ironIncrement = game.getResources().getIncrementIron(); game.applyBuildingEffect(ResourceType.Wood, 10); game.applyBuildingEffect(ResourceType.Stone, 10); game.applyBuildingEffect(ResourceType.Iron, 10); Assert.assertEquals(woodIncrement += 10, game.getResources().getIncrementWood()); Assert.assertEquals(stoneIncrement += 10, game.getResources().getIncrementStone()); Assert.assertEquals(ironIncrement += 10, game.getResources().getIncrementIron()); } @Test public void buyBuildingTest() { game = game.getInstance(); game.resetGame(); int wood = 1000; int stone = 1000; int iron = 1000; game.resetGame(); Resources maxResources = new Resources(wood,stone,iron, 1,1,1); game.setResources(maxResources); Building toBuyWood = new Building("Sawmill", "Something", 5, 20,30,40,ResourceType.Wood); Building toBuyStone = new Building("Stone Quarry", "Something", 5, 20,30,40,ResourceType.Stone); Building toBuyIron = new Building("Iron Mine", "Something", 5, 20,30,40,ResourceType.Iron); int woodCost = toBuyWood.getWoodCost(); int stoneCost = toBuyWood.getStoneCost(); int ironCost = toBuyWood.getIronCost(); int woodIncrement = toBuyWood.getIncrement(); int stoneIncrement = toBuyStone.getIncrement(); int ironIncrement = toBuyIron.getIncrement(); game.buyBuilding(toBuyWood); Assert.assertEquals(wood - woodCost, game.getResources().getWood()); Assert.assertEquals(stone - stoneCost, game.getResources().getStone()); Assert.assertEquals(iron - ironCost, game.getResources().getIron()); Assert.assertEquals(1 + woodIncrement, game.getResources().getIncrementWood()); game.resetGame(); game.setResources(maxResources); game.buyBuilding(toBuyStone); Assert.assertEquals(1 + stoneIncrement, game.getResources().getIncrementStone()); game.resetGame(); game.setResources(maxResources); game.buyBuilding(toBuyIron); Assert.assertEquals(1 + ironIncrement, game.getResources().getIncrementIron()); } }
package com.revolsys.ui.html.fields; import com.revolsys.record.io.format.xml.XmlWriter; import com.revolsys.util.HtmlAttr; import com.revolsys.util.HtmlElem; public class WeekField extends TextField { public WeekField(final String name, final boolean required) { super(name, required); } @Override public void serializeElement(final XmlWriter out) { final String id = getName(); out.startTag(HtmlElem.DIV); out.attribute(HtmlAttr.ID, id); out.text(" "); out.endTag(HtmlElem.DIV); out.startTag(HtmlElem.SCRIPT); out.attribute(HtmlAttr.TYPE, "text/javascript"); out.text("new WeekField('"); out.text(id); out.text("');"); out.endTag(HtmlElem.SCRIPT); } }
package com.github.appreciated.apexcharts.config.fill; public class Pattern { private String style; private Double width; private Double height; private Double strokeWidth; public Pattern() { } public String getStyle() { return style; } public Double getWidth() { return width; } public Double getHeight() { return height; } public Double getStrokeWidth() { return strokeWidth; } public void setStyle(String style) { this.style = style; } public void setWidth(Double width) { this.width = width; } public void setHeight(Double height) { this.height = height; } public void setStrokeWidth(Double strokeWidth) { this.strokeWidth = strokeWidth; } }
/* * Copyright 2002-2018 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 * * 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. */ package org.springframework.aop.target; import java.io.Serializable; import org.springframework.aop.TargetSource; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; /** * Implementation of the {@link TargetSource} interface * that holds a given object. This is the default implementation of the TargetSource * interface, as used by the Spring AOP framework. There is usually no need to * create objects of this class in application code. * * <p>This class is serializable. However, the actual serializability of a * SingletonTargetSource will depend on whether the target is serializable. * * @author Rod Johnson * @author Juergen Hoeller * @see org.springframework.aop.framework.AdvisedSupport#setTarget(Object) */ public class SingletonTargetSource implements TargetSource, Serializable { /** use serialVersionUID from Spring 1.2 for interoperability. */ private static final long serialVersionUID = 9031246629662423738L; /** Target cached and invoked using reflection. */ private final Object target; /** * Create a new SingletonTargetSource for the given target. * @param target the target object */ public SingletonTargetSource(Object target) { Assert.notNull(target, "Target object must not be null"); this.target = target; } @Override public Class<?> getTargetClass() { return this.target.getClass(); } @Override public Object getTarget() { return this.target; } @Override public void releaseTarget(Object target) { // nothing to do } @Override public boolean isStatic() { return true; } /** * Two invoker interceptors are equal if they have the same target or if the * targets or the targets are equal. */ @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof SingletonTargetSource)) { return false; } SingletonTargetSource otherTargetSource = (SingletonTargetSource) other; return this.target.equals(otherTargetSource.target); } /** * SingletonTargetSource uses the hash code of the target object. */ @Override public int hashCode() { return this.target.hashCode(); } @Override public String toString() { return "SingletonTargetSource for target object [" + ObjectUtils.identityToString(this.target) + "]"; } }
/* * 取り込み元 * ライブラリ名: seasar2 * クラス名: org.seasar.framework.beans.util.Copy * ソースリポジトリ: https://github.com/seasarorg/seasar2/blob/master/s2-tiger/src/main/java/org/seasar/framework/beans/util/Copy.java * * 上記ファイルを取り込み、修正を加えた。 * * Copyright 2020 TIS Inc. * * Copyright 2004-2013 the Seasar Foundation and the Others. * * 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 oscana.s2n.seasar.framework.beans.util; import java.util.Map; /** * プロパティをコピーするクラス。 * * @author higa * */ public class Copy extends AbstractCopy<Copy> { /** * コピー元 */ protected Object src; /** * コピー先 */ protected Object dest; /** * インスタンスを構築する。 * * @param src * コピー元 * @param dest * コピー先 * @throws NullPointerException * 引数が<code>null</code>だった場合 */ public Copy(Object src, Object dest) throws NullPointerException { if (src == null) { throw new NullPointerException("src"); } if (dest == null) { throw new NullPointerException("dest"); } this.src = src; this.dest = dest; } /** * プロパティをコピーする。 */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void execute() { if (src instanceof Map && dest instanceof Map) { copyMapToMap((Map) src, (Map) dest); } else if (src instanceof Map) { copyMapToBean((Map) src, dest); } else if (dest instanceof Map) { copyBeanToMap(src, (Map) dest); } else { copyBeanToBean(src, dest); } } }
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.v4; public final class R { public static final class attr { public static final int font = 0x7f04009b; public static final int fontProviderAuthority = 0x7f04009d; public static final int fontProviderCerts = 0x7f04009e; public static final int fontProviderFetchStrategy = 0x7f04009f; public static final int fontProviderFetchTimeout = 0x7f0400a0; public static final int fontProviderPackage = 0x7f0400a1; public static final int fontProviderQuery = 0x7f0400a2; public static final int fontStyle = 0x7f0400a3; public static final int fontWeight = 0x7f0400a4; } public static final class bool { public static final int abc_action_bar_embed_tabs = 0x7f050000; } public static final class color { public static final int notification_action_color_filter = 0x7f06004a; public static final int notification_icon_bg_color = 0x7f06004b; public static final int notification_material_background_media_default_color = 0x7f06004c; public static final int primary_text_default_material_dark = 0x7f060051; public static final int ripple_material_light = 0x7f060056; public static final int secondary_text_default_material_dark = 0x7f060057; public static final int secondary_text_default_material_light = 0x7f060058; } public static final class dimen { public static final int compat_button_inset_horizontal_material = 0x7f070050; public static final int compat_button_inset_vertical_material = 0x7f070051; public static final int compat_button_padding_horizontal_material = 0x7f070052; public static final int compat_button_padding_vertical_material = 0x7f070053; public static final int compat_control_corner_material = 0x7f070054; public static final int notification_action_icon_size = 0x7f07008b; public static final int notification_action_text_size = 0x7f07008c; public static final int notification_big_circle_margin = 0x7f07008d; public static final int notification_content_margin_start = 0x7f07008e; public static final int notification_large_icon_height = 0x7f07008f; public static final int notification_large_icon_width = 0x7f070090; public static final int notification_main_column_padding_top = 0x7f070091; public static final int notification_media_narrow_margin = 0x7f070092; public static final int notification_right_icon_size = 0x7f070093; public static final int notification_right_side_padding_top = 0x7f070094; public static final int notification_small_icon_background_padding = 0x7f070095; public static final int notification_small_icon_size_as_large = 0x7f070096; public static final int notification_subtext_size = 0x7f070097; public static final int notification_top_pad = 0x7f070098; public static final int notification_top_pad_large_text = 0x7f070099; } public static final class drawable { public static final int notification_action_background = 0x7f08006e; public static final int notification_bg = 0x7f08006f; public static final int notification_bg_low = 0x7f080070; public static final int notification_bg_low_normal = 0x7f080071; public static final int notification_bg_low_pressed = 0x7f080072; public static final int notification_bg_normal = 0x7f080073; public static final int notification_bg_normal_pressed = 0x7f080074; public static final int notification_icon_background = 0x7f080075; public static final int notification_template_icon_bg = 0x7f080076; public static final int notification_template_icon_low_bg = 0x7f080077; public static final int notification_tile_bg = 0x7f080078; public static final int notify_panel_notification_icon_bg = 0x7f080079; } public static final class id { public static final int action0 = 0x7f090006; public static final int action_container = 0x7f09000e; public static final int action_divider = 0x7f090010; public static final int action_image = 0x7f090011; public static final int action_text = 0x7f090017; public static final int actions = 0x7f090018; public static final int async = 0x7f09001e; public static final int blocking = 0x7f090023; public static final int cancel_action = 0x7f09002a; public static final int chronometer = 0x7f090033; public static final int end_padder = 0x7f090053; public static final int forever = 0x7f090060; public static final int icon = 0x7f090064; public static final int icon_group = 0x7f090065; public static final int info = 0x7f090069; public static final int italic = 0x7f09006b; public static final int line1 = 0x7f09006f; public static final int line3 = 0x7f090070; public static final int media_actions = 0x7f090078; public static final int normal = 0x7f090083; public static final int notification_background = 0x7f090084; public static final int notification_main_column = 0x7f090085; public static final int notification_main_column_container = 0x7f090086; public static final int right_icon = 0x7f090095; public static final int right_side = 0x7f090096; public static final int status_bar_latest_event_content = 0x7f0900cc; public static final int text = 0x7f0900d2; public static final int text2 = 0x7f0900d3; public static final int time = 0x7f0900d9; public static final int title = 0x7f0900da; } public static final class integer { public static final int cancel_button_image_alpha = 0x7f0a0004; public static final int status_bar_notification_info_maxnum = 0x7f0a0009; } public static final class layout { public static final int notification_action = 0x7f0b0036; public static final int notification_action_tombstone = 0x7f0b0037; public static final int notification_media_action = 0x7f0b0038; public static final int notification_media_cancel_action = 0x7f0b0039; public static final int notification_template_big_media = 0x7f0b003a; public static final int notification_template_big_media_custom = 0x7f0b003b; public static final int notification_template_big_media_narrow = 0x7f0b003c; public static final int notification_template_big_media_narrow_custom = 0x7f0b003d; public static final int notification_template_custom_big = 0x7f0b003e; public static final int notification_template_icon_group = 0x7f0b003f; public static final int notification_template_lines_media = 0x7f0b0040; public static final int notification_template_media = 0x7f0b0041; public static final int notification_template_media_custom = 0x7f0b0042; public static final int notification_template_part_chronometer = 0x7f0b0043; public static final int notification_template_part_time = 0x7f0b0044; } public static final class string { public static final int status_bar_notification_info_overflow = 0x7f0e0054; } public static final class style { public static final int TextAppearance_Compat_Notification = 0x7f0f0107; public static final int TextAppearance_Compat_Notification_Info = 0x7f0f0108; public static final int TextAppearance_Compat_Notification_Info_Media = 0x7f0f0109; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0f010a; public static final int TextAppearance_Compat_Notification_Line2_Media = 0x7f0f010b; public static final int TextAppearance_Compat_Notification_Media = 0x7f0f010c; public static final int TextAppearance_Compat_Notification_Time = 0x7f0f010d; public static final int TextAppearance_Compat_Notification_Time_Media = 0x7f0f010e; public static final int TextAppearance_Compat_Notification_Title = 0x7f0f010f; public static final int TextAppearance_Compat_Notification_Title_Media = 0x7f0f0110; public static final int Widget_Compat_NotificationActionContainer = 0x7f0f0185; public static final int Widget_Compat_NotificationActionText = 0x7f0f0186; } public static final class styleable { public static final int[] FontFamily = { 0x7f04009d, 0x7f04009e, 0x7f04009f, 0x7f0400a0, 0x7f0400a1, 0x7f0400a2 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x7f04009b, 0x7f0400a3, 0x7f0400a4 }; public static final int FontFamilyFont_font = 0; public static final int FontFamilyFont_fontStyle = 1; public static final int FontFamilyFont_fontWeight = 2; } }
package cn.jeeweb.ui.tags.form; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import cn.jeeweb.beetl.tags.annotation.BeetlTagName; import cn.jeeweb.beetl.tags.exception.BeetlTagException; import cn.jeeweb.beetl.tags.form.HiddenInputTag; import cn.jeeweb.beetl.tags.form.TagWriter; import cn.jeeweb.common.utils.SpringContextHolder; import cn.jeeweb.common.utils.StringUtils; import cn.jeeweb.common.utils.mapper.JsonMapper; import cn.jeeweb.ui.tags.form.support.FreemarkerFormTagHelper; import cn.jeeweb.ui.tags.html.manager.HtmlComponentManager; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; /** * * All rights Reserved, Designed By www.jeeweb.cn * * @title: TreeSelect.java * @package cn.jeeweb.tags.form * @description: 树形选择 * @author: 王存见 * @date: 2017年4月10日 下午9:16:24 * @version V1.0 * @copyright: 2017 www.jeeweb.cn Inc. All rights reserved. * */ @Component @Scope("prototype") @BeetlTagName("form.combox") public class ComboxTag extends HiddenInputTag { private String labelName = "";// 显示域的ID private String labelValue = "";// 显示域的值 private String idField = "id";/// 每组数据的哪个字段作为 data-id private String keyField = "name";// 每组数据的哪个字段作为输入框内容 private Boolean multiWord = Boolean.FALSE;// 以分隔符号分割的多关键字支持 private String separator = ",";// 多关键字支持时的分隔符,默认为空格 private String getDataMethod = "";// 获取数据的方式,url:一直从url请求;data:从 // options.data // 获取;firstByUrl:第一次从Url获取全部数据,之后从options.data获取 private String effectiveFields = "";// 下拉要显示的列 private String effectiveFieldsAlias = ""; // 有效字段的别名对象,用于 header 的显示 private Boolean showHeader; // 是否显示头部 private String dataUrl = "";// 获取数据的URL private String keyword="keyword";//搜索的关键字 private Object datas;// 数据 private String jsonp = ""; // private String processData = "";// 处理数据回调 private String dataRequestSuccess = "";// 数据请求成功 private String setSelectValue = "";// 设置选择数据回调 private String unsetSelectValue = "";// 取消选择回调 private String comboxSetting = ""; //扩展设置 public String getIdField() { return idField; } public void setIdField(String idField) { this.idField = idField; } public String getKeyField() { return keyField; } public void setKeyField(String keyField) { this.keyField = keyField; } public Boolean getMultiWord() { return multiWord; } public void setMultiWord(Boolean multiWord) { this.multiWord = multiWord; } public String getSeparator() { return separator; } public void setSeparator(String separator) { this.separator = separator; } public String getGetDataMethod() { return getDataMethod; } public void setGetDataMethod(String getDataMethod) { this.getDataMethod = getDataMethod; } public String getEffectiveFieldsAlias() { return effectiveFieldsAlias; } public void setEffectiveFieldsAlias(String effectiveFieldsAlias) { this.effectiveFieldsAlias = effectiveFieldsAlias; } public Boolean getShowHeader() { return showHeader; } public void setShowHeader(Boolean showHeader) { this.showHeader = showHeader; } public String getDataUrl() { return dataUrl; } public void setDataUrl(String dataUrl) { this.dataUrl = dataUrl; } public Object getDatas() { return datas; } public void setDatas(Object datas) { this.datas = datas; } public String getJsonp() { return jsonp; } public void setJsonp(String jsonp) { this.jsonp = jsonp; } public String getProcessData() { return processData; } public void setProcessData(String processData) { this.processData = processData; } public String getDataRequestSuccess() { return dataRequestSuccess; } public void setDataRequestSuccess(String dataRequestSuccess) { this.dataRequestSuccess = dataRequestSuccess; } public String getSetSelectValue() { return setSelectValue; } public void setSetSelectValue(String setSelectValue) { this.setSelectValue = setSelectValue; } public String getUnsetSelectValue() { return unsetSelectValue; } public void setUnsetSelectValue(String unsetSelectValue) { this.unsetSelectValue = unsetSelectValue; } public String getLabelName() { return labelName; } public void setLabelName(String labelName) { this.labelName = labelName; } public String getLabelValue() { return labelValue; } public void setLabelValue(String labelValue) { this.labelValue = labelValue; } public String getEffectiveFields() { return effectiveFields; } public void setEffectiveFields(String effectiveFields) { this.effectiveFields = effectiveFields; } public String getKeyword() { return keyword; } public void setKeyword(String keyword) { this.keyword = keyword; } public String getComboxSetting() { return comboxSetting; } public void setComboxSetting(String comboxSetting) { this.comboxSetting = comboxSetting; } @Override protected int writeTagContent(TagWriter tagWriter) throws BeetlTagException { tagWriter.startTag("input"); writeDefaultAttributes(tagWriter); tagWriter.writeAttribute("type", "hidden"); if (isDisabled()) { tagWriter.writeAttribute(DISABLED_ATTRIBUTE, "disabled"); } String value = getDisplayString(getBoundValue(), getPropertyEditor()); tagWriter.writeAttribute("value", processFieldValue(getName(), value, "hidden")); tagWriter.endTag(); // 输出编辑器代码片段 writeFragment(tagWriter); return SKIP_BODY; } private void writeFragment(TagWriter tagWriter) throws BeetlTagException { if (!StringUtils.isEmpty(effectiveFields)) { // 下拉要显示的列加入引号 String[] effectiveFieldsArr = effectiveFields.split(","); List<String> effectiveFieldList = new ArrayList<String>(); for (String effectiveField : effectiveFieldsArr) { effectiveFieldList.add(effectiveField.trim()); } this.effectiveFields = JsonMapper.toJsonString(effectiveFieldList); } if (!StringUtils.isEmpty(effectiveFieldsAlias)) { Map<String, String> effectiveFieldsAliasMap = new HashMap<String, String>(); String[] effectiveFieldsAliasArr = effectiveFieldsAlias.split(","); for (String effectiveFieldsAliasItem : effectiveFieldsAliasArr) { effectiveFieldsAliasItem = effectiveFieldsAliasItem.trim(); String[] effectiveFieldsAliasItemArr = effectiveFieldsAliasItem.split("\\|"); if (effectiveFieldsAliasItemArr.length == 2) { effectiveFieldsAliasMap.put(effectiveFieldsAliasItemArr[0], effectiveFieldsAliasItemArr[1]); } } if (effectiveFieldsAliasMap.size() > 0) { if (this.showHeader == null) { this.showHeader = Boolean.TRUE; } } this.effectiveFieldsAlias = JsonMapper.toJsonString(effectiveFieldsAliasMap); } Map<String, Object> rootMap = FreemarkerFormTagHelper.getTagStatic(this, this.ctx); rootMap.put("name", getPath()); String value = getDisplayString(getBoundValue(), getPropertyEditor()); rootMap.put("value", processFieldValue(getName(), value, "hidden")); String initDatas = "[]"; if (datas != null) { initDatas = JsonMapper.toJsonString(datas); if (StringUtils.isEmpty(getDataMethod)) { rootMap.put("getDataMethod", "data"); } } if (!StringUtils.isEmpty(dataUrl)) { if (this.dataUrl.contains("?")) { this.dataUrl=this.dataUrl+"&"+keyword+"="; }else{ this.dataUrl=this.dataUrl+"?"+keyword+"="; } if (StringUtils.isEmpty(getDataMethod)) { rootMap.put("getDataMethod", "url"); } rootMap.put("dataUrl", dataUrl); } rootMap.put("labelName", getPath() + "Label"); rootMap.put("labelValue", processFieldValue(getName(), value, "hidden")); rootMap.put("initDatas", initDatas); HtmlComponentManager htmlComponentManager = SpringContextHolder.getApplicationContext() .getBean(HtmlComponentManager.class); String fragment = htmlComponentManager.getFragmentComponent("suggest-combox", rootMap); if (!StringUtils.isEmpty(fragment) && !fragment.equals("null")) { // 获得编辑器 tagWriter.forceAppendValue(fragment); } } }
package org.apdoer.condition.monitor.listener.manager; import lombok.extern.slf4j.Slf4j; import org.apdoer.common.service.util.SpringBeanUtils; import org.apdoer.condition.monitor.handler.QuotHandler; import org.apdoer.condition.monitor.listener.impl.QuotPriceSourceEventListener; import org.apdoer.condition.common.event.listener.SourceEventListener; import org.apdoer.condition.common.event.listener.SourceEventListenerManager; import org.apdoer.condition.common.utils.HandlerNameUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author apdoer * @version 1.0 * @date 2020/6/12 16:11 */ @Component @Slf4j public class QuotSourceEventListenerManager implements SourceEventListenerManager { private static final String DEFAULT_POSTFIX = "ConditionOrderMonitorHandler"; private Map<String, SourceEventListener> listenerMap = new ConcurrentHashMap<>(); @Autowired private SpringBeanUtils springBeanUtils; @Override public SourceEventListener getListener(String listenerName) { return listenerMap.get(listenerName); } @Override public SourceEventListener buildListener(String listenerName, String handlerName) { if (exists(listenerName)) { return this.getListener(listenerName); } else { SourceEventListener listener = build(listenerName, handlerName); listenerMap.put(listenerName, listener); log.info("build quot listener success name:{}", listenerName); return listener; } } private SourceEventListener build(String listenerName, String handlerName) { QuotPriceSourceEventListener listener = springBeanUtils.getBean("quotPriceSourceEventListener", QuotPriceSourceEventListener.class); String realHandlerName = HandlerNameUtils.buildHandleName(handlerName.toLowerCase(), DEFAULT_POSTFIX); QuotHandler handler = this.springBeanUtils.getBean(realHandlerName, QuotHandler.class); listener.setQuotHandler(handler); return listener; } @Override public boolean exists(String listenerName) { return listenerMap.containsKey(listenerName); } }
package com.shitij.medium.topics; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "topicId", "slug", "createdAt", "deletedAt", "image", "name", "description", "isFollowing", "briefCatalogId", "relatedTopics", "visibility", "relatedTags", "type" }) public class Aef1078a3ef5 { @JsonProperty("topicId") private String topicId; @JsonProperty("slug") private String slug; @JsonProperty("createdAt") private long createdAt; @JsonProperty("deletedAt") private long deletedAt; @JsonProperty("image") private Image____________________________________ image; @JsonProperty("name") private String name; @JsonProperty("description") private String description; @JsonProperty("isFollowing") private boolean isFollowing; @JsonProperty("briefCatalogId") private String briefCatalogId; @JsonProperty("relatedTopics") private List<Object> relatedTopics = null; @JsonProperty("visibility") private long visibility; @JsonProperty("relatedTags") private List<Object> relatedTags = null; @JsonProperty("type") private String type; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("topicId") public String getTopicId() { return topicId; } @JsonProperty("topicId") public void setTopicId(String topicId) { this.topicId = topicId; } @JsonProperty("slug") public String getSlug() { return slug; } @JsonProperty("slug") public void setSlug(String slug) { this.slug = slug; } @JsonProperty("createdAt") public long getCreatedAt() { return createdAt; } @JsonProperty("createdAt") public void setCreatedAt(long createdAt) { this.createdAt = createdAt; } @JsonProperty("deletedAt") public long getDeletedAt() { return deletedAt; } @JsonProperty("deletedAt") public void setDeletedAt(long deletedAt) { this.deletedAt = deletedAt; } @JsonProperty("image") public Image____________________________________ getImage() { return image; } @JsonProperty("image") public void setImage(Image____________________________________ image) { this.image = image; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String name) { this.name = name; } @JsonProperty("description") public String getDescription() { return description; } @JsonProperty("description") public void setDescription(String description) { this.description = description; } @JsonProperty("isFollowing") public boolean isIsFollowing() { return isFollowing; } @JsonProperty("isFollowing") public void setIsFollowing(boolean isFollowing) { this.isFollowing = isFollowing; } @JsonProperty("briefCatalogId") public String getBriefCatalogId() { return briefCatalogId; } @JsonProperty("briefCatalogId") public void setBriefCatalogId(String briefCatalogId) { this.briefCatalogId = briefCatalogId; } @JsonProperty("relatedTopics") public List<Object> getRelatedTopics() { return relatedTopics; } @JsonProperty("relatedTopics") public void setRelatedTopics(List<Object> relatedTopics) { this.relatedTopics = relatedTopics; } @JsonProperty("visibility") public long getVisibility() { return visibility; } @JsonProperty("visibility") public void setVisibility(long visibility) { this.visibility = visibility; } @JsonProperty("relatedTags") public List<Object> getRelatedTags() { return relatedTags; } @JsonProperty("relatedTags") public void setRelatedTags(List<Object> relatedTags) { this.relatedTags = relatedTags; } @JsonProperty("type") public String getType() { return type; } @JsonProperty("type") public void setType(String type) { this.type = type; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() { return new ToStringBuilder(this).append("topicId", topicId).append("slug", slug).append("createdAt", createdAt).append("deletedAt", deletedAt).append("image", image).append("name", name).append("description", description).append("isFollowing", isFollowing).append("briefCatalogId", briefCatalogId).append("relatedTopics", relatedTopics).append("visibility", visibility).append("relatedTags", relatedTags).append("type", type).append("additionalProperties", additionalProperties).toString(); } @Override public int hashCode() { return new HashCodeBuilder().append(visibility).append(relatedTags).append(image).append(briefCatalogId).append(type).append(relatedTopics).append(additionalProperties).append(description).append(createdAt).append(name).append(deletedAt).append(topicId).append(slug).append(isFollowing).toHashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof Aef1078a3ef5) == false) { return false; } Aef1078a3ef5 rhs = ((Aef1078a3ef5) other); return new EqualsBuilder().append(visibility, rhs.visibility).append(relatedTags, rhs.relatedTags).append(image, rhs.image).append(briefCatalogId, rhs.briefCatalogId).append(type, rhs.type).append(relatedTopics, rhs.relatedTopics).append(additionalProperties, rhs.additionalProperties).append(description, rhs.description).append(createdAt, rhs.createdAt).append(name, rhs.name).append(deletedAt, rhs.deletedAt).append(topicId, rhs.topicId).append(slug, rhs.slug).append(isFollowing, rhs.isFollowing).isEquals(); } }
// Targeted by JavaCPP version 1.5.2-SNAPSHOT: DO NOT EDIT THIS FILE package org.bytedeco.tensorrt.nvinfer; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import org.bytedeco.cuda.cudart.*; import static org.bytedeco.cuda.global.cudart.*; import static org.bytedeco.tensorrt.global.nvinfer.*; /** * \class IActivationLayer * * \brief An Activation layer in a network definition. * * This layer applies a per-element activation function to its input. * * The output has the same shape as the input. * * \warning Do not inherit from this class, as doing so will break forward-compatibility of the API and ABI. * */ @Namespace("nvinfer1") @Properties(inherit = org.bytedeco.tensorrt.presets.nvinfer.class) public class IActivationLayer extends ILayer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public IActivationLayer(Pointer p) { super(p); } /** * \brief Set the type of activation to be performed. * * @see getActivationType(), ActivationType * */ //! //! //! public native void setActivationType(ActivationType type); public native void setActivationType(@Cast("nvinfer1::ActivationType") int type); /** * \brief Get the type of activation to be performed. * * @see setActivationType(), ActivationType * */ public native ActivationType getActivationType(); /** * \brief Set the alpha parameter (must be finite). * * This parameter is used by the following activations: * LeakyRelu, Elu, Selu, Softplus, Clip, HardSigmoid, ScaledTanh, * ThresholdedRelu. * * It is ignored by the other activations. * * @see getAlpha(), setBeta() */ //! //! //! //! public native void setAlpha(float alpha); /** * \brief Set the beta parameter (must be finite). * * This parameter is used by the following activations: * Selu, Softplus, Clip, HardSigmoid, ScaledTanh. * * It is ignored by the other activations. * * @see getBeta(), setAlpha() */ //! //! public native void setBeta(float beta); /** * \brief Get the alpha parameter. * * @see getBeta(), setAlpha() */ //! //! public native float getAlpha(); /** * \brief Get the beta parameter. * * @see getAlpha(), setBeta() */ public native float getBeta(); }
/* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. 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.wso2.carbon.apimgt.impl.token; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.user.core.util.UserCoreUtil; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.util.*; public class JWTGenerator extends AbstractJWTGenerator { private static final Log log = LogFactory.getLog(JWTGenerator.class); public Map<String, String> populateStandardClaims(APIKeyValidationInfoDTO keyValidationInfoDTO, String apiContext, String version) throws APIManagementException { //generating expiring timestamp long currentTime = Calendar.getInstance().getTimeInMillis(); long expireIn = currentTime + 1000 * 60 * getTTL(); String jwtBody = ""; String dialect; ClaimsRetriever claimsRetriever = getClaimsRetriever(); if (claimsRetriever != null) { //jwtBody = JWT_INITIAL_BODY.replaceAll("\\[0\\]", claimsRetriever.getDialectURI(endUserName)); dialect = claimsRetriever.getDialectURI(keyValidationInfoDTO.getEndUserName()); } else { //jwtBody = JWT_INITIAL_BODY.replaceAll("\\[0\\]", dialectURI); dialect = getDialectURI(); } String subscriber = keyValidationInfoDTO.getSubscriber(); String applicationName = keyValidationInfoDTO.getApplicationName(); String applicationId = keyValidationInfoDTO.getApplicationId(); String tier = keyValidationInfoDTO.getTier(); String endUserName = keyValidationInfoDTO.getEndUserName(); String keyType = keyValidationInfoDTO.getType(); String userType = keyValidationInfoDTO.getUserType(); String applicationTier = keyValidationInfoDTO.getApplicationTier(); String enduserTenantId = String.valueOf(APIUtil.getTenantId(endUserName)); Map<String, String> claims = new LinkedHashMap<String, String>(20); claims.put("iss", API_GATEWAY_ID); claims.put("exp", String.valueOf(expireIn)); claims.put(dialect + "/subscriber", subscriber); claims.put(dialect + "/applicationid", applicationId); claims.put(dialect + "/applicationname", applicationName); claims.put(dialect + "/applicationtier", applicationTier); claims.put(dialect + "/apicontext", apiContext); claims.put(dialect + "/version", version); claims.put(dialect + "/tier", tier); claims.put(dialect + "/keytype", keyType); claims.put(dialect + "/usertype", userType); claims.put(dialect + "/enduser", UserCoreUtil.removeDomainFromName(APIUtil.getUserNameWithTenantSuffix(endUserName))); claims.put(dialect + "/enduserTenantId", enduserTenantId); return claims; } public Map<String, String> populateCustomClaims(APIKeyValidationInfoDTO keyValidationInfoDTO, String apiContext, String version, String accessToken) throws APIManagementException { ClaimsRetriever claimsRetriever = getClaimsRetriever(); if (claimsRetriever != null) { String tenantAwareUserName = keyValidationInfoDTO.getEndUserName(); if (MultitenantConstants.SUPER_TENANT_ID == APIUtil.getTenantId(tenantAwareUserName)) { tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(tenantAwareUserName); } try { return claimsRetriever.getClaims(tenantAwareUserName); } catch (APIManagementException e) { log.error("Error while retrieving claims ", e); } } return null; } }
/* * 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.kafka.common.network; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.nio.channels.UnresolvedAddressException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.kafka.common.KafkaException; import org.apache.kafka.common.memory.MemoryPool; import org.apache.kafka.common.metrics.Measurable; import org.apache.kafka.common.metrics.MetricConfig; import org.apache.kafka.common.MetricName; import org.apache.kafka.common.errors.AuthenticationException; import org.apache.kafka.common.metrics.Metrics; import org.apache.kafka.common.metrics.Sensor; import org.apache.kafka.common.metrics.stats.Avg; import org.apache.kafka.common.metrics.stats.Meter; import org.apache.kafka.common.metrics.stats.SampledStat; import org.apache.kafka.common.metrics.stats.Count; import org.apache.kafka.common.metrics.stats.Max; import org.apache.kafka.common.utils.LogContext; import org.apache.kafka.common.utils.Time; import org.slf4j.Logger; /** * A nioSelector interface for doing non-blocking multi-connection network I/O. * <p> * This class works with {@link NetworkSend} and {@link NetworkReceive} to transmit size-delimited network requests and * responses. * <p> * A connection can be added to the nioSelector associated with an integer id by doing * * <pre> * nioSelector.connect(&quot;42&quot;, new InetSocketAddress(&quot;google.com&quot;, server.port), 64000, 64000); * </pre> * * The connect call does not block on the creation of the TCP connection, so the connect method only begins initiating * the connection. The successful invocation of this method does not mean a valid connection has been established. * * Sending requests, receiving responses, processing connection completions, and disconnections on the existing * connections are all done using the <code>poll()</code> call. * * <pre> * nioSelector.send(new NetworkSend(myDestination, myBytes)); * nioSelector.send(new NetworkSend(myOtherDestination, myOtherBytes)); * nioSelector.poll(TIMEOUT_MS); * </pre> * * The nioSelector maintains several lists that are reset by each call to <code>poll()</code> which are available via * various getters. These are reset by each call to <code>poll()</code>. * * This class is not thread safe! */ public class Selector implements Selectable, AutoCloseable { public static final long NO_IDLE_TIMEOUT_MS = -1; private final Logger log; private final java.nio.channels.Selector nioSelector; private final Map<String, KafkaChannel> channels; private final Set<KafkaChannel> explicitlyMutedChannels; private boolean outOfMemory; private final List<Send> completedSends; private final List<NetworkReceive> completedReceives; private final Map<KafkaChannel, Deque<NetworkReceive>> stagedReceives; private final Set<SelectionKey> immediatelyConnectedKeys; private final Map<String, KafkaChannel> closingChannels; private Set<SelectionKey> keysWithBufferedRead; private final Map<String, ChannelState> disconnected; private final List<String> connected; private final List<String> failedSends; private final Time time; private final SelectorMetrics sensors; private final ChannelBuilder channelBuilder; private final int maxReceiveSize; private final boolean recordTimePerConnection; private final IdleExpiryManager idleExpiryManager; private final MemoryPool memoryPool; private final long lowMemThreshold; //indicates if the previous call to poll was able to make progress in reading already-buffered data. //this is used to prevent tight loops when memory is not available to read any more data private boolean madeReadProgressLastPoll = true; /** * Create a new nioSelector * @param maxReceiveSize Max size in bytes of a single network receive (use {@link NetworkReceive#UNLIMITED} for no limit) * @param connectionMaxIdleMs Max idle connection time (use {@link #NO_IDLE_TIMEOUT_MS} to disable idle timeout) * @param metrics Registry for Selector metrics * @param time Time implementation * @param metricGrpPrefix Prefix for the group of metrics registered by Selector * @param metricTags Additional tags to add to metrics registered by Selector * @param metricsPerConnection Whether or not to enable per-connection metrics * @param channelBuilder Channel builder for every new connection * @param logContext Context for logging with additional info */ public Selector(int maxReceiveSize, long connectionMaxIdleMs, Metrics metrics, Time time, String metricGrpPrefix, Map<String, String> metricTags, boolean metricsPerConnection, boolean recordTimePerConnection, ChannelBuilder channelBuilder, MemoryPool memoryPool, LogContext logContext) { try { this.nioSelector = java.nio.channels.Selector.open(); } catch (IOException e) { throw new KafkaException(e); } this.maxReceiveSize = maxReceiveSize; this.time = time; this.channels = new HashMap<>(); this.explicitlyMutedChannels = new HashSet<>(); this.outOfMemory = false; this.completedSends = new ArrayList<>(); this.completedReceives = new ArrayList<>(); this.stagedReceives = new HashMap<>(); this.immediatelyConnectedKeys = new HashSet<>(); this.closingChannels = new HashMap<>(); this.keysWithBufferedRead = new HashSet<>(); this.connected = new ArrayList<>(); this.disconnected = new HashMap<>(); this.failedSends = new ArrayList<>(); this.sensors = new SelectorMetrics(metrics, metricGrpPrefix, metricTags, metricsPerConnection); this.channelBuilder = channelBuilder; this.recordTimePerConnection = recordTimePerConnection; this.idleExpiryManager = connectionMaxIdleMs < 0 ? null : new IdleExpiryManager(time, connectionMaxIdleMs); this.memoryPool = memoryPool; this.lowMemThreshold = (long) (0.1 * this.memoryPool.size()); this.log = logContext.logger(Selector.class); } public Selector(int maxReceiveSize, long connectionMaxIdleMs, Metrics metrics, Time time, String metricGrpPrefix, Map<String, String> metricTags, boolean metricsPerConnection, ChannelBuilder channelBuilder, LogContext logContext) { this(maxReceiveSize, connectionMaxIdleMs, metrics, time, metricGrpPrefix, metricTags, metricsPerConnection, false, channelBuilder, MemoryPool.NONE, logContext); } public Selector(long connectionMaxIdleMS, Metrics metrics, Time time, String metricGrpPrefix, ChannelBuilder channelBuilder, LogContext logContext) { this(NetworkReceive.UNLIMITED, connectionMaxIdleMS, metrics, time, metricGrpPrefix, Collections.<String, String>emptyMap(), true, channelBuilder, logContext); } /** * Begin connecting to the given address and add the connection to this nioSelector associated with the given id * number. * <p> * Note that this call only initiates the connection, which will be completed on a future {@link #poll(long)} * call. Check {@link #connected()} to see which (if any) connections have completed after a given poll call. * @param id The id for the new connection * @param address The address to connect to * @param sendBufferSize The send buffer for the new connection * @param receiveBufferSize The receive buffer for the new connection * @throws IllegalStateException if there is already a connection for that id * @throws IOException if DNS resolution fails on the hostname or if the broker is down */ @Override public void connect(String id, InetSocketAddress address, int sendBufferSize, int receiveBufferSize) throws IOException { if (this.channels.containsKey(id)) throw new IllegalStateException("There is already a connection for id " + id); if (this.closingChannels.containsKey(id)) throw new IllegalStateException("There is already a connection for id " + id + " that is still being closed"); SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); Socket socket = socketChannel.socket(); socket.setKeepAlive(true); if (sendBufferSize != Selectable.USE_DEFAULT_BUFFER_SIZE) socket.setSendBufferSize(sendBufferSize); if (receiveBufferSize != Selectable.USE_DEFAULT_BUFFER_SIZE) socket.setReceiveBufferSize(receiveBufferSize); socket.setTcpNoDelay(true); boolean connected; try { connected = socketChannel.connect(address); } catch (UnresolvedAddressException e) { socketChannel.close(); throw new IOException("Can't resolve address: " + address, e); } catch (IOException e) { socketChannel.close(); throw e; } SelectionKey key = socketChannel.register(nioSelector, SelectionKey.OP_CONNECT); KafkaChannel channel = buildChannel(socketChannel, id, key); if (connected) { // OP_CONNECT won't trigger for immediately connected channels log.debug("Immediately connected to node {}", channel.id()); immediatelyConnectedKeys.add(key); key.interestOps(0); } } /** * Register the nioSelector with an existing channel * Use this on server-side, when a connection is accepted by a different thread but processed by the Selector * <p> * If a connection already exists with the same connection id in `channels` or `closingChannels`, * an exception is thrown. Connection ids must be chosen to avoid conflict when remote ports are reused. * Kafka brokers add an incrementing index to the connection id to avoid reuse in the timing window * where an existing connection may not yet have been closed by the broker when a new connection with * the same remote host:port is processed. * </p><p> * If a `KafkaChannel` cannot be created for this connection, the `socketChannel` is closed * and its selection key cancelled. * </p> */ public void register(String id, SocketChannel socketChannel) throws IOException { if (this.channels.containsKey(id)) throw new IllegalStateException("There is already a connection for id " + id); if (this.closingChannels.containsKey(id)) throw new IllegalStateException("There is already a connection for id " + id + " that is still being closed"); SelectionKey key = socketChannel.register(nioSelector, SelectionKey.OP_READ); buildChannel(socketChannel, id, key); } private KafkaChannel buildChannel(SocketChannel socketChannel, String id, SelectionKey key) throws IOException { KafkaChannel channel; try { channel = channelBuilder.buildChannel(id, key, maxReceiveSize, memoryPool); } catch (Exception e) { try { socketChannel.close(); } finally { key.cancel(); } throw new IOException("Channel could not be created for socket " + socketChannel, e); } key.attach(channel); this.channels.put(id, channel); return channel; } /** * Interrupt the nioSelector if it is blocked waiting to do I/O. */ @Override public void wakeup() { this.nioSelector.wakeup(); } /** * Close this selector and all associated connections */ @Override public void close() { List<String> connections = new ArrayList<>(channels.keySet()); for (String id : connections) close(id); try { this.nioSelector.close(); } catch (IOException | SecurityException e) { log.error("Exception closing nioSelector:", e); } sensors.close(); channelBuilder.close(); } /** * Queue the given request for sending in the subsequent {@link #poll(long)} calls * @param send The request to send */ public void send(Send send) { String connectionId = send.destination(); KafkaChannel channel = openOrClosingChannelOrFail(connectionId); if (closingChannels.containsKey(connectionId)) { // ensure notification via `disconnected`, leave channel in the state in which closing was triggered this.failedSends.add(connectionId); } else { try { channel.setSend(send); } catch (Exception e) { // update the state for consistency, the channel will be discarded after `close` channel.state(ChannelState.FAILED_SEND); // ensure notification via `disconnected` this.failedSends.add(connectionId); close(channel, false); if (!(e instanceof CancelledKeyException)) { log.error("Unexpected exception during send, closing connection {} and rethrowing exception {}", connectionId, e); throw e; } } } } /** * Do whatever I/O can be done on each connection without blocking. This includes completing connections, completing * disconnections, initiating new sends, or making progress on in-progress sends or receives. * * When this call is completed the user can check for completed sends, receives, connections or disconnects using * {@link #completedSends()}, {@link #completedReceives()}, {@link #connected()}, {@link #disconnected()}. These * lists will be cleared at the beginning of each `poll` call and repopulated by the call if there is * any completed I/O. * * In the "Plaintext" setting, we are using socketChannel to read & write to the network. But for the "SSL" setting, * we encrypt the data before we use socketChannel to write data to the network, and decrypt before we return the responses. * This requires additional buffers to be maintained as we are reading from network, since the data on the wire is encrypted * we won't be able to read exact no.of bytes as kafka protocol requires. We read as many bytes as we can, up to SSLEngine's * application buffer size. This means we might be reading additional bytes than the requested size. * If there is no further data to read from socketChannel selector won't invoke that channel and we've have additional bytes * in the buffer. To overcome this issue we added "stagedReceives" map which contains per-channel deque. When we are * reading a channel we read as many responses as we can and store them into "stagedReceives" and pop one response during * the poll to add the completedReceives. If there are any active channels in the "stagedReceives" we set "timeout" to 0 * and pop response and add to the completedReceives. * * Atmost one entry is added to "completedReceives" for a channel in each poll. This is necessary to guarantee that * requests from a channel are processed on the broker in the order they are sent. Since outstanding requests added * by SocketServer to the request queue may be processed by different request handler threads, requests on each * channel must be processed one-at-a-time to guarantee ordering. * * @param timeout The amount of time to wait, in milliseconds, which must be non-negative * @throws IllegalArgumentException If `timeout` is negative * @throws IllegalStateException If a send is given for which we have no existing connection or for which there is * already an in-progress send */ @Override public void poll(long timeout) throws IOException { if (timeout < 0) throw new IllegalArgumentException("timeout should be >= 0"); boolean madeReadProgressLastCall = madeReadProgressLastPoll; clear(); boolean dataInBuffers = !keysWithBufferedRead.isEmpty(); if (hasStagedReceives() || !immediatelyConnectedKeys.isEmpty() || (madeReadProgressLastCall && dataInBuffers)) timeout = 0; if (!memoryPool.isOutOfMemory() && outOfMemory) { //we have recovered from memory pressure. unmute any channel not explicitly muted for other reasons log.trace("Broker no longer low on memory - unmuting incoming sockets"); for (KafkaChannel channel : channels.values()) { if (channel.isInMutableState() && !explicitlyMutedChannels.contains(channel)) { channel.unmute(); } } outOfMemory = false; } /* check ready keys */ long startSelect = time.nanoseconds(); int numReadyKeys = select(timeout); long endSelect = time.nanoseconds(); this.sensors.selectTime.record(endSelect - startSelect, time.milliseconds()); if (numReadyKeys > 0 || !immediatelyConnectedKeys.isEmpty() || dataInBuffers) { Set<SelectionKey> readyKeys = this.nioSelector.selectedKeys(); keysWithBufferedRead.removeAll(readyKeys); //so no channel gets polled twice //poll from channels that have buffered data (but nothing more from the underlying socket) if (!keysWithBufferedRead.isEmpty()) { Set<SelectionKey> toPoll = keysWithBufferedRead; keysWithBufferedRead = new HashSet<>(); //poll() calls will repopulate if needed pollSelectionKeys(toPoll, false, endSelect); } //poll from channels where the underlying socket has more data pollSelectionKeys(readyKeys, false, endSelect); pollSelectionKeys(immediatelyConnectedKeys, true, endSelect); // Clear all selected keys so that they are included in the ready count for the next select readyKeys.clear(); } else { madeReadProgressLastPoll = true; //no work is also "progress" } long endIo = time.nanoseconds(); this.sensors.ioTime.record(endIo - endSelect, time.milliseconds()); // we use the time at the end of select to ensure that we don't close any connections that // have just been processed in pollSelectionKeys maybeCloseOldestConnection(endSelect); // Add to completedReceives after closing expired connections to avoid removing // channels with completed receives until all staged receives are completed. addToCompletedReceives(); } /** * handle any ready I/O on a set of selection keys * @param selectionKeys set of keys to handle * @param isImmediatelyConnected true if running over a set of keys for just-connected sockets * @param currentTimeNanos time at which set of keys was determined */ // package-private for testing void pollSelectionKeys(Set<SelectionKey> selectionKeys, boolean isImmediatelyConnected, long currentTimeNanos) { Iterator<SelectionKey> iterator = determineHandlingOrder(selectionKeys).iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); KafkaChannel channel = channel(key); long channelStartTimeNanos = recordTimePerConnection ? time.nanoseconds() : 0; // register all per-connection metrics at once sensors.maybeRegisterConnectionMetrics(channel.id()); if (idleExpiryManager != null) idleExpiryManager.update(channel.id(), currentTimeNanos); try { /* complete any connections that have finished their handshake (either normally or immediately) */ if (isImmediatelyConnected || key.isConnectable()) { if (channel.finishConnect()) { this.connected.add(channel.id()); this.sensors.connectionCreated.record(); SocketChannel socketChannel = (SocketChannel) key.channel(); log.debug("Created socket with SO_RCVBUF = {}, SO_SNDBUF = {}, SO_TIMEOUT = {} to node {}", socketChannel.socket().getReceiveBufferSize(), socketChannel.socket().getSendBufferSize(), socketChannel.socket().getSoTimeout(), channel.id()); } else continue; } /* if channel is not ready finish prepare */ if (channel.isConnected() && !channel.ready()) { try { channel.prepare(); } catch (AuthenticationException e) { sensors.failedAuthentication.record(); throw e; } if (channel.ready()) sensors.successfulAuthentication.record(); } attemptRead(key, channel); if (channel.hasBytesBuffered()) { //this channel has bytes enqueued in intermediary buffers that we could not read //(possibly because no memory). it may be the case that the underlying socket will //not come up in the next poll() and so we need to remember this channel for the //next poll call otherwise data may be stuck in said buffers forever. keysWithBufferedRead.add(key); } /* if channel is ready write to any sockets that have space in their buffer and for which we have data */ if (channel.ready() && key.isWritable()) { Send send = channel.write(); if (send != null) { this.completedSends.add(send); this.sensors.recordBytesSent(channel.id(), send.size()); } } /* cancel any defunct sockets */ if (!key.isValid()) close(channel, true); } catch (Exception e) { String desc = channel.socketDescription(); if (e instanceof IOException) log.debug("Connection with {} disconnected", desc, e); else if (e instanceof AuthenticationException) // will be logged later as error by clients log.debug("Connection with {} disconnected due to authentication exception", desc, e); else log.warn("Unexpected error from {}; closing connection", desc, e); close(channel, true); } finally { maybeRecordTimePerConnection(channel, channelStartTimeNanos); } } } private Collection<SelectionKey> determineHandlingOrder(Set<SelectionKey> selectionKeys) { //it is possible that the iteration order over selectionKeys is the same every invocation. //this may cause starvation of reads when memory is low. to address this we shuffle the keys if memory is low. Collection<SelectionKey> inHandlingOrder; if (!outOfMemory && memoryPool.availableMemory() < lowMemThreshold) { List<SelectionKey> temp = new ArrayList<>(selectionKeys); Collections.shuffle(temp); inHandlingOrder = temp; } else { inHandlingOrder = selectionKeys; } return inHandlingOrder; } private void attemptRead(SelectionKey key, KafkaChannel channel) throws IOException { //if channel is ready and has bytes to read from socket or buffer, and has no //previous receive(s) already staged or otherwise in progress then read from it if (channel.ready() && (key.isReadable() || channel.hasBytesBuffered()) && !hasStagedReceive(channel) && !explicitlyMutedChannels.contains(channel)) { NetworkReceive networkReceive; while ((networkReceive = channel.read()) != null) { madeReadProgressLastPoll = true; addToStagedReceives(channel, networkReceive); } if (channel.isMute()) { outOfMemory = true; //channel has muted itself due to memory pressure. } else { madeReadProgressLastPoll = true; } } } // Record time spent in pollSelectionKeys for channel (moved into a method to keep checkstyle happy) private void maybeRecordTimePerConnection(KafkaChannel channel, long startTimeNanos) { if (recordTimePerConnection) channel.addNetworkThreadTimeNanos(time.nanoseconds() - startTimeNanos); } @Override public List<Send> completedSends() { return this.completedSends; } @Override public List<NetworkReceive> completedReceives() { return this.completedReceives; } @Override public Map<String, ChannelState> disconnected() { return this.disconnected; } @Override public List<String> connected() { return this.connected; } @Override public void mute(String id) { KafkaChannel channel = openOrClosingChannelOrFail(id); mute(channel); } private void mute(KafkaChannel channel) { channel.mute(); explicitlyMutedChannels.add(channel); } @Override public void unmute(String id) { KafkaChannel channel = openOrClosingChannelOrFail(id); unmute(channel); } private void unmute(KafkaChannel channel) { explicitlyMutedChannels.remove(channel); channel.unmute(); } @Override public void muteAll() { for (KafkaChannel channel : this.channels.values()) mute(channel); } @Override public void unmuteAll() { for (KafkaChannel channel : this.channels.values()) unmute(channel); } private void maybeCloseOldestConnection(long currentTimeNanos) { if (idleExpiryManager == null) return; Map.Entry<String, Long> expiredConnection = idleExpiryManager.pollExpiredConnection(currentTimeNanos); if (expiredConnection != null) { String connectionId = expiredConnection.getKey(); KafkaChannel channel = this.channels.get(connectionId); if (channel != null) { if (log.isTraceEnabled()) log.trace("About to close the idle connection from {} due to being idle for {} millis", connectionId, (currentTimeNanos - expiredConnection.getValue()) / 1000 / 1000); channel.state(ChannelState.EXPIRED); close(channel, true); } } } /** * Clear the results from the prior poll */ private void clear() { this.completedSends.clear(); this.completedReceives.clear(); this.connected.clear(); this.disconnected.clear(); // Remove closed channels after all their staged receives have been processed or if a send was requested for (Iterator<Map.Entry<String, KafkaChannel>> it = closingChannels.entrySet().iterator(); it.hasNext(); ) { KafkaChannel channel = it.next().getValue(); Deque<NetworkReceive> deque = this.stagedReceives.get(channel); boolean sendFailed = failedSends.remove(channel.id()); if (deque == null || deque.isEmpty() || sendFailed) { doClose(channel, true); it.remove(); } } for (String channel : this.failedSends) this.disconnected.put(channel, ChannelState.FAILED_SEND); this.failedSends.clear(); this.madeReadProgressLastPoll = false; } /** * Check for data, waiting up to the given timeout. * * @param ms Length of time to wait, in milliseconds, which must be non-negative * @return The number of keys ready * @throws IllegalArgumentException * @throws IOException */ private int select(long ms) throws IOException { if (ms < 0L) throw new IllegalArgumentException("timeout should be >= 0"); if (ms == 0L) return this.nioSelector.selectNow(); else return this.nioSelector.select(ms); } /** * Close the connection identified by the given id */ public void close(String id) { KafkaChannel channel = this.channels.get(id); if (channel != null) { // There is no disconnect notification for local close, but updating // channel state here anyway to avoid confusion. channel.state(ChannelState.LOCAL_CLOSE); close(channel, false); } else { KafkaChannel closingChannel = this.closingChannels.remove(id); // Close any closing channel, leave the channel in the state in which closing was triggered if (closingChannel != null) doClose(closingChannel, false); } } /** * Begin closing this connection. * * If 'processOutstanding' is true, the channel is disconnected here, but staged receives are * processed. The channel is closed when there are no outstanding receives or if a send * is requested. The channel will be added to disconnect list when it is actually closed. * * If 'processOutstanding' is false, outstanding receives are discarded and the channel is * closed immediately. The channel will not be added to disconnected list and it is the * responsibility of the caller to handle disconnect notifications. */ private void close(KafkaChannel channel, boolean processOutstanding) { channel.disconnect(); // Ensure that `connected` does not have closed channels. This could happen if `prepare` throws an exception // in the `poll` invocation when `finishConnect` succeeds connected.remove(channel.id()); // Keep track of closed channels with pending receives so that all received records // may be processed. For example, when producer with acks=0 sends some records and // closes its connections, a single poll() in the broker may receive records and // handle close(). When the remote end closes its connection, the channel is retained until // a send fails or all outstanding receives are processed. Mute state of disconnected channels // are tracked to ensure that requests are processed one-by-one by the broker to preserve ordering. Deque<NetworkReceive> deque = this.stagedReceives.get(channel); if (processOutstanding && deque != null && !deque.isEmpty()) { // stagedReceives will be moved to completedReceives later along with receives from other channels closingChannels.put(channel.id(), channel); } else doClose(channel, processOutstanding); this.channels.remove(channel.id()); if (idleExpiryManager != null) idleExpiryManager.remove(channel.id()); } private void doClose(KafkaChannel channel, boolean notifyDisconnect) { try { channel.close(); } catch (IOException e) { log.error("Exception closing connection to node {}:", channel.id(), e); } this.sensors.connectionClosed.record(); this.stagedReceives.remove(channel); if (notifyDisconnect) this.disconnected.put(channel.id(), channel.state()); } /** * check if channel is ready */ @Override public boolean isChannelReady(String id) { KafkaChannel channel = this.channels.get(id); return channel != null && channel.ready(); } private KafkaChannel openOrClosingChannelOrFail(String id) { KafkaChannel channel = this.channels.get(id); if (channel == null) channel = this.closingChannels.get(id); if (channel == null) throw new IllegalStateException("Attempt to retrieve channel for which there is no connection. Connection id " + id + " existing connections " + channels.keySet()); return channel; } /** * Return the selector channels. */ public List<KafkaChannel> channels() { return new ArrayList<>(channels.values()); } /** * Return the channel associated with this connection or `null` if there is no channel associated with the * connection. */ public KafkaChannel channel(String id) { return this.channels.get(id); } /** * Return the channel with the specified id if it was disconnected, but not yet closed * since there are outstanding messages to be processed. */ public KafkaChannel closingChannel(String id) { return closingChannels.get(id); } /** * Get the channel associated with selectionKey */ private KafkaChannel channel(SelectionKey key) { return (KafkaChannel) key.attachment(); } /** * Check if given channel has a staged receive */ private boolean hasStagedReceive(KafkaChannel channel) { return stagedReceives.containsKey(channel); } /** * check if stagedReceives have unmuted channel */ private boolean hasStagedReceives() { for (KafkaChannel channel : this.stagedReceives.keySet()) { if (!channel.isMute()) return true; } return false; } /** * adds a receive to staged receives */ private void addToStagedReceives(KafkaChannel channel, NetworkReceive receive) { if (!stagedReceives.containsKey(channel)) stagedReceives.put(channel, new ArrayDeque<NetworkReceive>()); Deque<NetworkReceive> deque = stagedReceives.get(channel); deque.add(receive); } /** * checks if there are any staged receives and adds to completedReceives */ private void addToCompletedReceives() { if (!this.stagedReceives.isEmpty()) { Iterator<Map.Entry<KafkaChannel, Deque<NetworkReceive>>> iter = this.stagedReceives.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<KafkaChannel, Deque<NetworkReceive>> entry = iter.next(); KafkaChannel channel = entry.getKey(); if (!explicitlyMutedChannels.contains(channel)) { Deque<NetworkReceive> deque = entry.getValue(); addToCompletedReceives(channel, deque); if (deque.isEmpty()) iter.remove(); } } } } private void addToCompletedReceives(KafkaChannel channel, Deque<NetworkReceive> stagedDeque) { NetworkReceive networkReceive = stagedDeque.poll(); this.completedReceives.add(networkReceive); this.sensors.recordBytesReceived(channel.id(), networkReceive.payload().limit()); } // only for testing public Set<SelectionKey> keys() { return new HashSet<>(nioSelector.keys()); } // only for testing public int numStagedReceives(KafkaChannel channel) { Deque<NetworkReceive> deque = stagedReceives.get(channel); return deque == null ? 0 : deque.size(); } private class SelectorMetrics { private final Metrics metrics; private final String metricGrpPrefix; private final Map<String, String> metricTags; private final boolean metricsPerConnection; public final Sensor connectionClosed; public final Sensor connectionCreated; public final Sensor successfulAuthentication; public final Sensor failedAuthentication; public final Sensor bytesTransferred; public final Sensor bytesSent; public final Sensor bytesReceived; public final Sensor selectTime; public final Sensor ioTime; /* Names of metrics that are not registered through sensors */ private final List<MetricName> topLevelMetricNames = new ArrayList<>(); private final List<Sensor> sensors = new ArrayList<>(); public SelectorMetrics(Metrics metrics, String metricGrpPrefix, Map<String, String> metricTags, boolean metricsPerConnection) { this.metrics = metrics; this.metricGrpPrefix = metricGrpPrefix; this.metricTags = metricTags; this.metricsPerConnection = metricsPerConnection; String metricGrpName = metricGrpPrefix + "-metrics"; StringBuilder tagsSuffix = new StringBuilder(); for (Map.Entry<String, String> tag: metricTags.entrySet()) { tagsSuffix.append(tag.getKey()); tagsSuffix.append("-"); tagsSuffix.append(tag.getValue()); } this.connectionClosed = sensor("connections-closed:" + tagsSuffix); this.connectionClosed.add(createMeter(metrics, metricGrpName, metricTags, "connection-close", "connections closed")); this.connectionCreated = sensor("connections-created:" + tagsSuffix); this.connectionCreated.add(createMeter(metrics, metricGrpName, metricTags, "connection-creation", "new connections established")); this.successfulAuthentication = sensor("successful-authentication:" + tagsSuffix); this.successfulAuthentication.add(createMeter(metrics, metricGrpName, metricTags, "successful-authentication", "connections with successful authentication")); this.failedAuthentication = sensor("failed-authentication:" + tagsSuffix); this.failedAuthentication.add(createMeter(metrics, metricGrpName, metricTags, "failed-authentication", "connections with failed authentication")); this.bytesTransferred = sensor("bytes-sent-received:" + tagsSuffix); bytesTransferred.add(createMeter(metrics, metricGrpName, metricTags, new Count(), "network-io", "network operations (reads or writes) on all connections")); this.bytesSent = sensor("bytes-sent:" + tagsSuffix, bytesTransferred); this.bytesSent.add(createMeter(metrics, metricGrpName, metricTags, "outgoing-byte", "outgoing bytes sent to all servers")); this.bytesSent.add(createMeter(metrics, metricGrpName, metricTags, new Count(), "request", "requests sent")); MetricName metricName = metrics.metricName("request-size-avg", metricGrpName, "The average size of requests sent.", metricTags); this.bytesSent.add(metricName, new Avg()); metricName = metrics.metricName("request-size-max", metricGrpName, "The maximum size of any request sent.", metricTags); this.bytesSent.add(metricName, new Max()); this.bytesReceived = sensor("bytes-received:" + tagsSuffix, bytesTransferred); this.bytesReceived.add(createMeter(metrics, metricGrpName, metricTags, "incoming-byte", "bytes read off all sockets")); this.bytesReceived.add(createMeter(metrics, metricGrpName, metricTags, new Count(), "response", "responses received")); this.selectTime = sensor("select-time:" + tagsSuffix); this.selectTime.add(createMeter(metrics, metricGrpName, metricTags, new Count(), "select", "times the I/O layer checked for new I/O to perform")); metricName = metrics.metricName("io-wait-time-ns-avg", metricGrpName, "The average length of time the I/O thread spent waiting for a socket ready for reads or writes in nanoseconds.", metricTags); this.selectTime.add(metricName, new Avg()); this.selectTime.add(createIOThreadRatioMeter(metrics, metricGrpName, metricTags, "io-wait", "waiting")); this.ioTime = sensor("io-time:" + tagsSuffix); metricName = metrics.metricName("io-time-ns-avg", metricGrpName, "The average length of time for I/O per select call in nanoseconds.", metricTags); this.ioTime.add(metricName, new Avg()); this.ioTime.add(createIOThreadRatioMeter(metrics, metricGrpName, metricTags, "io", "doing I/O")); metricName = metrics.metricName("connection-count", metricGrpName, "The current number of active connections.", metricTags); topLevelMetricNames.add(metricName); this.metrics.addMetric(metricName, new Measurable() { public double measure(MetricConfig config, long now) { return channels.size(); } }); } private Meter createMeter(Metrics metrics, String groupName, Map<String, String> metricTags, SampledStat stat, String baseName, String descriptiveName) { MetricName rateMetricName = metrics.metricName(baseName + "-rate", groupName, String.format("The number of %s per second", descriptiveName), metricTags); MetricName totalMetricName = metrics.metricName(baseName + "-total", groupName, String.format("The total number of %s", descriptiveName), metricTags); if (stat == null) return new Meter(rateMetricName, totalMetricName); else return new Meter(stat, rateMetricName, totalMetricName); } private Meter createMeter(Metrics metrics, String groupName, Map<String, String> metricTags, String baseName, String descriptiveName) { return createMeter(metrics, groupName, metricTags, null, baseName, descriptiveName); } private Meter createIOThreadRatioMeter(Metrics metrics, String groupName, Map<String, String> metricTags, String baseName, String action) { MetricName rateMetricName = metrics.metricName(baseName + "-ratio", groupName, String.format("The fraction of time the I/O thread spent %s", action), metricTags); MetricName totalMetricName = metrics.metricName(baseName + "time-total", groupName, String.format("The total time the I/O thread spent %s", action), metricTags); return new Meter(TimeUnit.NANOSECONDS, rateMetricName, totalMetricName); } private Sensor sensor(String name, Sensor... parents) { Sensor sensor = metrics.sensor(name, parents); sensors.add(sensor); return sensor; } public void maybeRegisterConnectionMetrics(String connectionId) { if (!connectionId.isEmpty() && metricsPerConnection) { // if one sensor of the metrics has been registered for the connection, // then all other sensors should have been registered; and vice versa String nodeRequestName = "node-" + connectionId + ".bytes-sent"; Sensor nodeRequest = this.metrics.getSensor(nodeRequestName); if (nodeRequest == null) { String metricGrpName = metricGrpPrefix + "-node-metrics"; Map<String, String> tags = new LinkedHashMap<>(metricTags); tags.put("node-id", "node-" + connectionId); nodeRequest = sensor(nodeRequestName); nodeRequest.add(createMeter(metrics, metricGrpName, tags, "outgoing-byte", "outgoing bytes")); nodeRequest.add(createMeter(metrics, metricGrpName, tags, new Count(), "request", "requests sent")); MetricName metricName = metrics.metricName("request-size-avg", metricGrpName, "The average size of requests sent.", tags); nodeRequest.add(metricName, new Avg()); metricName = metrics.metricName("request-size-max", metricGrpName, "The maximum size of any request sent.", tags); nodeRequest.add(metricName, new Max()); String nodeResponseName = "node-" + connectionId + ".bytes-received"; Sensor nodeResponse = sensor(nodeResponseName); nodeResponse.add(createMeter(metrics, metricGrpName, tags, "incoming-byte", "incoming bytes")); nodeResponse.add(createMeter(metrics, metricGrpName, tags, new Count(), "response", "responses received")); String nodeTimeName = "node-" + connectionId + ".latency"; Sensor nodeRequestTime = sensor(nodeTimeName); metricName = metrics.metricName("request-latency-avg", metricGrpName, tags); nodeRequestTime.add(metricName, new Avg()); metricName = metrics.metricName("request-latency-max", metricGrpName, tags); nodeRequestTime.add(metricName, new Max()); } } } public void recordBytesSent(String connectionId, long bytes) { long now = time.milliseconds(); this.bytesSent.record(bytes, now); if (!connectionId.isEmpty()) { String nodeRequestName = "node-" + connectionId + ".bytes-sent"; Sensor nodeRequest = this.metrics.getSensor(nodeRequestName); if (nodeRequest != null) nodeRequest.record(bytes, now); } } public void recordBytesReceived(String connection, int bytes) { long now = time.milliseconds(); this.bytesReceived.record(bytes, now); if (!connection.isEmpty()) { String nodeRequestName = "node-" + connection + ".bytes-received"; Sensor nodeRequest = this.metrics.getSensor(nodeRequestName); if (nodeRequest != null) nodeRequest.record(bytes, now); } } public void close() { for (MetricName metricName : topLevelMetricNames) metrics.removeMetric(metricName); for (Sensor sensor : sensors) metrics.removeSensor(sensor.name()); } } // helper class for tracking least recently used connections to enable idle connection closing private static class IdleExpiryManager { private final Map<String, Long> lruConnections; private final long connectionsMaxIdleNanos; private long nextIdleCloseCheckTime; public IdleExpiryManager(Time time, long connectionsMaxIdleMs) { this.connectionsMaxIdleNanos = connectionsMaxIdleMs * 1000 * 1000; // initial capacity and load factor are default, we set them explicitly because we want to set accessOrder = true this.lruConnections = new LinkedHashMap<>(16, .75F, true); this.nextIdleCloseCheckTime = time.nanoseconds() + this.connectionsMaxIdleNanos; } public void update(String connectionId, long currentTimeNanos) { lruConnections.put(connectionId, currentTimeNanos); } public Map.Entry<String, Long> pollExpiredConnection(long currentTimeNanos) { if (currentTimeNanos <= nextIdleCloseCheckTime) return null; if (lruConnections.isEmpty()) { nextIdleCloseCheckTime = currentTimeNanos + connectionsMaxIdleNanos; return null; } Map.Entry<String, Long> oldestConnectionEntry = lruConnections.entrySet().iterator().next(); Long connectionLastActiveTime = oldestConnectionEntry.getValue(); nextIdleCloseCheckTime = connectionLastActiveTime + connectionsMaxIdleNanos; if (currentTimeNanos > nextIdleCloseCheckTime) return oldestConnectionEntry; else return null; } public void remove(String connectionId) { lruConnections.remove(connectionId); } } //package-private for testing boolean isOutOfMemory() { return outOfMemory; } //package-private for testing boolean isMadeReadProgressLastPoll() { return madeReadProgressLastPoll; } }
public class Missing implements Interface { public void interfaceMethod () { System.out.println("Missing.interfaceMethod()"); } public void missingMethod () { System.out.println("Missing.missingMethod()"); } }
package me.zhengjie.service; import me.zhengjie.domain.CalibrationOrg; import me.zhengjie.service.dto.CaliOrgQueryCriteria; import me.zhengjie.service.dto.CalibrationOrgDto; import org.springframework.data.domain.Pageable; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; /** * @author tmj * @version 1.0 * @date 2022/3/11 11:32 */ public interface CaliOrgService { /** * 查询全部数据 * * @param criteria / * @return / */ List<CalibrationOrg> queryAll(CaliOrgQueryCriteria criteria); /** * 分页查询 * * @param criteria 条件 * @param pageable 分页参数 * @return / */ Map<String, Object> queryAll(CaliOrgQueryCriteria criteria, Pageable pageable); /** * 导出数据 * * @param queryAll 待导出的数据 * @param response / * @throws IOException / */ void download(List<CalibrationOrg> queryAll, HttpServletResponse response) throws IOException; /** * 根据ID查询 * * @param caliOrgId / * @return / */ CalibrationOrgDto findById(Long caliOrgId); /** * 新增/创建 * * @param resources / */ void create(CalibrationOrgDto resources); /** * 编辑 * * @param resources / */ void update(CalibrationOrg resources); /** * 删除 * * @param ids / */ void delete(Set<Long> ids); }
/* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.resources.media; import java.io.IOException; import java.io.InputStream; import java.util.PropertyResourceBundle; /** * Resource loader for OSP video package. Resource strings are obtained from properties. * * Defining a Java resource class speeds up resource loading, particularly for applets because * a connection to the server is not required. * * @author Wolfgang Christian */ public class video extends PropertyResourceBundle { // relative path to strings static String res = "video.properties"; //$NON-NLS-1$ /** * Constructor video * @throws IOException */ public video() throws IOException { this(video.class.getResourceAsStream(res)); } /** * Constructor tools * @param stream * @throws IOException */ public video(InputStream stream) throws IOException { super(stream); } } /* * Open Source Physics software is free software; you can redistribute * it and/or modify it under the terms of the GNU General Public License (GPL) as * published by the Free Software Foundation; either version 2 of the License, * or(at your option) any later version. * Code that uses any portion of the code in the org.opensourcephysics package * or any subpackage (subdirectory) of this package must must also be be released * under the GNU GPL license. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston MA 02111-1307 USA * or view the license online at http://www.gnu.org/copyleft/gpl.html * * Copyright (c) 2007 The Open Source Physics project * http://www.opensourcephysics.org */
package com.org.derpyjakey.frames; import com.org.derpyjakey.utilities.LanguageHandler; import com.org.derpyjakey.references.Directories; import com.org.derpyjakey.utilities.LogHandler; import com.org.derpyjakey.utilities.IOHandler; import java.awt.event.ActionEvent; import javax.swing.border.*; import javax.swing.*; import java.awt.*; public class Bot { private String activeLanguage = ""; private String activeChannel; private JFrame frame = new JFrame(); private JLabel botLabel = new JLabel(); private JLabel commandKeyLabel = new JLabel(); private JLabel blacklistLabel = new JLabel(); private JLabel blacklistEnableLabel = new JLabel(); private JLabel blacklistRulesLabel = new JLabel(); private JLabel blacklistResponseLabel = new JLabel(); private JLabel capLimitLabel = new JLabel(); private JLabel capLimitEnableLabel = new JLabel(); private JLabel capLimitRulesLabel = new JLabel(); private JLabel capLimitResponseLabel = new JLabel(); private JLabel charLimitLabel = new JLabel(); private JLabel charLimitEnableLabel = new JLabel(); private JLabel charLimitRulesLabel = new JLabel(); private JLabel charLimitResponseLabel = new JLabel(); private JLabel wordLimitLabel = new JLabel(); private JLabel wordLimitEnableLabel = new JLabel(); private JLabel wordLimitRulesLabel = new JLabel(); private JLabel wordLimitResponseLabel = new JLabel(); private JLabel spamProtectionLabel = new JLabel(); private JLabel spamProtectionEnableLabel = new JLabel(); private JLabel spamProtectionRuleLabel = new JLabel(); private JLabel spamProtectionResponseLabel = new JLabel(); private JLabel timeoutBanLabel = new JLabel(); private JCheckBox botEnableCheckbox = new JCheckBox(); private JCheckBox blacklistEnableCheckbox = new JCheckBox(); private JCheckBox capLimitEnableCheckbox = new JCheckBox(); private JCheckBox charLimitEnableCheckbox = new JCheckBox(); private JCheckBox wordLimitEnableCheckbox = new JCheckBox(); private JCheckBox spamProtectionEnableCheckbox = new JCheckBox(); private JTextField commandKeyTextfield = new JTextField(8); private JTextField blacklistRulesTextfield = new JTextField(10); private JTextField blacklistResponseTextfield = new JTextField(10); private JTextField capLimitRulesTextfield = new JTextField(10); private JTextField capLimitResponseTextfield = new JTextField(10); private JTextField charLimitRulesTextfield = new JTextField(10); private JTextField charLimitResponseTextfield = new JTextField(10); private JTextField wordLimitRulesTextfield = new JTextField(10); private JTextField wordLimitResponseTextfield = new JTextField(10); private JTextField spamProtectionRuleTextfield = new JTextField(10); private JTextField spamProtectionResponseTextfield = new JTextField(10); private JTextField timeoutBanTextfield = new JTextField(10); private JButton saveButton = new JButton(); private JButton closeButton = new JButton(); private JPanel mainPanel = new JPanel(new GridBagLayout()); private GridBagConstraints gridLayout = new GridBagConstraints(); public Bot(String channel) { activeChannel = channel; updateLanguage(); addComponents(); setFrameProperties(); updateSettings(); saveButton.addActionListener((ActionEvent actionEvent) -> { IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Enable Bot", botEnableCheckbox.isSelected()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Enable Blacklist", blacklistEnableCheckbox.isSelected()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Enable Cap Limit", capLimitEnableCheckbox.isSelected()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Enable Char Limit", charLimitEnableCheckbox.isSelected()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Enable Word Limit", wordLimitEnableCheckbox.isSelected()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Enable Spam Protection", spamProtectionEnableCheckbox.isSelected()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Command Key", commandKeyTextfield.getText()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Blacklist Rules", blacklistRulesTextfield.getText()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Cap Limit Rules", capLimitRulesTextfield.getText()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Char Limit Rules", charLimitRulesTextfield.getText()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Word Limit Rules", wordLimitRulesTextfield.getText()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Spam Protection Rules", spamProtectionRuleTextfield.getText()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Blacklist Response", blacklistResponseTextfield.getText()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Cap Limit Response", capLimitResponseTextfield.getText()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Char Limit Response", charLimitResponseTextfield.getText()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Word Limit Response", wordLimitResponseTextfield.getText()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Spam Protection Response", spamProtectionResponseTextfield.getText()); IOHandler.setKey(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Timeout/Ban", timeoutBanTextfield.getText()); }); closeButton.addActionListener((ActionEvent actionEvent) -> { frame.dispose(); }); } private void updateLanguage() { if (!activeLanguage.equals(LanguageHandler.getLanguage())) { frame.setTitle(LanguageHandler.getText("Frame.Bot") + " " + activeChannel); commandKeyLabel.setText(LanguageHandler.getText("Label.CommandKey")); botLabel.setText(LanguageHandler.getText("Label.BotFeatureEnable")); blacklistLabel.setText(LanguageHandler.getText("Label.Blacklist")); blacklistEnableLabel.setText(LanguageHandler.getText("Label.BlacklistEnable")); blacklistRulesLabel.setText(LanguageHandler.getText("Label.BlacklistRules")); blacklistResponseLabel.setText(LanguageHandler.getText("Label.BlacklistResponse")); capLimitLabel.setText(LanguageHandler.getText("Label.CapLimit")); capLimitEnableLabel.setText(LanguageHandler.getText("Label.CapLimitEnable")); capLimitRulesLabel.setText(LanguageHandler.getText("Label.CapLimitRules")); capLimitResponseLabel.setText(LanguageHandler.getText("Label.CapLimitResponse")); charLimitLabel.setText(LanguageHandler.getText("Label.CharLimit")); charLimitEnableLabel.setText(LanguageHandler.getText("Label.CharLimitEnable")); charLimitRulesLabel.setText(LanguageHandler.getText("Label.CharLimitRules")); charLimitResponseLabel.setText(LanguageHandler.getText("Label.CharLimitResponse")); wordLimitLabel.setText(LanguageHandler.getText("Label.WordLimit")); wordLimitEnableLabel.setText(LanguageHandler.getText("Label.WordLimitEnable")); wordLimitRulesLabel.setText(LanguageHandler.getText("Label.WordLimitRules")); wordLimitResponseLabel.setText(LanguageHandler.getText("Label.WordLimitResponse")); spamProtectionLabel.setText(LanguageHandler.getText("Label.SpamProtection")); spamProtectionEnableLabel.setText(LanguageHandler.getText("Label.SpamProtectionEnable")); spamProtectionRuleLabel.setText(LanguageHandler.getText("Label.SpamProtectionRule")); spamProtectionResponseLabel.setText(LanguageHandler.getText("Label.SpamProtectionResponse")); timeoutBanLabel.setText(LanguageHandler.getText("Label.TimeoutBan")); saveButton.setText(LanguageHandler.getText("Button.Save")); closeButton.setText(LanguageHandler.getText("Button.Close")); activeLanguage = LanguageHandler.getLanguage(); } } private void addComponents() { gridLayout.weightx = 0.5; int[] tempX = {1, 2, 4, 5, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 2, 4, 2, 4}; int[] tempY = {0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 6, 6, 7, 7}; Component[] tempComp = {botLabel, botEnableCheckbox, commandKeyLabel, commandKeyTextfield, blacklistLabel, blacklistEnableLabel, blacklistEnableCheckbox, blacklistRulesLabel, blacklistRulesTextfield, blacklistResponseLabel, blacklistResponseTextfield, capLimitLabel, capLimitEnableLabel, capLimitEnableCheckbox, capLimitRulesLabel, capLimitRulesTextfield, capLimitResponseLabel, capLimitResponseTextfield, charLimitLabel, charLimitEnableLabel, charLimitEnableCheckbox, charLimitRulesLabel, charLimitRulesTextfield, charLimitResponseLabel, charLimitResponseTextfield, wordLimitLabel, wordLimitEnableLabel, wordLimitEnableCheckbox, wordLimitRulesLabel, wordLimitRulesTextfield, wordLimitResponseLabel, wordLimitResponseTextfield, spamProtectionLabel, spamProtectionEnableLabel, spamProtectionEnableCheckbox, spamProtectionRuleLabel, spamProtectionRuleTextfield, spamProtectionResponseLabel, spamProtectionResponseTextfield, timeoutBanLabel, timeoutBanTextfield, saveButton, closeButton}; setGrid(mainPanel, tempX, tempY, tempComp, gridLayout); frame.getContentPane().add(mainPanel); } private void setGrid(JPanel panel, int[] x, int[] y, Component[] comp, GridBagConstraints gridBagLayout) { for (int i = 0; i <= comp.length - 1; i++) { gridBagLayout.gridx = x[i]; gridBagLayout.gridy = y[i]; panel.add(comp[i], gridBagLayout); } } private void setFrameProperties() { frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setResizable(false); frame.pack(); frame.setVisible(true); } private void updateSettings() { botEnableCheckbox.setSelected(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Enable Bot").equals("True")); blacklistEnableCheckbox.setSelected(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Enable Blacklist").equals("True")); capLimitEnableCheckbox.setSelected(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Enable Cap Limit").equals("True")); charLimitEnableCheckbox.setSelected(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Enable Char Limit").equals("True")); wordLimitEnableCheckbox.setSelected(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Enable Word Limit").equals("True")); spamProtectionEnableCheckbox.setSelected(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Enable Spam Protection").equals("True")); commandKeyTextfield.setText(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Command Key")); blacklistRulesTextfield.setText(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Blacklist Rules")); capLimitRulesTextfield.setText(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Cap Limit Rules")); charLimitRulesTextfield.setText(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Char Limit Rules")); wordLimitRulesTextfield.setText(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Word Limit Rules")); spamProtectionRuleTextfield.setText(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Spam Protection Rules")); blacklistResponseTextfield.setText(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Blacklist Response")); capLimitResponseTextfield.setText(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Cap Limit Response")); charLimitResponseTextfield.setText(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Char Limit Response")); wordLimitResponseTextfield.setText(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Word Limit Response")); spamProtectionResponseTextfield.setText(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Spam Protection Response")); timeoutBanTextfield.setText(IOHandler.getValue(Directories.Files.channelFile.replace("%CHANNEL%", activeChannel), "Timeout/Ban")); } }
package uk.gov.digital.ho.proving.income.validator; import org.junit.Test; import java.time.LocalDate; import java.time.Month; import static org.assertj.core.api.Assertions.assertThat; public class ValidationHelperDateTest { @Test public void sameDayOneMonthDifference() { LocalDate from = LocalDate.of(2015, Month.JANUARY, 23); LocalDate to = LocalDate.of(2015, Month.FEBRUARY, 23); long months = IncomeValidationHelper.getDifferenceInMonthsBetweenDates(to, from); assertThat(months).isEqualTo(1L).withFailMessage("There should be 1 month between the dates"); } @Test public void earlierDayOneMonthDifference() { LocalDate from = LocalDate.of(2015,Month.JUNE,17); LocalDate to = LocalDate.of(2015,Month.JULY,14); long months = IncomeValidationHelper.getDifferenceInMonthsBetweenDates(to, from); assertThat(months).isEqualTo(1L).withFailMessage("There should be 1 month between the dates"); } @Test public void laterDayOneMonthDifference() { LocalDate from = LocalDate.of(2015,Month.JANUARY,1); LocalDate to = LocalDate.of(2015,Month.FEBRUARY,28); long months = IncomeValidationHelper.getDifferenceInMonthsBetweenDates(to, from); assertThat(months).isEqualTo(1L).withFailMessage("There should be 1 month between the dates"); } @Test public void laterDayTwoMonthsDifference() { LocalDate from = LocalDate.of(2014,Month.DECEMBER,1); LocalDate to = LocalDate.of(2015,Month.FEBRUARY,28); long months = IncomeValidationHelper.getDifferenceInMonthsBetweenDates(to, from); assertThat(months).isEqualTo(2L).withFailMessage("There should be 2 months between the dates"); } @Test public void moreThanOneYearMonthDifference() { LocalDate from = LocalDate.of(2014,Month.DECEMBER,1); LocalDate to = LocalDate.of(2016,Month.FEBRUARY,28); long months = IncomeValidationHelper.getDifferenceInMonthsBetweenDates(to, from); assertThat(months).isEqualTo(14L).withFailMessage("There should be 14 months between the dates"); } }
package io.dropwizard.servlets.tasks; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import io.dropwizard.util.Maps; import org.junit.jupiter.api.Test; import java.io.PrintWriter; import java.io.StringWriter; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; public class LogConfigurationTaskTest { private final LoggerContext loggerContext = new LoggerContext(); private final Logger logger1 = loggerContext.getLogger("logger.one"); private final Logger logger2 = loggerContext.getLogger("logger.two"); private final StringWriter stringWriter = new StringWriter(); private final PrintWriter output = new PrintWriter(stringWriter); private final LogConfigurationTask task = new LogConfigurationTask(loggerContext); @Test public void configuresSpecificLevelForALogger() throws Exception { // given Level twoEffectiveBefore = logger2.getEffectiveLevel(); Map<String, List<String>> parameters = Maps.of( "logger", Collections.singletonList("logger.one"), "level", Collections.singletonList("debug")); // when task.execute(parameters, output); // then assertThat(logger1.getEffectiveLevel()).isEqualTo(Level.DEBUG); assertThat(logger2.getEffectiveLevel()).isEqualTo(twoEffectiveBefore); assertThat(stringWriter.toString()).isEqualTo(String.format("Configured logging level for logger.one to DEBUG%n")); } @Test public void configuresSpecificLevelForALoggerForADuration() throws Exception { // given long millis = 2000; Level oneEffectiveBefore = logger1.getEffectiveLevel(); Map<String, List<String>> parameters = Maps.of( "logger", Collections.singletonList("logger.one"), "level", Collections.singletonList("debug"), "duration", Collections.singletonList(Duration.ofMillis(millis).toString())); // when task.execute(parameters, output); // then assertThat(logger1.getLevel()).isEqualTo(Level.DEBUG); assertThat(stringWriter.toString()).isEqualTo(String.format("Configured logging level for logger.one to DEBUG for %d milliseconds%n", millis)); // after Thread.sleep(4000); assertThat(logger1.getEffectiveLevel()).isEqualTo(oneEffectiveBefore); } @Test public void configuresDefaultLevelForALogger() throws Exception { // given Level oneEffectiveBefore = logger1.getEffectiveLevel(); Level twoEffectiveBefore = logger2.getEffectiveLevel(); Map<String, List<String>> parameters = Collections.singletonMap("logger", Collections.singletonList("logger.one")); // when task.execute(parameters, output); // then assertThat(logger1.getLevel()).isNull(); assertThat(logger1.getEffectiveLevel()).isEqualTo(oneEffectiveBefore); assertThat(logger2.getEffectiveLevel()).isEqualTo(twoEffectiveBefore); assertThat(stringWriter.toString()).isEqualTo(String.format("Configured logging level for logger.one to null%n")); } @Test public void configuresLevelForMultipleLoggers() throws Exception { // given Map<String, List<String>> parameters = Maps.of( "logger", Arrays.asList("logger.one", "logger.two"), "level", Collections.singletonList("INFO")); // when task.execute(parameters, output); // then assertThat(logger1.getEffectiveLevel()).isEqualTo(Level.INFO); assertThat(logger2.getEffectiveLevel()).isEqualTo(Level.INFO); assertThat(stringWriter.toString()) .isEqualTo(String.format("Configured logging level for logger.one to INFO%nConfigured logging level for logger.two to INFO%n")); } }
/* * The MIT License * * Copyright 2013 Andreas Giemza. * * 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 de.andreasgiemza.jgeagle.repo.data; import java.nio.file.Path; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.eclipse.jgit.revwalk.RevCommit; /** * * @author Andreas Giemza */ public class EagleFile { private final Path file; private final Path repoFile; private final String fileName; private final String fileExtension; private Boolean workingCopychanges; private Date workingCopyLastModified; private final List<RevCommit> commits = new LinkedList<>(); private final Map<RevCommit, String> renames = new HashMap<>(); private boolean follow; // Constants public final static String BRD = ".brd"; public final static String SCH = ".sch"; public EagleFile(Path file, Path repoFile) { this.file = file; this.repoFile = repoFile; fileName = repoFile.getFileName().toString().substring( 0, repoFile.getFileName().toString().length() - 4); if (repoFile.toString().toLowerCase().endsWith(".brd")) { fileExtension = BRD; } else { fileExtension = SCH; } } public void clearData() { commits.clear(); renames.clear(); } public Path getFile() { return file; } public Path getRepoFile() { return repoFile; } public String getFileName() { return fileName; } public String getFileExtension() { return fileExtension; } public Boolean isWorkingCopychanges() { return workingCopychanges; } public void setWorkingCopychanges(Boolean workingCopychanges) { this.workingCopychanges = workingCopychanges; } public Date getWorkingCopyLastModified() { return workingCopyLastModified; } public void setWorkingCopyLastModified(Date workingCopyLastModified) { this.workingCopyLastModified = workingCopyLastModified; } public List<RevCommit> getCommits() { return commits; } public Map<RevCommit, String> getRenames() { return renames; } public boolean isFollow() { return follow; } public void setFollow(boolean follow) { this.follow = follow; } @Override public String toString() { return file.getFileName().toString(); } }
/** * Copyright 2013 Canada Health Infoway, 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. * * Author: $LastChangedBy$ * Last modified: $LastChangedDate$ * Revision: $LastChangedRevision$ */ /* This class was auto-generated by the message builder generator tools. */ package ca.infoway.messagebuilder.model.pcs_mr2009_r02_04_02.claims.merged; import ca.infoway.messagebuilder.annotation.Hl7PartTypeMapping; import ca.infoway.messagebuilder.annotation.Hl7XmlMapping; import ca.infoway.messagebuilder.datatype.CV; import ca.infoway.messagebuilder.datatype.II; import ca.infoway.messagebuilder.datatype.IVL; import ca.infoway.messagebuilder.datatype.MO; import ca.infoway.messagebuilder.datatype.TS; import ca.infoway.messagebuilder.datatype.impl.CVImpl; import ca.infoway.messagebuilder.datatype.impl.IIImpl; import ca.infoway.messagebuilder.datatype.impl.IVLImpl; import ca.infoway.messagebuilder.datatype.impl.MOImpl; import ca.infoway.messagebuilder.datatype.lang.Identifier; import ca.infoway.messagebuilder.datatype.lang.Interval; import ca.infoway.messagebuilder.datatype.lang.Money; import ca.infoway.messagebuilder.model.MessagePartBean; import ca.infoway.messagebuilder.model.pcs_mr2009_r02_04_02.claims.ficr_mt600201ca.InvoiceElementComponentBean; import ca.infoway.messagebuilder.model.pcs_mr2009_r02_04_02.claims.ficr_mt600201ca.PolicyOrAccountBean; import ca.infoway.messagebuilder.model.pcs_mr2009_r02_04_02.common.coct_mt280001ca.A_BillableActChoice; import ca.infoway.messagebuilder.model.pcs_mr2009_r02_04_02.common.coct_mt680000ca.AdjudicatedInvoiceElementGroupBean; import ca.infoway.messagebuilder.model.pcs_mr2009_r02_04_02.domainvalue.ActInvoiceGroupType; import java.util.ArrayList; import java.util.Date; import java.util.List; @Hl7PartTypeMapping({"FICR_MT600201CA.InvoiceElementGroup","FICR_MT610201CA.InvoiceElementGroup","QUCR_MT830201CA.InvoiceElementGroup"}) public class InvoiceGroupingIdentifiersBean extends MessagePartBean implements ca.infoway.messagebuilder.model.pcs_mr2009_r02_04_02.claims.ficr_mt600201ca.InvoiceElementChoice, ca.infoway.messagebuilder.model.pcs_mr2009_r02_04_02.claims.ficr_mt610201ca.InvoiceElementChoice { private static final long serialVersionUID = 20190730L; private II id = new IIImpl(); private CV code = new CVImpl(); private IVL<TS, Interval<Date>> effectiveTime = new IVLImpl<TS, Interval<Date>>(); private MO netAmt = new MOImpl(); private FinancialContractBean inFulfillmentOfFinancialContract; private List<HealthDocumentAttachment_2Bean> pertinentInformationHealthDocumentAttachment = new ArrayList<HealthDocumentAttachment_2Bean>(); private List<InvoiceElementCrossReferenceBean> predecessorInvoiceElementCrossReference = new ArrayList<InvoiceElementCrossReferenceBean>(); private List<AdjudicatedInvoiceElementGroupBean> referenceAdjudicatedInvoiceElementGroup = new ArrayList<AdjudicatedInvoiceElementGroupBean>(); private List<PolicyOrAccountBean> coveragePolicyOrAccount = new ArrayList<PolicyOrAccountBean>(); private List<InvoiceElementComponentBean> component = new ArrayList<InvoiceElementComponentBean>(); private List<A_BillableActChoice> reasonOfBillableActChoice = new ArrayList<A_BillableActChoice>(); private List<InvoiceElementOverrideBean> triggerForInvoiceElementOverride = new ArrayList<InvoiceElementOverrideBean>(); /** * <p>Un-merged Business Name: InvoiceGroupingIdentifierS</p> * * <p>Relationship: FICR_MT600201CA.InvoiceElementGroup.id</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> * * <p>Un-merged Business Name: InvoiceGroupID</p> * * <p>Relationship: QUCR_MT830201CA.InvoiceElementGroup.id</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> * * <p></p><p>For example:</p><p>1. unique invoice group * identifier, independent of adjudicator recipient.</p><p>2. * sequential invoice grouping identifier by * adjudicator.</p><p>Obligation on adjudicator is to return * and communicate about this item with all identifiers (i.e. * identifier 1. and 2.).</p> * * <p>Set of identifiers that uniquely identify the Invoice * Grouping.</p> * * <p>Un-merged Business Name: InvoiceGroupingIdentifier</p> * * <p>Relationship: FICR_MT610201CA.InvoiceElementGroup.id</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ @Hl7XmlMapping({"id"}) public Identifier getId() { return this.id.getValue(); } /** * <p>Un-merged Business Name: InvoiceGroupingIdentifierS</p> * * <p>Relationship: FICR_MT600201CA.InvoiceElementGroup.id</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> * * <p>Un-merged Business Name: InvoiceGroupID</p> * * <p>Relationship: QUCR_MT830201CA.InvoiceElementGroup.id</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> * * <p></p><p>For example:</p><p>1. unique invoice group * identifier, independent of adjudicator recipient.</p><p>2. * sequential invoice grouping identifier by * adjudicator.</p><p>Obligation on adjudicator is to return * and communicate about this item with all identifiers (i.e. * identifier 1. and 2.).</p> * * <p>Set of identifiers that uniquely identify the Invoice * Grouping.</p> * * <p>Un-merged Business Name: InvoiceGroupingIdentifier</p> * * <p>Relationship: FICR_MT610201CA.InvoiceElementGroup.id</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ public void setId(Identifier id) { this.id.setValue(id); } /** * <p>Business Name: InvoiceType</p> * * <p>Un-merged Business Name: InvoiceType</p> * * <p>Relationship: FICR_MT600201CA.InvoiceElementGroup.code</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> * * <p>Un-merged Business Name: InvoiceType</p> * * <p>Relationship: FICR_MT610201CA.InvoiceElementGroup.code</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ @Hl7XmlMapping({"code"}) public ActInvoiceGroupType getCode() { return (ActInvoiceGroupType) this.code.getValue(); } /** * <p>Business Name: InvoiceType</p> * * <p>Un-merged Business Name: InvoiceType</p> * * <p>Relationship: FICR_MT600201CA.InvoiceElementGroup.code</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> * * <p>Un-merged Business Name: InvoiceType</p> * * <p>Relationship: FICR_MT610201CA.InvoiceElementGroup.code</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ public void setCode(ActInvoiceGroupType code) { this.code.setValue(code); } /** * <p>Business Name: TimePeriodForInvoice</p> * * <p>Un-merged Business Name: TimePeriodForInvoice</p> * * <p>Relationship: * FICR_MT600201CA.InvoiceElementGroup.effectiveTime</p> * * <p>Conformance/Cardinality: REQUIRED (0-1)</p> */ @Hl7XmlMapping({"effectiveTime"}) public Interval<Date> getEffectiveTime() { return this.effectiveTime.getValue(); } /** * <p>Business Name: TimePeriodForInvoice</p> * * <p>Un-merged Business Name: TimePeriodForInvoice</p> * * <p>Relationship: * FICR_MT600201CA.InvoiceElementGroup.effectiveTime</p> * * <p>Conformance/Cardinality: REQUIRED (0-1)</p> */ public void setEffectiveTime(Interval<Date> effectiveTime) { this.effectiveTime.setValue(effectiveTime); } /** * <p>Business Name: InvoiceSubTotal</p> * * <p>Un-merged Business Name: InvoiceSubTotal</p> * * <p>Relationship: FICR_MT600201CA.InvoiceElementGroup.netAmt</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> * * <p>Un-merged Business Name: InvoiceSubTotal</p> * * <p>Relationship: FICR_MT610201CA.InvoiceElementGroup.netAmt</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ @Hl7XmlMapping({"netAmt"}) public Money getNetAmt() { return this.netAmt.getValue(); } /** * <p>Business Name: InvoiceSubTotal</p> * * <p>Un-merged Business Name: InvoiceSubTotal</p> * * <p>Relationship: FICR_MT600201CA.InvoiceElementGroup.netAmt</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> * * <p>Un-merged Business Name: InvoiceSubTotal</p> * * <p>Relationship: FICR_MT610201CA.InvoiceElementGroup.netAmt</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ public void setNetAmt(Money netAmt) { this.netAmt.setValue(netAmt); } /** * <p>Un-merged Business Name: (no business name specified)</p> * * <p>Relationship: * FICR_MT600201CA.InvoiceElementGroupInFulfillmentOf.financialContract</p> * * <p>Conformance/Cardinality: REQUIRED (1)</p> */ @Hl7XmlMapping({"inFulfillmentOf/financialContract"}) public FinancialContractBean getInFulfillmentOfFinancialContract() { return this.inFulfillmentOfFinancialContract; } /** * <p>Un-merged Business Name: (no business name specified)</p> * * <p>Relationship: * FICR_MT600201CA.InvoiceElementGroupInFulfillmentOf.financialContract</p> * * <p>Conformance/Cardinality: REQUIRED (1)</p> */ public void setInFulfillmentOfFinancialContract(FinancialContractBean inFulfillmentOfFinancialContract) { this.inFulfillmentOfFinancialContract = inFulfillmentOfFinancialContract; } /** * <p>Un-merged Business Name: (no business name specified)</p> * * <p>Relationship: * FICR_MT600201CA.InvoiceElementGroupAttachment.healthDocumentAttachment</p> * * <p>Conformance/Cardinality: REQUIRED (1)</p> */ @Hl7XmlMapping({"pertinentInformation/healthDocumentAttachment"}) public List<HealthDocumentAttachment_2Bean> getPertinentInformationHealthDocumentAttachment() { return this.pertinentInformationHealthDocumentAttachment; } /** * <p>Un-merged Business Name: (no business name specified)</p> * * <p>Relationship: * FICR_MT600201CA.Predecessor.invoiceElementCrossReference</p> * * <p>Conformance/Cardinality: REQUIRED (1)</p> */ @Hl7XmlMapping({"predecessor/invoiceElementCrossReference"}) public List<InvoiceElementCrossReferenceBean> getPredecessorInvoiceElementCrossReference() { return this.predecessorInvoiceElementCrossReference; } /** * <p>Un-merged Business Name: (no business name specified)</p> * * <p>Relationship: * FICR_MT600201CA.Reference.adjudicatedInvoiceElementGroup</p> * * <p>Conformance/Cardinality: REQUIRED (1)</p> */ @Hl7XmlMapping({"reference/adjudicatedInvoiceElementGroup"}) public List<AdjudicatedInvoiceElementGroupBean> getReferenceAdjudicatedInvoiceElementGroup() { return this.referenceAdjudicatedInvoiceElementGroup; } /** * <p>Un-merged Business Name: (no business name specified)</p> * * <p>Relationship: * FICR_MT600201CA.InvoiceElementCoverage.policyOrAccount</p> * * <p>Conformance/Cardinality: REQUIRED (1)</p> */ @Hl7XmlMapping({"coverage/policyOrAccount"}) public List<PolicyOrAccountBean> getCoveragePolicyOrAccount() { return this.coveragePolicyOrAccount; } /** * <p>Un-merged Business Name: (no business name specified)</p> * * <p>Relationship: * FICR_MT600201CA.InvoiceElementGroup.component</p> * * <p>Conformance/Cardinality: MANDATORY (1-10)</p> */ @Hl7XmlMapping({"component"}) public List<InvoiceElementComponentBean> getComponent() { return this.component; } /** * <p>Un-merged Business Name: (no business name specified)</p> * * <p>Relationship: * FICR_MT600201CA.InvoiceElementReason.billableActChoice</p> * * <p>Conformance/Cardinality: REQUIRED (1)</p> */ @Hl7XmlMapping({"reasonOf/billableActChoice"}) public List<A_BillableActChoice> getReasonOfBillableActChoice() { return this.reasonOfBillableActChoice; } /** * <p>Un-merged Business Name: (no business name specified)</p> * * <p>Relationship: * FICR_MT600201CA.Suggests.invoiceElementOverride</p> * * <p>Conformance/Cardinality: REQUIRED (1)</p> */ @Hl7XmlMapping({"triggerFor/invoiceElementOverride"}) public List<InvoiceElementOverrideBean> getTriggerForInvoiceElementOverride() { return this.triggerForInvoiceElementOverride; } }
package com.kingtogroup.domain; public class ServiceEntity { public String ServiceDate; public String Logo; public String TimeSection; public int Woods; public int Regionid; public double ShopPrice; public int Water; public int Storerid; public double Weight; public String StoreName; public String Mobile; public int BuyCount; public int BeginNum; public int Pid; public int Pstid; public int OrderId; public String MassagerNames; public String Massagers; public String Consignee; public int Storeid; public String Name; public int Stsid; public String Address; public String ShowImg; public String NextSection; public String Remark; public int ServiceSelf; public int Opid; @Override public String toString() { return "ServiceEntity [ServiceDate=" + ServiceDate + ", Logo=" + Logo + ", TimeSection=" + TimeSection + ", Woods=" + Woods + ", Regionid=" + Regionid + ", ShopPrice=" + ShopPrice + ", Water=" + Water + ", Storerid=" + Storerid + ", Weight=" + Weight + ", StoreName=" + StoreName + ", Mobile=" + Mobile + ", BuyCount=" + BuyCount + ", BeginNum=" + BeginNum + ", Pid=" + Pid + ", Pstid=" + Pstid + ", OrderId=" + OrderId + ", MassagerNames=" + MassagerNames + ", Massagers=" + Massagers + ", Consignee=" + Consignee + ", Storeid=" + Storeid + ", Name=" + Name + ", Stsid=" + Stsid + ", Address=" + Address + ", ShowImg=" + ShowImg + ", NextSection=" + NextSection + ", Remark=" + Remark + ", ServiceSelf=" + ServiceSelf + ", Opid=" + Opid + "]"; } }
package GUIPrograms; /** * James N * 2020.10.13 * Loading * loading icon that transitions between all tetrominoes */ import java.awt.Color; import game.*; import game.drawing.Camera; import game.drawing.Draw; import game.physics.Physics; import game.physics.Point; import game.physics.Rect; import java.awt.Color; public class Loading extends GameJava { // must be above 3, powers of 2 are recommended static final double TIME_SCALE = 32; // time scale of 16 looks good with rotation static final boolean ROTATION = true; // rect index, direction 1=up 2=right 3=down 4=left, r, g, b static int[][] moves = { // z { 1, 2, 255, 106, 31 }, { 0, 3, 255, 140, 31 }, // L { 2, 1, 255, 199, 31 }, { 0, 2, 255, 255, 31 }, // o { 0, 4, 192, 255, 31 }, { 3, 4, 68, 255, 31 }, // s { 3, 2, 31, 255, 87 }, { 3, 2, 31, 255, 147 }, { 2, 3, 31, 255, 184 }, { 1, 3, 31, 255, 244 }, // i { 2, 1, 31, 177, 255 }, { 0, 2, 31, 53, 255 }, // j { 0, 4, 113, 31, 255 }, { 1, 4, 165, 31, 255 }, { 3, 4, 203, 31, 255 }, // t { 0, 1, 255, 31, 31 } // z }; static int movementIndex = 0; static int movementTime = 0; static Rect[] rects = { new Rect(0, 1, 1, 1), new Rect(1, 1, 1, 1), new Rect(1, 2, 1, 1), new Rect(2, 2, 1, 1) }; static Point[] rectsOffsets = { new Point(0, 0), new Point(0, 0), new Point(0, 0), new Point(0, 0) }; public Loading() { super(256, 256, 60, 60); Draw.alphaBetweenFrames = 0.2f; Draw.undecorate(); LoopManager.startLoops(this); } public static void main(String[] args) { new Loading(); } @Override public void update() { if (ROTATION) { Camera.angle += (Math.PI * 2.0) / (moves.length * TIME_SCALE); } movementTime++; // go to next movement if (movementTime > TIME_SCALE) { movementTime = 0; movementIndex++; // round blocks to nearest 32 for (int i = 0; i < rects.length; i++) { rects[i].x += Math.round(rectsOffsets[i].x / 32); rects[i].y += Math.round(rectsOffsets[i].y / 32); rectsOffsets[i] = new Point(0, 0); } // reset loop if (movementIndex == moves.length) { movementIndex = 0; rects[0] = new Rect(0, 1, 1, 1); rects[1] = new Rect(1, 1, 1, 1); rects[2] = new Rect(1, 2, 1, 1); rects[3] = new Rect(2, 2, 1, 1); for (int i = 0; i < 4; i++) { rectsOffsets[i] = new Point(0, 0); } } } // move block int i = moves[movementIndex][0]; switch (moves[movementIndex][1]) { case 1: rectsOffsets[i].y -= 32.0 / TIME_SCALE; break; case 2: rectsOffsets[i].x += 32.0 / TIME_SCALE; break; case 3: rectsOffsets[i].y += 32.0 / TIME_SCALE; break; case 4: rectsOffsets[i].x -= 32.0 / TIME_SCALE; break; } } @Override public void draw() { Draw.setColor(new Color(30, 30, 30)); Draw.rect(gw / 2, gh / 2, gw * 2, gh * 2); int[] c = moves[movementIndex]; Draw.setColor(new Color(c[2], c[3], c[4])); for (int i = 0; i < rects.length; i++) { Draw.rect((int) (rects[i].x * 32 + rectsOffsets[i].x) + 64, (int) (rects[i].y * 32 + rectsOffsets[i].y) + 64, 30, 30); } } @Override public void absoluteDraw() {} }
package com.ithub.source.learn.nio; import lombok.extern.slf4j.Slf4j; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; /** * BIO */ @Slf4j public class SocketIO { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(9990); log.info("step1: new ServerSocket(9990)"); Socket client = server.accept(); log.info("step2: client\t {}",client.getPort()); InputStream in = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); System.out.println(reader.readLine()); while (true){ } } }
/** * Copyright (c) 2018-present, A2 Rešitve d.o.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 eu.solutions.a2.cdc.oracle.utils; import java.sql.Types; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import eu.solutions.a2.cdc.oracle.OraCdcJdbcSinkConnectionPool; import eu.solutions.a2.cdc.oracle.OraColumn; /** * * @author averemee * */ public class TargetDbSqlUtils { public static final String INSERT = "0#"; //For future... public static final String UPDATE = "1#"; //For future... public static final String DELETE = "2#"; public static final String UPSERT = "3#"; @SuppressWarnings("serial") private static final Map<Integer, String> MYSQL_MAPPING = Collections.unmodifiableMap(new HashMap<Integer, String>() {{ put(Types.BOOLEAN, "tinyint"); put(Types.TINYINT, "tinyint"); put(Types.SMALLINT, "smallint"); put(Types.INTEGER, "int"); put(Types.BIGINT, "bigint"); put(Types.FLOAT, "float"); put(Types.DOUBLE, "double"); put(Types.DECIMAL, "decimal"); put(Types.NUMERIC, "decimal(38,9)"); put(Types.DATE, "datetime"); put(Types.TIMESTAMP, "timestamp"); put(Types.TIMESTAMP_WITH_TIMEZONE, "varchar(127)"); put(Types.VARCHAR, "varchar(255)"); put(Types.BINARY, "varbinary(1000)"); put(Types.BLOB, "longblob"); put(Types.CLOB, "longtext"); put(Types.NCLOB, "longtext"); }}); @SuppressWarnings("serial") private static final Map<Integer, String> POSTGRESQL_MAPPING = Collections.unmodifiableMap(new HashMap<Integer, String>() {{ put(Types.BOOLEAN, "boolean"); put(Types.TINYINT, "smallint"); put(Types.SMALLINT, "smallint"); put(Types.INTEGER, "integer"); put(Types.BIGINT, "bigint"); put(Types.FLOAT, "real"); put(Types.DOUBLE, "double precision"); put(Types.DECIMAL, "numeric"); put(Types.NUMERIC, "numeric"); put(Types.DATE, "timestamp"); put(Types.TIMESTAMP, "timestamp"); put(Types.TIMESTAMP_WITH_TIMEZONE, "timestamp with time zone"); put(Types.VARCHAR, "text"); put(Types.BINARY, "bytea"); // https://www.postgresql.org/docs/current/lo.html put(Types.BLOB, "lo"); put(Types.CLOB, "text"); put(Types.NCLOB, "text"); }}); @SuppressWarnings("serial") private static final Map<Integer, String> ORACLE_MAPPING = Collections.unmodifiableMap(new HashMap<Integer, String>() {{ put(Types.BOOLEAN, "CHAR(1)"); put(Types.TINYINT, "NUMBER(3)"); put(Types.SMALLINT, "NUMBER(5)"); put(Types.INTEGER, "NUMBER(10)"); put(Types.BIGINT, "NUMBER(19)"); put(Types.FLOAT, "BINARY_FLOAT"); put(Types.DOUBLE, "BINARY_DOUBLE"); put(Types.DECIMAL, "NUMBER"); put(Types.NUMERIC, "NUMBER"); put(Types.DATE, "DATE"); put(Types.TIMESTAMP, "TIMESTAMP"); put(Types.TIMESTAMP_WITH_TIMEZONE, "TIMESTAMP(9) WITH TIME ZONE"); put(Types.VARCHAR, "VARCHAR2(4000)"); put(Types.BINARY, "RAW(2000)"); put(Types.BLOB, "BLOB"); put(Types.CLOB, "CLOB"); put(Types.NCLOB, "NCLOB"); }}); /** * * @param tableName * @param dbType * @param pkColumns * @param allColumns * @return List with at least one element for PostgreSQL and exactly one element for others RDBMS * Element at index 0 is always CREATE TABLE, at other indexes (PostgreSQL only) SQL text * script for creation of lo trigger (Ref.: https://www.postgresql.org/docs/current/lo.html) */ public static List<String> createTableSql( final String tableName, final int dbType, final Map<String, OraColumn> pkColumns, final List<OraColumn> allColumns, final Map<String, OraColumn> lobColumns) { final List<String> sqlStrings = new ArrayList<>(); final StringBuilder sbCreateTable = new StringBuilder(256); final StringBuilder sbPrimaryKey = new StringBuilder(64); final Map<Integer, String> dataTypesMap; if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_POSTGRESQL) { dataTypesMap = POSTGRESQL_MAPPING; } else if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_ORACLE) { dataTypesMap = ORACLE_MAPPING; } else { //TODO - more types required dataTypesMap = MYSQL_MAPPING; } sbCreateTable.append("create table "); sbCreateTable.append(tableName); sbCreateTable.append("(\n"); sbPrimaryKey.append(",\n constraint "); sbPrimaryKey.append(tableName); sbPrimaryKey.append("_PK primary key("); Iterator<Entry<String, OraColumn>> pkIterator = pkColumns.entrySet().iterator(); while (pkIterator.hasNext()) { OraColumn column = pkIterator.next().getValue(); sbCreateTable.append(" "); sbCreateTable.append(getTargetDbColumn(dbType, dataTypesMap, column)); sbCreateTable.append(" not null"); sbPrimaryKey.append(column.getColumnName()); if (pkIterator.hasNext()) { sbCreateTable.append(",\n"); sbPrimaryKey.append(","); } } sbPrimaryKey.append(")"); final int nonPkColumnCount = allColumns.size(); for (int i = 0; i < nonPkColumnCount; i++) { OraColumn column = allColumns.get(i); sbCreateTable.append(",\n "); sbCreateTable.append(getTargetDbColumn(dbType, dataTypesMap, column)); if (!column.isNullable()) { sbCreateTable.append(" not null"); } } if (lobColumns != null && lobColumns.size() > 0) { sbCreateTable.append(",\n"); Iterator<Entry<String, OraColumn>> lobIterator = lobColumns.entrySet().iterator(); while (lobIterator.hasNext()) { OraColumn column = lobIterator.next().getValue(); sbCreateTable.append(" "); sbCreateTable.append(getTargetDbColumn(dbType, dataTypesMap, column)); if (lobIterator.hasNext()) { sbCreateTable.append(",\n"); } if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_POSTGRESQL && column.getJdbcType() == Types.BLOB) { final StringBuilder sbPostgresLoTriggers = new StringBuilder(128); sbPostgresLoTriggers.append("CREATE TRIGGER t_lo_"); sbPostgresLoTriggers.append(tableName); sbPostgresLoTriggers.append("_"); sbPostgresLoTriggers.append(column.getColumnName()); sbPostgresLoTriggers.append(" BEFORE UPDATE OR DELETE ON "); sbPostgresLoTriggers.append(tableName); sbPostgresLoTriggers.append("\n\tFOR EACH ROW EXECUTE FUNCTION lo_manage("); sbPostgresLoTriggers.append(column.getColumnName()); sbPostgresLoTriggers.append(")\n"); sqlStrings.add(sbPostgresLoTriggers.toString()); } } } sbCreateTable.append(sbPrimaryKey); sbCreateTable.append("\n)"); sqlStrings.add(0, sbCreateTable.toString()); return sqlStrings; } private static String getTargetDbColumn(final int dbType, final Map<Integer, String> dataTypesMap, final OraColumn column) { final StringBuilder sb = new StringBuilder(64); sb.append(column.getColumnName()); sb.append(" "); if (column.getJdbcType() != Types.DECIMAL) sb.append(dataTypesMap.get(column.getJdbcType())); else { if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_POSTGRESQL || dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_ORACLE) { sb.append(dataTypesMap.get(column.getJdbcType())); } else if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_MYSQL) { sb.append(dataTypesMap.get(column.getJdbcType())); sb.append("(38,"); sb.append(column.getDataScale()); sb.append(")"); } } return sb.toString(); } public static Map<String, String> generateSinkSql(final String tableName, final int dbType, final Map<String, OraColumn> pkColumns, final List<OraColumn> allColumns, final Map<String, OraColumn> lobColumns) { final int pkColCount = pkColumns.size(); final boolean onlyPkColumns = allColumns.size() == 0; final StringBuilder sbDelUpdWhere = new StringBuilder(128); sbDelUpdWhere.append(" where "); final StringBuilder sbInsSql = new StringBuilder(512); final StringBuilder sbOraMergeOnList = new StringBuilder(64); final StringBuilder sbOraInsertList = new StringBuilder(256); final StringBuilder sbOraValuesList = new StringBuilder(256); if (dbType != OraCdcJdbcSinkConnectionPool.DB_TYPE_ORACLE) { sbInsSql.append("insert into "); sbInsSql.append(tableName); sbInsSql.append("("); } final StringBuilder sbUpsert = new StringBuilder(128); if (!onlyPkColumns) { if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_POSTGRESQL) { sbUpsert.append(" on conflict("); } else if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_MYSQL) { sbUpsert.append(" on duplicate key update "); } else if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_ORACLE) { sbInsSql.append("merge into "); sbInsSql.append(tableName); sbInsSql.append(" D using\n(select "); } } Iterator<Entry<String, OraColumn>> iterator = pkColumns.entrySet().iterator(); int pkColumnNo = 0; while (iterator.hasNext()) { final String columnName = iterator.next().getValue().getColumnName(); if (pkColumnNo > 0) { sbDelUpdWhere.append(" and "); } sbDelUpdWhere.append(columnName); sbDelUpdWhere.append("=?"); if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_ORACLE) { if (!onlyPkColumns) { sbInsSql.append("? "); } sbOraMergeOnList.append("D."); sbOraMergeOnList.append(columnName); sbOraMergeOnList.append("="); sbOraMergeOnList.append("ORACDC."); sbOraMergeOnList.append(columnName); sbOraInsertList.append(columnName); if (!onlyPkColumns) { sbOraValuesList.append("ORACDC."); sbOraValuesList.append(columnName); } else { sbOraValuesList.append("?"); } } if (!onlyPkColumns || dbType != OraCdcJdbcSinkConnectionPool.DB_TYPE_ORACLE) { sbInsSql.append(columnName); } if (pkColumnNo < pkColCount - 1) { if (!onlyPkColumns || dbType != OraCdcJdbcSinkConnectionPool.DB_TYPE_ORACLE) { sbInsSql.append(","); } if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_ORACLE) { sbOraMergeOnList.append(" and "); sbOraInsertList.append(","); sbOraValuesList.append(","); } } if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_POSTGRESQL) { if (!onlyPkColumns) { sbUpsert.append(columnName); if (pkColumnNo < pkColCount - 1) { sbUpsert.append(","); } } } pkColumnNo++; } if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_POSTGRESQL) { if (!onlyPkColumns) { sbUpsert.append(") do update set "); } } else if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_ORACLE) { if (!onlyPkColumns) { sbOraInsertList.append(","); sbOraValuesList.append(","); } } final StringBuilder sbUpdSql = new StringBuilder(256); sbUpdSql.append("update "); sbUpdSql.append(tableName); sbUpdSql.append(" set "); final int nonPkColumnCount = allColumns.size(); for (int i = 0; i < nonPkColumnCount; i++) { sbInsSql.append(","); if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_ORACLE) { sbInsSql.append("? "); } sbInsSql.append(allColumns.get(i).getColumnName()); sbUpdSql.append(allColumns.get(i).getColumnName()); if (i < nonPkColumnCount - 1) { sbUpdSql.append("=?,"); } else { sbUpdSql.append("=?"); } if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_POSTGRESQL) { sbUpsert.append(allColumns.get(i).getColumnName()); sbUpsert.append("=EXCLUDED."); sbUpsert.append(allColumns.get(i).getColumnName()); if (i < nonPkColumnCount - 1) { sbUpsert.append(","); } } else if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_MYSQL) { sbUpsert.append(allColumns.get(i).getColumnName()); sbUpsert.append("=VALUES("); sbUpsert.append(allColumns.get(i).getColumnName()); sbUpsert.append(")"); if (i < nonPkColumnCount - 1) { sbUpsert.append(","); } } else if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_ORACLE) { sbUpsert.append("D."); sbUpsert.append(allColumns.get(i).getColumnName()); sbUpsert.append("="); sbUpsert.append("ORACDC."); sbUpsert.append(allColumns.get(i).getColumnName()); sbOraInsertList.append(allColumns.get(i).getColumnName()); sbOraValuesList.append("ORACDC."); sbOraValuesList.append(allColumns.get(i).getColumnName()); if (i < nonPkColumnCount - 1) { sbUpsert.append(","); sbOraInsertList.append(","); sbOraValuesList.append(","); } } } if (dbType == OraCdcJdbcSinkConnectionPool.DB_TYPE_ORACLE) { if (!onlyPkColumns) { sbInsSql.append(" from DUAL) ORACDC\non ("); sbInsSql.append(sbOraMergeOnList); sbInsSql.append(")"); sbInsSql.append("\nwhen matched then update\nset "); sbInsSql.append(sbUpsert); sbInsSql.append("\nwhen not matched then\ninsert("); sbInsSql.append(sbOraInsertList); sbInsSql.append(")"); sbInsSql.append("\nvalues("); sbInsSql.append(sbOraValuesList); sbInsSql.append(")"); } else { sbInsSql.append("insert into "); sbInsSql.append(tableName); sbInsSql.append("("); sbInsSql.append(sbOraInsertList); sbInsSql.append(")"); sbInsSql.append("\nvalues("); sbInsSql.append(sbOraValuesList); sbInsSql.append(")"); } } else { sbInsSql.append(") values("); final int totalColumns = nonPkColumnCount + pkColCount; for (int i = 0; i < totalColumns; i++) { if (i < totalColumns - 1) { sbInsSql.append("?,"); } else { sbInsSql.append("?)"); } } sbInsSql.append(sbUpsert); } final StringBuilder sbDelSql = new StringBuilder(128); sbDelSql.append("delete from "); sbDelSql.append(tableName); sbDelSql.append(sbDelUpdWhere); sbUpdSql.append(sbDelUpdWhere); final Map<String, String> generatedSql = new HashMap<>(); generatedSql.put(UPSERT, sbInsSql.toString()); generatedSql.put(UPDATE, sbUpdSql.toString()); generatedSql.put(DELETE, sbDelSql.toString()); if (lobColumns != null && lobColumns.size() > 0) { lobColumns.forEach((columnName, v) -> { final StringBuilder sbLobUpdate = new StringBuilder(64); sbLobUpdate.append("update "); sbLobUpdate.append(tableName); sbLobUpdate.append(" set "); sbLobUpdate.append(columnName); sbLobUpdate.append("=?"); sbLobUpdate.append(sbDelUpdWhere); generatedSql.put(columnName, sbLobUpdate.toString()); }); } return generatedSql; } }
package me.mvp.demo.app.config; import android.content.Context; import com.google.gson.Gson; import javax.inject.Inject; import me.logg.Logg; import me.mvp.demo.app.utils.tool.GsonConverterBodyFactory; import me.mvp.demo.app.utils.tool.JsonConverterFactory; import me.mvp.frame.di.module.HttpModule; import retrofit2.Retrofit; /** * 扩展自定义配置 Retrofit 参数 */ public class RetrofitConfig implements HttpModule.RetrofitConfiguration { @Override public void configRetrofit(Context context, Retrofit.Builder builder) { builder .addConverterFactory(JsonConverterFactory.create())// 支持 Json ; } }