text
stringlengths
7
1.01M
package de.metas.inoutcandidate.api; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import de.metas.inoutcandidate.ShipmentScheduleId; import de.metas.quantity.Quantity; import de.metas.util.ISingletonService; /** * Packaging related DAO * * @author ts * @author tsa * * @see <a href="http://dewiki908/mediawiki/index.php/Transportverpackung_%282009_0022_G61%29">(2009_0022_G61)</a> */ public interface IPackagingDAO extends ISingletonService { Stream<Packageable> stream(PackageableQuery query); /** * @return The current QtyPickedPlanned (qty that was picked but not yet processed) for the given schedule if found */ Optional<Quantity> retrieveQtyPickedPlanned(ShipmentScheduleId shipmentScheduleId); Packageable getByShipmentScheduleId(ShipmentScheduleId shipmentScheduleId); List<Packageable> getByShipmentScheduleIds(Collection<ShipmentScheduleId> shipmentScheduleIds); }
package us.fjj.spring.learning.aspectj5notifytype.aftertest; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; @Aspect public class AfterAspect { @Pointcut("execution(* us.fjj.spring.learning.aspectj5notifytype.aftertest.Service3.*(..))") public void pc1(){} @After("pc1()") public void after(JoinPoint joinPoint) { System.out.println(joinPoint.getSignature().getName()+"执行完毕!"); } }
package cn.hutool.core.lang; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.StrUtil; /** * {@link ParameterizedType} 接口实现,用于重新定义泛型类型 * * @author looly * @since 4.5.7 */ public class ParameterizedTypeImpl implements ParameterizedType, Serializable { private static final long serialVersionUID = 1L; private final Type[] actualTypeArguments; private final Type ownerType; private final Type rawType; /** * 构造 * * @param actualTypeArguments 实际的泛型参数类型 * @param ownerType 拥有者类型 * @param rawType 原始类型 */ public ParameterizedTypeImpl(Type[] actualTypeArguments, Type ownerType, Type rawType) { this.actualTypeArguments = actualTypeArguments; this.ownerType = ownerType; this.rawType = rawType; } @Override public Type[] getActualTypeArguments() { return actualTypeArguments; } @Override public Type getOwnerType() { return ownerType; } @Override public Type getRawType() { return rawType; } @Override public String toString() { final StringBuilder buf = new StringBuilder(); final Type useOwner = this.ownerType; final Class<?> raw = (Class<?>) this.rawType; if (useOwner == null) { buf.append(raw.getName()); } else { if (useOwner instanceof Class<?>) { buf.append(((Class<?>) useOwner).getName()); } else { buf.append(useOwner.toString()); } buf.append('.').append(raw.getSimpleName()); } appendAllTo(buf.append('<'), ", ", this.actualTypeArguments).append('>'); return buf.toString(); } /** * 追加 {@code types} 到 @{code buf},使用 {@code sep} 分隔 * * @param buf 目标 * @param sep 分隔符 * @param types 加入的类型 * @return {@code buf} */ private static StringBuilder appendAllTo(final StringBuilder buf, final String sep, final Type... types) { if (ArrayUtil.isNotEmpty(types)) { boolean isFirst = true; for (Type type : types) { if (isFirst) { isFirst = false; } else { buf.append(sep); } String typeStr; if(type instanceof Class) { typeStr = ((Class<?>)type).getName(); }else { typeStr = StrUtil.toString(type); } buf.append(typeStr); } } return buf; } }
/* * Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. */ package de.hybris.platform.commerceorgaddon.controllers.pages; import de.hybris.platform.acceleratorstorefrontcommons.annotations.RequireHardLogIn; import de.hybris.platform.acceleratorstorefrontcommons.breadcrumb.Breadcrumb; import de.hybris.platform.acceleratorstorefrontcommons.controllers.ThirdPartyConstants; import de.hybris.platform.acceleratorstorefrontcommons.controllers.pages.AbstractSearchPageController; import de.hybris.platform.acceleratorstorefrontcommons.controllers.util.GlobalMessages; import de.hybris.platform.b2b.enums.B2BPermissionTypeEnum; import de.hybris.platform.b2b.model.B2BPermissionModel; import de.hybris.platform.b2bapprovalprocessfacades.company.data.B2BPermissionData; import de.hybris.platform.b2bapprovalprocessfacades.company.data.B2BPermissionTypeData; import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException; import de.hybris.platform.cms2.model.pages.ContentPageModel; import de.hybris.platform.commerceorgaddon.controllers.ControllerConstants; import de.hybris.platform.commerceorgaddon.forms.B2BPermissionForm; import de.hybris.platform.commerceorgaddon.forms.B2BPermissionTypeSelectionForm; import de.hybris.platform.commerceservices.search.pagedata.PageableData; import de.hybris.platform.commerceservices.search.pagedata.SearchPageData; import de.hybris.platform.commerceservices.util.ResponsiveUtils; import de.hybris.platform.servicelayer.interceptor.InterceptorException; import de.hybris.platform.servicelayer.interceptor.impl.UniqueAttributesInterceptor; import java.text.ParseException; import java.util.List; import javax.validation.Valid; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; /** * Controller defines routes to manage Permissions and B2B User groups within My Company section. */ @Controller @RequestMapping("/my-company/organization-management/manage-permissions") public class PermissionManagementPageController extends MyCompanyPageController { private static final Logger LOG = Logger.getLogger(PermissionManagementPageController.class); @RequestMapping(method = RequestMethod.GET) @RequireHardLogIn public String managePermissions(@RequestParam(value = "page", defaultValue = "0") final int page, @RequestParam(value = "show", defaultValue = "Page") final AbstractSearchPageController.ShowMode showMode, @RequestParam(value = "sort", defaultValue = B2BPermissionModel.CODE) final String sortCode, final Model model) throws CMSItemNotFoundException { final ContentPageModel myCompanyPage = getContentPageForLabelOrId(MY_COMPANY_CMS_PAGE); storeCmsPageInModel(model, myCompanyPage); setUpMetaDataForContentPage(model, myCompanyPage); final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManagePermissionsBreadcrumb(); model.addAttribute("breadcrumbs", breadcrumbs); // Handle paged search results final PageableData pageableData = createPageableData(page, getSearchPageSize(), sortCode, showMode); final SearchPageData<B2BPermissionData> searchPageData = b2bPermissionFacade.getPagedPermissions(pageableData); populateModel(model, searchPageData, showMode); model.addAttribute("action", "managePermissions"); model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS, ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW); return ControllerConstants.Views.Pages.MyCompany.MyCompanyManagePermissionsPage; } @RequestMapping(value = "/view", method = RequestMethod.GET) @RequireHardLogIn public String viewPermissionDetails(@RequestParam("permissionCode") final String permissionCode, final Model model) throws CMSItemNotFoundException { model.addAttribute("permissionData", b2bPermissionFacade.getPermissionDetails(permissionCode)); final ContentPageModel myCompanyPage = getContentPageForLabelOrId(MY_COMPANY_CMS_PAGE); storeCmsPageInModel(model, myCompanyPage); setUpMetaDataForContentPage(model, myCompanyPage); final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManagePermissionsBreadcrumb(); model.addAttribute("breadcrumbs", breadcrumbs); myCompanyBreadcrumbBuilder.addViewPermissionBreadCrumbs(breadcrumbs, permissionCode); model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS, ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW); return ControllerConstants.Views.Pages.MyCompany.MyCompanyManagePermissionsViewPage; } @Override @RequestMapping(value = "/edit", method = RequestMethod.GET) @RequireHardLogIn public String editPermission(@RequestParam("permissionCode") final String permissionCode, final Model model) throws CMSItemNotFoundException { return super.editPermission(permissionCode, model); } @Override @RequestMapping(value = "/edit", method = RequestMethod.POST) @RequireHardLogIn public String editPermission(@Valid final B2BPermissionForm b2BPermissionForm, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectModel) throws CMSItemNotFoundException, ParseException { return super.editPermission(b2BPermissionForm, bindingResult, model, redirectModel); } @RequestMapping(value = "/add", method = RequestMethod.GET) @RequireHardLogIn public String getSelectPermissionTypePage(final Model model) throws CMSItemNotFoundException { if (!model.containsAttribute("b2BPermissionTypeSelectionForm")) { model.addAttribute(new B2BPermissionTypeSelectionForm()); } final ContentPageModel organizationManagementPage = getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE); storeCmsPageInModel(model, organizationManagementPage); setUpMetaDataForContentPage(model, organizationManagementPage); final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManagePermissionsBreadcrumb(); if (ResponsiveUtils.isResponsive()) { breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-permissions/add", getMessageSource() .getMessage("text.company.managePermissions.create.new.permission", null, getI18nService().getCurrentLocale()), null)); } else { breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-permissions/add", getMessageSource() .getMessage("text.company.managePermissions.create.step1.page", null, getI18nService().getCurrentLocale()), null)); } model.addAttribute("breadcrumbs", breadcrumbs); model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS, ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW); return ControllerConstants.Views.Pages.MyCompany.MyCompanyManagePermissionTypeSelectPage; } @RequestMapping(value = "/getNewPermissionForm", method = RequestMethod.GET) @RequireHardLogIn public String addNewPermissionForm(@RequestParam("permissionType") final String permissionType, final Model model) throws CMSItemNotFoundException { if (!StringUtils.isEmpty(permissionType)) { final B2BPermissionForm b2BPermissionForm = new B2BPermissionForm(); final B2BPermissionTypeEnum permissionTypeEnum = B2BPermissionTypeEnum.valueOf(permissionType); final B2BPermissionTypeData b2BPermissionTypeData = b2bPermissionFacade .getB2BPermissionTypeDataForPermission(permissionTypeEnum); b2BPermissionForm.setB2BPermissionTypeData(b2BPermissionTypeData); b2BPermissionForm.setParentUnitName(b2bUnitFacade.getParentUnit().getUid()); b2BPermissionForm.setPermissionType(b2BPermissionTypeData.getCode()); model.addAttribute(b2BPermissionForm); } return ControllerConstants.Views.Pages.MyCompany.MyCompanyManagePermissionAddPage; } @RequestMapping(value = "/add", method = RequestMethod.POST) @RequireHardLogIn public String addNewPermission(@Valid final B2BPermissionTypeSelectionForm b2BPermissionTypeSelectionForm, final BindingResult bindingResult, final Model model) throws CMSItemNotFoundException { if (bindingResult.hasErrors()) { model.addAttribute(b2BPermissionTypeSelectionForm); GlobalMessages.addErrorMessage(model, "form.global.error"); return getSelectPermissionTypePage(model); } if (!model.containsAttribute("b2BPermissionForm")) { final B2BPermissionForm b2BPermissionForm = new B2BPermissionForm(); final B2BPermissionTypeEnum permissionTypeEnum = B2BPermissionTypeEnum.valueOf(b2BPermissionTypeSelectionForm .getB2BPermissionType()); final B2BPermissionTypeData b2BPermissionTypeData = b2bPermissionFacade .getB2BPermissionTypeDataForPermission(permissionTypeEnum); b2BPermissionForm.setB2BPermissionTypeData(b2BPermissionTypeData); b2BPermissionForm.setParentUnitName(b2bUnitFacade.getParentUnit().getUid()); b2BPermissionForm.setPermissionType(b2BPermissionTypeData.getName()); model.addAttribute(b2BPermissionForm); } return getAddPermissionPage(model); } @RequestMapping(value = "/addPermission", method = RequestMethod.GET) @RequireHardLogIn public String getAddPermissionPage(final Model model) throws CMSItemNotFoundException { final ContentPageModel organizationManagementPage = getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE); storeCmsPageInModel(model, organizationManagementPage); setUpMetaDataForContentPage(model, organizationManagementPage); final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManagePermissionsBreadcrumb(); breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-permissions/add", getMessageSource().getMessage( "text.company.managePermissions.create.step1.page", null, getI18nService().getCurrentLocale()), null)); breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-permissions/addPermission", getMessageSource() .getMessage("text.company.managePermissions.create.step2.page", null, getI18nService().getCurrentLocale()), null)); model.addAttribute("breadcrumbs", breadcrumbs); model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS, ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW); return ControllerConstants.Views.Pages.MyCompany.MyCompanyManagePermissionAddPage; } @RequestMapping(value = "/addPermissionResponsive", method = RequestMethod.GET) @RequireHardLogIn public String getAddErrorPermissionPage(final Model model) throws CMSItemNotFoundException { final ContentPageModel organizationManagementPage = getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE); storeCmsPageInModel(model, organizationManagementPage); setUpMetaDataForContentPage(model, organizationManagementPage); final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManagePermissionsBreadcrumb(); breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-permissions/add", getMessageSource().getMessage( "text.company.managePermissions.create.new.permission", null, getI18nService().getCurrentLocale()), null)); model.addAttribute("breadcrumbs", breadcrumbs); model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS, ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW); return ControllerConstants.Views.Pages.MyCompany.MyCompanyManagePermissionAddErrorPage; } @RequestMapping(value = "/add/save", method = RequestMethod.POST) @RequireHardLogIn public String saveNewPermissionDetails(@Valid final B2BPermissionForm b2BPermissionForm, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectModel) throws CMSItemNotFoundException, ParseException { b2BPermissionFormValidator.validate(b2BPermissionForm, bindingResult); if (bindingResult.hasErrors()) { model.addAttribute(b2BPermissionForm); GlobalMessages.addErrorMessage(model, "form.global.error"); return (ResponsiveUtils.isResponsive()) ? getAddErrorPermissionPage(model) : getAddPermissionPage(model); } final B2BPermissionData b2BPermissionData = populateB2BPermissionDataFromForm(b2BPermissionForm); try { b2bPermissionFacade.addPermission(b2BPermissionData); } catch (final Exception e) { LOG.warn("Exception while saving the permission details " + e); if (e.getCause() instanceof InterceptorException && ((InterceptorException) e.getCause()).getInterceptor().getClass().equals(UniqueAttributesInterceptor.class)) { model.addAttribute(b2BPermissionForm); bindingResult.rejectValue("code", "text.company.managePermissions.code.exists.error.title"); GlobalMessages.addErrorMessage(model, "form.global.error"); return (ResponsiveUtils.isResponsive()) ? getAddErrorPermissionPage(model) : getAddPermissionPage(model); } } final ContentPageModel organizationManagementPage = getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE); storeCmsPageInModel(model, organizationManagementPage); setUpMetaDataForContentPage(model, organizationManagementPage); final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManagePermissionsBreadcrumb(); model.addAttribute("breadcrumbs", breadcrumbs); GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER, "text.confirmation.permission.created"); return String.format(REDIRECT_TO_PERMISSION_DETAILS, urlEncode(b2BPermissionData.getCode())); } @RequestMapping(value = "/enable", method = RequestMethod.GET) @RequireHardLogIn public String enablePermission(@RequestParam("permissionCode") final String permissionCode, final Model model) throws CMSItemNotFoundException { try { b2bPermissionFacade.enableDisablePermission(permissionCode, true); } catch (final Exception e) { LOG.error(e.getMessage(), e); GlobalMessages.addErrorMessage(model, "form.global.error"); return viewPermissionDetails(permissionCode, model); } return String.format(REDIRECT_TO_PERMISSION_DETAILS, urlEncode(permissionCode)); } @RequestMapping(value = "/disable", method = RequestMethod.GET) @RequireHardLogIn public String confirmDisablePermission(@RequestParam("permissionCode") final String permissionCode, final Model model) throws CMSItemNotFoundException { final ContentPageModel organizationManagementPage = getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE); storeCmsPageInModel(model, organizationManagementPage); setUpMetaDataForContentPage(model, organizationManagementPage); final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManagePermissionsBreadcrumb(); breadcrumbs.add(new Breadcrumb(String.format("/my-company/organization-management/manage-permissions/%s/disable", urlEncode(permissionCode)), getMessageSource().getMessage("text.company.managePermissions.disable.breadcrumb", new Object[] { permissionCode }, "Disable {0} ", getI18nService().getCurrentLocale()), null)); model.addAttribute("breadcrumbs", breadcrumbs); model.addAttribute("permissionCode", permissionCode); model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS, ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW); return ControllerConstants.Views.Pages.MyCompany.MyCompanyManagePermissionDisablePage; } @RequestMapping(value = "/disable", method = RequestMethod.POST) @RequireHardLogIn public String disablePermission(@RequestParam("permissionCode") final String permissionCode, final Model model) throws CMSItemNotFoundException { try { b2bPermissionFacade.enableDisablePermission(permissionCode, false); } catch (final Exception e) { LOG.error("Failed to disable permission: " + permissionCode, e); GlobalMessages.addErrorMessage(model, "form.global.error"); return viewPermissionDetails(permissionCode, model); } return String.format(REDIRECT_TO_PERMISSION_DETAILS, urlEncode(permissionCode)); } }
package org.arend.naming; import org.arend.core.context.binding.Binding; import org.arend.frontend.ConcreteReferableProvider; import org.arend.frontend.reference.ConcreteLocatedReferable; import org.arend.naming.reference.Referable; import org.arend.naming.resolving.visitor.DefinitionResolveNameVisitor; import org.arend.naming.resolving.visitor.ExpressionResolveNameVisitor; import org.arend.naming.scope.*; import org.arend.prelude.PreludeLibrary; import org.arend.term.concrete.Concrete; import org.arend.term.group.ChildGroup; import org.arend.typechecking.TestLocalErrorReporter; import org.arend.typechecking.visitor.SyntacticDesugarVisitor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; public abstract class NameResolverTestCase extends ParserTestCase { private Concrete.Expression resolveNamesExpr(Scope parentScope, List<Referable> context, String text, int errors) { Concrete.Expression expression = parseExpr(text); assertThat(expression, is(notNullValue())); expression = expression .accept(new ExpressionResolveNameVisitor(ConcreteReferableProvider.INSTANCE, parentScope, context, new TestLocalErrorReporter(errorReporter), null), null) .accept(new SyntacticDesugarVisitor(errorReporter), null); assertThat(errorList, containsErrors(errors)); return expression; } protected Concrete.Expression resolveNamesExpr(Scope parentScope, String text, int errors) { return resolveNamesExpr(parentScope, new ArrayList<>(), text, errors); } protected Concrete.Expression resolveNamesExpr(String text, @SuppressWarnings("SameParameterValue") int errors) { return resolveNamesExpr(PreludeLibrary.getPreludeScope(), new ArrayList<>(), text, errors); } protected Concrete.Expression resolveNamesExpr(Scope parentScope, @SuppressWarnings("SameParameterValue") String text) { return resolveNamesExpr(parentScope, text, 0); } protected Concrete.Expression resolveNamesExpr(Map<Referable, Binding> context, String text) { List<Referable> names = new ArrayList<>(context.keySet()); return resolveNamesExpr(PreludeLibrary.getPreludeScope(), names, text, 0); } protected Concrete.Expression resolveNamesExpr(String text) { return resolveNamesExpr(new HashMap<>(), text); } ChildGroup resolveNamesDefGroup(String text, int errors) { ChildGroup group = parseDef(text); Scope parentScope = new MergeScope(new SingletonScope(group.getReferable()), PreludeLibrary.getPreludeScope()); new DefinitionResolveNameVisitor(ConcreteReferableProvider.INSTANCE, errorReporter).resolveGroupWithTypes(group, null, CachingScope.make(LexicalScope.insideOf(group, parentScope))); assertThat(errorList, containsErrors(errors)); return group; } protected ChildGroup resolveNamesDefGroup(String text) { return resolveNamesDefGroup(text, 0); } protected ConcreteLocatedReferable resolveNamesDef(String text, int errors) { return (ConcreteLocatedReferable) resolveNamesDefGroup(text, errors).getReferable(); } protected ConcreteLocatedReferable resolveNamesDef(String text) { return resolveNamesDef(text, 0); } private void resolveNamesModule(ChildGroup group, int errors) { Scope scope = CachingScope.make(ScopeFactory.forGroup(group, moduleScopeProvider)); new DefinitionResolveNameVisitor(ConcreteReferableProvider.INSTANCE, errorReporter).resolveGroupWithTypes(group, null, scope); libraryManager.getInstanceProviderSet().collectInstances(group, CachingScope.make(ScopeFactory.parentScopeForGroup(group, moduleScopeProvider, true)), ConcreteReferableProvider.INSTANCE, null); assertThat(errorList, containsErrors(errors)); } protected ChildGroup resolveNamesModule(String text, int errors) { ChildGroup group = parseModule(text); resolveNamesModule(group, errors); return group; } protected ChildGroup resolveNamesModule(String text) { return resolveNamesModule(text, 0); } }
/** * Copyright (c) 2015, Benny Bobaganoosh. All rights reserved. * License terms are in the included LICENSE.txt file. */ package engine.rendering; import static org.lwjgl.opengl.GL11.*; /** * Interface for some piece of hardware, physical or virtual, that is capable of * graphics rendering. * * @author Benny Bobaganoosh (thebennybox@gmail.com) */ public interface IRenderDevice { /** * Specifies a way of blending graphics. */ public static enum BlendMode { SPRITE, ADD_LIGHT, APPLY_LIGHT } /** Filter images using color from the pixel nearest to desired point. */ public static final int FILTER_NEAREST = GL_NEAREST; /** * Filter images by sampling color from several pixels near the given point * and linearly interpolating to more accurately determine color at a given * point */ public static final int FILTER_LINEAR = GL_LINEAR; /** * Cleans up released resources, but keeps the object usable. dispose should * be used for final resource cleanup and release. */ public void cleanupResources(); /** * Releases any resources being used. This object should not be used after * this is called. */ public void dispose(); /** * Creates a texture that can be used by the device. It is preferred to use * this through the {@link Texture} class when possible. * * @param width * The width of the texture, in pixels. * @param height * The height of the texture, in pixels. * @param image * The image being used as a texture. * @param filter * The filter used when sampling the image. Should be one of the * IRenderDevice.FILTER options. * @return An integer identifying the texture on this device. */ public int createTexture(int width, int height, ArrayBitmap image, int filter); /** * Releases and invalidates a texture. The value of {@code id} will be * invalid after this call and may be reused to identify a new texture. Note * that this does nothing when the null id, 0, is given for {@code id}. * <p/> * It is preferred to use this through the {@link Texture} class when * possible. * * @param id * The integer identifying the texture to be released. * @return The null id of 0. */ public int releaseTexture(int id); /** * Gets a texture, in whole or in part, from this device. It is preferred to * use this through the {@link Texture} class when possible. * * @param id * The integer identifying the texture to be gotten. * @param x * The x location to start getting the texture from. * @param y * The y location to start getting the texture from. * @param width * How many pixels should be read on x. * @param height * How many pixels should be read on y. * @return An ArrayBitmap storing the read portion of the texture. */ public ArrayBitmap getTexture(int id, int x, int y, int width, int height); /** * Creates a render target that can be used by this device. It is preferred * to use this through the {@link RenderTarget} class when possible. * * @param width * The width of the render target, in pixels. * @param height * The height of the render target, in pixels. * @param texId * The integer identifying the texture being used for rendering. * @return An integer identifying the render target on this device. */ public int createRenderTarget(int width, int height, int texId); /** * Releases and invalidates a render target. The value of {@code fbo} will * be invalid after this call and may be reused to identify a new render * target. Note that this does nothing when the null id, 0, is given for * {@code fbo}. * <p/> * It is preferred to use this through the {@link RenderTarget} class when * possible. * * @param fbo * The integer identifying the render target to be released. * @return The null id of 0. */ public int releaseRenderTarget(int fbo); /** * Clears a render target to a single color. It is preferred to use this * through the {@link RenderTarget} class when possible. * * @param fbo * The integer identifying the render target. * @param color * The color to clear to. */ public void clear(int fbo, Color color); /** * Produces a rendering effect within a rectangle. It is preferred to use * this through the {@link RenderTarget} class when possible. * * @param fbo * The integer identifying the render target. * @param texId * The integer identifying the texture being used for rendering. * @param mode * The blend mode being used * @param startX * The start location on X, normalized into the range (-1, 1) * @param startY * The start location on Y, normalized into the range (-1, 1) * @param endX * The end location on X, normalized into the range (-1, 1) * @param endY * The end location on Y, normalized into the range (-1, 1) * @param texStartX * The location in the image on X where pixels should begin being * copied, normalized into the range (0, 1) * @param texStartY * The location in the image on Y where pixels should begin being * copied, normalized into the range (0, 1) * @param texEndX * The location in the image on X where pixels should finish * being copied, normalized into the range (0, 1) * @param texEndY * The location in the image on Y where pixels should finish * being copied, normalized into the range (0, 1) * @param c * The color masking everything. * @param transparency * The amount of transparency being used. */ public void drawRect(int fbo, int texId, BlendMode mode, double startX, double startY, double endX, double endY, double texStartX, double texStartY, double texEndX, double texEndY, Color c, double transparency); }
package com.stripe.android.paymentsheet; import java.lang.System; @kotlin.Metadata(mv = {1, 5, 1}, k = 1, d1 = {"\u0000.\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0010\u000e\n\u0000\n\u0002\u0010\t\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010\b\n\u0002\b\u0003\b\u0000\u0018\u0000 \u000f2\u00020\u0001:\u0001\u000fB\u0005\u00a2\u0006\u0002\u0010\u0002J \u0010\u0003\u001a\u00020\u00042\u0006\u0010\u0005\u001a\u00020\u00062\u0006\u0010\u0007\u001a\u00020\b2\b\b\u0002\u0010\t\u001a\u00020\nJ \u0010\u0003\u001a\u00020\u00042\u0006\u0010\u0005\u001a\u00020\u00062\u0006\u0010\u000b\u001a\u00020\u00042\b\b\u0002\u0010\t\u001a\u00020\nJ\u0010\u0010\f\u001a\u00020\r2\u0006\u0010\u000e\u001a\u00020\bH\u0002\u00a8\u0006\u0010"}, d2 = {"Lcom/stripe/android/paymentsheet/CurrencyFormatter;", "", "()V", "format", "", "amount", "", "amountCurrency", "Ljava/util/Currency;", "targetLocale", "Ljava/util/Locale;", "amountCurrencyCode", "getDefaultDecimalDigits", "", "currency", "Companion", "paymentsheet_release"}) public final class CurrencyFormatter { @org.jetbrains.annotations.NotNull() public static final com.stripe.android.paymentsheet.CurrencyFormatter.Companion Companion = null; private static final double MAJOR_UNIT_BASE = 10.0; private static final java.util.Map<java.util.Set<java.lang.String>, java.lang.Integer> SERVER_DECIMAL_DIGITS = null; public CurrencyFormatter() { super(); } @org.jetbrains.annotations.NotNull() public final java.lang.String format(long amount, @org.jetbrains.annotations.NotNull() java.lang.String amountCurrencyCode, @org.jetbrains.annotations.NotNull() java.util.Locale targetLocale) { return null; } @org.jetbrains.annotations.NotNull() public final java.lang.String format(long amount, @org.jetbrains.annotations.NotNull() java.util.Currency amountCurrency, @org.jetbrains.annotations.NotNull() java.util.Locale targetLocale) { return null; } private final int getDefaultDecimalDigits(java.util.Currency currency) { return 0; } @kotlin.Metadata(mv = {1, 5, 1}, k = 1, d1 = {"\u0000$\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0010\u0006\n\u0000\n\u0002\u0010$\n\u0002\u0010\"\n\u0002\u0010\u000e\n\u0002\u0010\b\n\u0000\b\u0080\u0003\u0018\u00002\u00020\u0001B\u0007\b\u0002\u00a2\u0006\u0002\u0010\u0002R\u000e\u0010\u0003\u001a\u00020\u0004X\u0082T\u00a2\u0006\u0002\n\u0000R \u0010\u0005\u001a\u0014\u0012\n\u0012\b\u0012\u0004\u0012\u00020\b0\u0007\u0012\u0004\u0012\u00020\t0\u0006X\u0082\u0004\u00a2\u0006\u0002\n\u0000\u00a8\u0006\n"}, d2 = {"Lcom/stripe/android/paymentsheet/CurrencyFormatter$Companion;", "", "()V", "MAJOR_UNIT_BASE", "", "SERVER_DECIMAL_DIGITS", "", "", "", "", "paymentsheet_release"}) public static final class Companion { private Companion() { super(); } } }
package com.didichuxing.doraemonkit.ui.realtime.widget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Shader; import android.text.TextUtils; import com.didichuxing.doraemonkit.R; import com.didichuxing.doraemonkit.util.UIUtils; /** * @desc: 折线图渲染器 */ public class LineRender { // 顶部预留50sp,防止文字绘制出界 private int mPaddingTop = 50; // 底部预留2dp,防止圆点绘制补全 private int mPaddingBottom; private final int GRAPH_STROKE_WIDTH = 2; private final float SMALL_RADIUS = 10; private final float CIRCLE_STROKE_WIDTH = 2; private Context mContext; private float maxValue;//最高值 private float minValue;//最低值 private String label;//显示值 private float nextValue;//下一个值 private Paint mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint mLabelPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint mGradientPaint = new Paint(); private Paint mPointPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private float viewHeight; private float viewWidth; private float pointX;//所有点的x坐标 private float pointY;//当前点的Y private float pointSize = SMALL_RADIUS;// 圆点大小 private boolean drawRightLine = true;//是否画右边的线 private boolean showLabel; private float labelAlpha; private float startPosition; private float baseLine = 20; private Path mGradientPath = new Path(); public LineRender(Context context) { mContext = context; mPaddingBottom = UIUtils.dp2px(context, 2); } public void setMaxValue(int maxValue) { this.maxValue = maxValue; } public void setMinValue(int minValue) { this.minValue = minValue; } protected void measure(float width, float height) { viewHeight = height - mPaddingBottom - mPaddingTop; viewWidth = width; initPaint(); } private void initPaint() { mGradientPaint.setShader(new LinearGradient(0, 0, viewWidth, viewHeight, mContext.getResources().getColor(R.color.dk_color_3300BFFF), mContext.getResources().getColor(R.color.dk_color_33434352), Shader.TileMode.CLAMP)); mLabelPaint.setTextSize(mContext.getResources().getDimensionPixelSize(R.dimen.dk_font_size_14)); mLabelPaint.setColor(Color.WHITE); mLabelPaint.setTextAlign(Paint.Align.CENTER); mLinePaint.setPathEffect(null); mLinePaint.setStyle(Paint.Style.FILL); mLinePaint.setColor(mContext.getResources().getColor(R.color.dk_color_4c00C9F4)); mLinePaint.setStrokeWidth(GRAPH_STROKE_WIDTH); mLinePaint.setAntiAlias(true); int color = mContext.getResources().getColor(R.color.dk_color_ff00C9F4); mPointPaint.setColor(color); mPointPaint.setStrokeWidth(CIRCLE_STROKE_WIDTH); } public void draw(Canvas canvas) { drawGraph(canvas); drawGradient(canvas); drawPoint(canvas); drawLabel(canvas); } /** * 画数字 * * @param canvas */ private void drawLabel(Canvas canvas) { if (showLabel && !TextUtils.isEmpty(label)) { mLabelPaint.setAlpha((int) (labelAlpha * 0xff)); canvas.drawText(label, startPosition, pointY - baseLine, mLabelPaint); } } public void setNextValue(float nextValue) { if (nextValue > maxValue) { nextValue = (int) maxValue; } if (nextValue < minValue) { nextValue = (int) minValue; } this.nextValue = (1 - nextValue / (maxValue - minValue)) * viewHeight + mPaddingTop; } public void setCurrentValue(int index, float currentValue) { if (currentValue > maxValue) { currentValue = (int) maxValue; } if (currentValue < minValue) { currentValue = (int) minValue; } startPosition = index * viewWidth; pointX = startPosition; pointY = (1 - currentValue / (maxValue - minValue)) * viewHeight + mPaddingTop; } /** * 画折线 * * @param canvas */ private void drawGraph(Canvas canvas) { if (drawRightLine) { float middleY = nextValue; canvas.drawLine(startPosition, pointY, viewWidth + startPosition, middleY, mLinePaint); } } private void drawGradient(Canvas canvas) { if (drawRightLine) { mGradientPath.rewind(); mGradientPath.moveTo(pointX, pointY); mGradientPath.lineTo(pointX, viewHeight + mPaddingTop); mGradientPath.lineTo(pointX + viewWidth, viewHeight + mPaddingTop); mGradientPath.lineTo(pointX + viewWidth, nextValue); canvas.drawPath(mGradientPath, mGradientPaint); } } /** * 画数字下面的小圆圈 * * @param canvas */ private void drawPoint(Canvas canvas) { canvas.drawCircle(pointX, pointY, pointSize, mPointPaint); } public void setDrawRightLine(boolean drawRightLine) { this.drawRightLine = drawRightLine; } public void setPointSize(float pointSize) { if (pointSize != 0) { this.pointSize = pointSize; } } public void setLabel(String label) { this.label = label; } public void setShowLabel(boolean show) { showLabel = show; } public void setLabelAlpha(float alpha) { labelAlpha = alpha; } }
/* * 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.superbiz.connector.adapter; import org.superbiz.connector.api.InboundListener; import javax.resource.ResourceException; import javax.resource.spi.ActivationSpec; import javax.resource.spi.BootstrapContext; import javax.resource.spi.Connector; import javax.resource.spi.ResourceAdapter; import javax.resource.spi.ResourceAdapterInternalException; import javax.resource.spi.endpoint.MessageEndpoint; import javax.resource.spi.endpoint.MessageEndpointFactory; import javax.transaction.xa.XAResource; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Connector(description = "Sample Resource Adapter", displayName = "Sample Resource Adapter", eisType = "Sample Resource Adapter", version = "1.0") public class SampleResourceAdapter implements ResourceAdapter { final Map<SampleActivationSpec, EndpointTarget> targets = new ConcurrentHashMap<SampleActivationSpec, EndpointTarget>(); public void start(BootstrapContext bootstrapContext) throws ResourceAdapterInternalException { } public void stop() { } public void endpointActivation(final MessageEndpointFactory messageEndpointFactory, final ActivationSpec activationSpec) throws ResourceException { final SampleActivationSpec sampleActivationSpec = (SampleActivationSpec) activationSpec; try { final MessageEndpoint messageEndpoint = messageEndpointFactory.createEndpoint(null); final EndpointTarget target = new EndpointTarget(messageEndpoint); targets.put(sampleActivationSpec, target); } catch (Exception e) { e.printStackTrace(); } } public void endpointDeactivation(MessageEndpointFactory messageEndpointFactory, ActivationSpec activationSpec) { final SampleActivationSpec sampleActivationSpec = (SampleActivationSpec) activationSpec; final EndpointTarget endpointTarget = targets.get(sampleActivationSpec); if (endpointTarget == null) { throw new IllegalStateException("No EndpointTarget to undeploy for ActivationSpec " + activationSpec); } endpointTarget.messageEndpoint.release(); } public XAResource[] getXAResources(ActivationSpec[] activationSpecs) throws ResourceException { return new XAResource[0]; } public void sendMessage(final String message) { final Collection<EndpointTarget> endpoints = this.targets.values(); for (final EndpointTarget endpoint : endpoints) { endpoint.invoke(message); } } public static class EndpointTarget { private final MessageEndpoint messageEndpoint; public EndpointTarget(final MessageEndpoint messageEndpoint) { this.messageEndpoint = messageEndpoint; } public void invoke(final String message) { ((InboundListener)this.messageEndpoint).receiveMessage(message); } } }
package com.senior.project.genealogy.response; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class PeopleResponse { @SerializedName("error") @Expose private Message error; @SerializedName("peopleList") @Expose private List<People> peopleList; public PeopleResponse(Message error, List<People> peopleList) { this.error = error; this.peopleList = peopleList; } public Message getError() { return error; } public void setError(Message error) { this.error = error; } public List<People> getPeopleList() { return peopleList; } public void setPeopleList(List<People> peopleList) { this.peopleList = peopleList; } }
/* * MIT License * * Copyright (c) 2022 MASES s.r.l. * * 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. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.windows.automation.provider; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import system.windows.automation.provider.IRawElementProviderSimple; import system.windows.automation.provider.IRawElementProviderSimpleImplementation; import system.windows.automation.provider.ProviderOptions; /** * The base .NET class managing System.Windows.Automation.Provider.IRawElementProviderHwndOverride, UIAutomationProvider, Version=5.0.15.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Automation.Provider.IRawElementProviderHwndOverride" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Automation.Provider.IRawElementProviderHwndOverride</a> */ public class IRawElementProviderHwndOverrideImplementation extends NetObject implements IRawElementProviderHwndOverride { /** * Fully assembly qualified name: UIAutomationProvider, Version=5.0.15.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 */ public static final String assemblyFullName = "UIAutomationProvider, Version=5.0.15.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; /** * Assembly name: UIAutomationProvider */ public static final String assemblyShortName = "UIAutomationProvider"; /** * Qualified class name: System.Windows.Automation.Provider.IRawElementProviderHwndOverride */ public static final String className = "System.Windows.Automation.Provider.IRawElementProviderHwndOverride"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public IRawElementProviderHwndOverrideImplementation(java.lang.Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link IRawElementProviderHwndOverride}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link IRawElementProviderHwndOverride} instance * @throws java.lang.Throwable in case of error during cast operation */ public static IRawElementProviderHwndOverride ToIRawElementProviderHwndOverride(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new IRawElementProviderHwndOverrideImplementation(from.getJCOInstance()); } // Methods section public NetObject GetPatternProvider(int patternId) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPatternProvider = (JCObject)classInstance.Invoke("GetPatternProvider", patternId); return new NetObject(objGetPatternProvider); } catch (JCNativeException jcne) { throw translateException(jcne); } } public NetObject GetPropertyValue(int propertyId) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPropertyValue = (JCObject)classInstance.Invoke("GetPropertyValue", propertyId); return new NetObject(objGetPropertyValue); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Properties section public IRawElementProviderSimple getHostRawElementProvider() throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject val = (JCObject)classInstance.Get("HostRawElementProvider"); return new IRawElementProviderSimpleImplementation(val); } catch (JCNativeException jcne) { throw translateException(jcne); } } public ProviderOptions getProviderOptions() throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject val = (JCObject)classInstance.Get("ProviderOptions"); return new ProviderOptions(val); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Instance Events section }
package com.rohan.java.concurrency.concepts.deadlocks; import java.util.Random; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Created by rohan on 18/03/2017. * * Base */ public class RunnerUsingLocks { private Account acc1 = new Account(); private Account acc2 = new Account(); private Lock lock1 = new ReentrantLock(); private Lock lock2 = new ReentrantLock(); public void firstThread() throws InterruptedException { lock1.lock(); lock2.lock(); try{ Random random = new Random(); for(int i =0; i < 10000; i++){ Account.transfer(acc1, acc2, random.nextInt(100)); } } finally{ lock1.unlock(); lock2.unlock(); } } public void secondThread() throws InterruptedException { lock1.lock(); lock2.lock(); try{ Random random = new Random(); for(int i =0; i < 10000; i++){ Account.transfer(acc2, acc1, random.nextInt(100)); } } finally{ lock1.unlock(); lock2.unlock(); } } public void finished() { System.out.println("Account 1 balance: " + acc1.getBalance()); System.out.println("Account 2 balance: " + acc2.getBalance()); System.out.println("Total balance: " + (acc1.getBalance() + acc2.getBalance())); } }
/* * Copyright (c) 2007-2017 Xplenty, Inc. All Rights Reserved. * * Project and contact information: http://www.cascading.org/ * * This file is part of the Cascading 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 cascading.flow.local.planner; import java.util.Properties; import cascading.flow.FlowDef; import cascading.flow.FlowStep; import cascading.flow.local.LocalFlow; import cascading.flow.local.LocalFlowStep; import cascading.flow.planner.BaseFlowStepFactory; import cascading.flow.planner.FlowPlanner; import cascading.flow.planner.PlannerInfo; import cascading.flow.planner.PlatformInfo; import cascading.flow.planner.graph.ElementGraph; import cascading.flow.planner.process.FlowNodeGraph; import cascading.flow.planner.process.FlowStepFactory; import cascading.tap.Tap; import cascading.util.Version; /** * */ public class LocalPlanner extends FlowPlanner<LocalFlow, Properties> { public static final String PLATFORM_NAME = "local"; public LocalPlanner() { } @Override public Properties getDefaultConfig() { return null; } @Override public PlannerInfo getPlannerInfo( String registryName ) { return new PlannerInfo( getClass().getSimpleName(), PLATFORM_NAME, registryName ); } @Override public PlatformInfo getPlatformInfo() { return new PlatformInfo( "local", "Xplenty, Inc.", Version.getRelease() ); } protected LocalFlow createFlow( FlowDef flowDef ) { return new LocalFlow( getPlatformInfo(), getDefaultProperties(), getDefaultConfig(), flowDef ); } @Override public FlowStepFactory<Properties> getFlowStepFactory() { return new BaseFlowStepFactory<Properties>( getFlowNodeFactory() ) { @Override public FlowStep<Properties> createFlowStep( ElementGraph stepElementGraph, FlowNodeGraph flowNodeGraph ) { return new LocalFlowStep( stepElementGraph, flowNodeGraph ); } }; } @Override protected Tap makeTempTap( String prefix, String name ) { return null; } }
package com.murilo.jumia.controller; import com.murilo.jumia.model.*; import com.murilo.jumia.model.DTO.PaginatedRepresentation; import com.murilo.jumia.model.DTO.PhoneDTO; import com.murilo.jumia.model.DTO.RequestFilter; import com.murilo.jumia.service.PhoneService; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.List; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @WebMvcTest(PhoneController.class) public class PhoneControllerTests { @Autowired private MockMvc mockMvc; @MockBean private PhoneService service; @Test public void getCameroonPhoneTest() throws Exception { List<PhoneDTO> responseData = new ArrayList<>(); CameroonPhone phoneOne = new CameroonPhone(); phoneOne.setPhoneNumber("(237)212345675"); responseData.add(new PhoneDTO(phoneOne)); CameroonPhone phoneTwo = new CameroonPhone(); phoneTwo.setPhoneNumber("(237) 232345675"); responseData.add(new PhoneDTO(phoneTwo)); CameroonPhone phoneThree = new CameroonPhone(); phoneThree.setPhoneNumber("(237)91234563"); responseData.add(new PhoneDTO(phoneThree)); PaginatedRepresentation<PhoneDTO> response = PaginatedRepresentation.of(20L, 2, 1, responseData); when(service.getPaginatedPhonesDTOByFilter(Mockito.any(RequestFilter.class))).thenReturn(response); this.mockMvc.perform(get("/api/phone")) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.total", is(response.getTotal().intValue()))) .andExpect(jsonPath("$.totalPages", is(response.getTotalPages()))) .andExpect(jsonPath("$.page", is(response.getPage()))) .andExpect(jsonPath("$.data").isArray()) .andExpect(jsonPath("$.data", hasSize(3))) .andExpect(jsonPath("$.data[0].phoneNumber", is("212345675"))) .andExpect(jsonPath("$.data[0].countryCode", is("237"))) .andExpect(jsonPath("$.data[0].countryName", is("Cameroon"))) .andExpect(jsonPath("$.data[0].state", is("VALID"))) .andExpect(jsonPath("$.data[1].phoneNumber", is("232345675"))) .andExpect(jsonPath("$.data[1].countryCode", is("237"))) .andExpect(jsonPath("$.data[1].countryName", is("Cameroon"))) .andExpect(jsonPath("$.data[1].state", is("VALID"))) .andExpect(jsonPath("$.data[2].phoneNumber", is("91234563"))) .andExpect(jsonPath("$.data[2].countryCode", is("237"))) .andExpect(jsonPath("$.data[2].countryName", is("Cameroon"))) .andExpect(jsonPath("$.data[2].state", is("NOT_VALID"))); } @Test public void getEthiopiaPhoneTest() throws Exception { List<PhoneDTO> responseData = new ArrayList<>(); EthiopiaPhone phoneOne = new EthiopiaPhone(); phoneOne.setPhoneNumber("(251)912345678"); responseData.add(new PhoneDTO(phoneOne)); EthiopiaPhone phoneTwo = new EthiopiaPhone(); phoneTwo.setPhoneNumber("(251) 932345678"); responseData.add(new PhoneDTO(phoneTwo)); EthiopiaPhone phoneThree = new EthiopiaPhone(); phoneThree.setPhoneNumber("(251)12345678"); responseData.add(new PhoneDTO(phoneThree)); PaginatedRepresentation<PhoneDTO> response = PaginatedRepresentation.of(20L, 2, 1, responseData); when(service.getPaginatedPhonesDTOByFilter(Mockito.any(RequestFilter.class))).thenReturn(response); this.mockMvc.perform(get("/api/phone")) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.total", is(response.getTotal().intValue()))) .andExpect(jsonPath("$.totalPages", is(response.getTotalPages()))) .andExpect(jsonPath("$.page", is(response.getPage()))) .andExpect(jsonPath("$.data").isArray()) .andExpect(jsonPath("$.data", hasSize(3))) .andExpect(jsonPath("$.data[0].phoneNumber", is("912345678"))) .andExpect(jsonPath("$.data[0].countryCode", is("251"))) .andExpect(jsonPath("$.data[0].countryName", is("Ethiopia"))) .andExpect(jsonPath("$.data[0].state", is("VALID"))) .andExpect(jsonPath("$.data[1].phoneNumber", is("932345678"))) .andExpect(jsonPath("$.data[1].countryCode", is("251"))) .andExpect(jsonPath("$.data[1].countryName", is("Ethiopia"))) .andExpect(jsonPath("$.data[1].state", is("VALID"))) .andExpect(jsonPath("$.data[2].phoneNumber", is("12345678"))) .andExpect(jsonPath("$.data[2].countryCode", is("251"))) .andExpect(jsonPath("$.data[2].countryName", is("Ethiopia"))) .andExpect(jsonPath("$.data[2].state", is("NOT_VALID"))); } @Test public void getMoroccoPhoneTest() throws Exception { List<PhoneDTO> responseData = new ArrayList<>(); MoroccoPhone phoneOne = new MoroccoPhone(); phoneOne.setPhoneNumber("(212)512345678"); responseData.add(new PhoneDTO(phoneOne)); MoroccoPhone phoneTwo = new MoroccoPhone(); phoneTwo.setPhoneNumber("(212) 512345690"); responseData.add(new PhoneDTO(phoneTwo)); MoroccoPhone phoneThree = new MoroccoPhone(); phoneThree.setPhoneNumber("(212)411234567"); responseData.add(new PhoneDTO(phoneThree)); PaginatedRepresentation<PhoneDTO> response = PaginatedRepresentation.of(20L, 2, 1, responseData); when(service.getPaginatedPhonesDTOByFilter(Mockito.any(RequestFilter.class))).thenReturn(response); this.mockMvc.perform(get("/api/phone")) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.total", is(response.getTotal().intValue()))) .andExpect(jsonPath("$.totalPages", is(response.getTotalPages()))) .andExpect(jsonPath("$.page", is(response.getPage()))) .andExpect(jsonPath("$.data").isArray()) .andExpect(jsonPath("$.data", hasSize(3))) .andExpect(jsonPath("$.data[0].phoneNumber", is("512345678"))) .andExpect(jsonPath("$.data[0].countryCode", is("212"))) .andExpect(jsonPath("$.data[0].countryName", is("Morocco"))) .andExpect(jsonPath("$.data[0].state", is("VALID"))) .andExpect(jsonPath("$.data[1].phoneNumber", is("512345690"))) .andExpect(jsonPath("$.data[1].countryCode", is("212"))) .andExpect(jsonPath("$.data[1].countryName", is("Morocco"))) .andExpect(jsonPath("$.data[1].state", is("VALID"))) .andExpect(jsonPath("$.data[2].phoneNumber", is("411234567"))) .andExpect(jsonPath("$.data[2].countryCode", is("212"))) .andExpect(jsonPath("$.data[2].countryName", is("Morocco"))) .andExpect(jsonPath("$.data[2].state", is("NOT_VALID"))); } @Test public void getMozambiquePhoneTest() throws Exception { List<PhoneDTO> responseData = new ArrayList<>(); MozambiquePhone phoneOne = new MozambiquePhone(); phoneOne.setPhoneNumber("(258)214567863"); responseData.add(new PhoneDTO(phoneOne)); MozambiquePhone phoneTwo = new MozambiquePhone(); phoneTwo.setPhoneNumber("(258) 214567890"); responseData.add(new PhoneDTO(phoneTwo)); MozambiquePhone phoneThree = new MozambiquePhone(); phoneThree.setPhoneNumber("(258)734567863"); responseData.add(new PhoneDTO(phoneThree)); PaginatedRepresentation<PhoneDTO> response = PaginatedRepresentation.of(20L, 2, 1, responseData); when(service.getPaginatedPhonesDTOByFilter(Mockito.any(RequestFilter.class))).thenReturn(response); this.mockMvc.perform(get("/api/phone")) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.total", is(response.getTotal().intValue()))) .andExpect(jsonPath("$.totalPages", is(response.getTotalPages()))) .andExpect(jsonPath("$.page", is(response.getPage()))) .andExpect(jsonPath("$.data").isArray()) .andExpect(jsonPath("$.data", hasSize(3))) .andExpect(jsonPath("$.data[0].phoneNumber", is("214567863"))) .andExpect(jsonPath("$.data[0].countryCode", is("258"))) .andExpect(jsonPath("$.data[0].countryName", is("Mozambique"))) .andExpect(jsonPath("$.data[0].state", is("VALID"))) .andExpect(jsonPath("$.data[1].phoneNumber", is("214567890"))) .andExpect(jsonPath("$.data[1].countryCode", is("258"))) .andExpect(jsonPath("$.data[1].countryName", is("Mozambique"))) .andExpect(jsonPath("$.data[1].state", is("VALID"))) .andExpect(jsonPath("$.data[2].phoneNumber", is("734567863"))) .andExpect(jsonPath("$.data[2].countryCode", is("258"))) .andExpect(jsonPath("$.data[2].countryName", is("Mozambique"))) .andExpect(jsonPath("$.data[2].state", is("NOT_VALID"))); } @Test public void getUgandaPhoneTest() throws Exception { List<PhoneDTO> responseData = new ArrayList<>(); UgandaPhone phoneOne = new UgandaPhone(); phoneOne.setPhoneNumber("(256)134567863"); responseData.add(new PhoneDTO(phoneOne)); UgandaPhone phoneTwo = new UgandaPhone(); phoneTwo.setPhoneNumber("(256) 134567890"); responseData.add(new PhoneDTO(phoneTwo)); UgandaPhone phoneThree = new UgandaPhone(); phoneThree.setPhoneNumber("(256)5634567863"); responseData.add(new PhoneDTO(phoneThree)); PaginatedRepresentation<PhoneDTO> response = PaginatedRepresentation.of(20L, 2, 1, responseData); when(service.getPaginatedPhonesDTOByFilter(Mockito.any(RequestFilter.class))).thenReturn(response); this.mockMvc.perform(get("/api/phone")) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.total", is(response.getTotal().intValue()))) .andExpect(jsonPath("$.totalPages", is(response.getTotalPages()))) .andExpect(jsonPath("$.page", is(response.getPage()))) .andExpect(jsonPath("$.data").isArray()) .andExpect(jsonPath("$.data", hasSize(3))) .andExpect(jsonPath("$.data[0].phoneNumber", is("134567863"))) .andExpect(jsonPath("$.data[0].countryCode", is("256"))) .andExpect(jsonPath("$.data[0].countryName", is("Uganda"))) .andExpect(jsonPath("$.data[0].state", is("VALID"))) .andExpect(jsonPath("$.data[1].phoneNumber", is("134567890"))) .andExpect(jsonPath("$.data[1].countryCode", is("256"))) .andExpect(jsonPath("$.data[1].countryName", is("Uganda"))) .andExpect(jsonPath("$.data[1].state", is("VALID"))) .andExpect(jsonPath("$.data[2].phoneNumber", is("5634567863"))) .andExpect(jsonPath("$.data[2].countryCode", is("256"))) .andExpect(jsonPath("$.data[2].countryName", is("Uganda"))) .andExpect(jsonPath("$.data[2].state", is("NOT_VALID"))); } }
package net.floodlightcontroller.cgnipdecap; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Arrays; import org.projectfloodlight.openflow.protocol.OFMessage; import org.projectfloodlight.openflow.protocol.OFPacketIn; import org.projectfloodlight.openflow.protocol.OFPacketOut; import org.projectfloodlight.openflow.protocol.OFType; import org.projectfloodlight.openflow.protocol.OFVersion; import org.projectfloodlight.openflow.protocol.action.OFAction; import org.projectfloodlight.openflow.protocol.action.OFActionOutput; import org.projectfloodlight.openflow.protocol.match.MatchField; import org.projectfloodlight.openflow.types.EthType; import org.projectfloodlight.openflow.types.IpProtocol; import org.projectfloodlight.openflow.types.OFBufferId; import org.projectfloodlight.openflow.types.OFPort; import org.python.constantine.platform.darwin.IPProto; import net.floodlightcontroller.cgnipencap.cgnIPEncap; import net.floodlightcontroller.core.FloodlightContext; import net.floodlightcontroller.core.IOFMessageListener; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.IListener.Command; import net.floodlightcontroller.core.module.FloodlightModuleContext; import net.floodlightcontroller.core.module.FloodlightModuleException; import net.floodlightcontroller.core.module.IFloodlightModule; import net.floodlightcontroller.core.module.IFloodlightService; import net.floodlightcontroller.core.IFloodlightProviderService; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Set; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.packet.IPacket; import net.floodlightcontroller.packet.IPv4; import net.floodlightcontroller.packet.PacketParsingException; import net.floodlightcontroller.packet.TCP; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class cgnIPDecap implements IOFMessageListener, IFloodlightModule { protected IFloodlightProviderService floodlightProvider; protected static Logger logger; // Response packets // Value of the IP addresses should be dynamic protected String serverIP = "192.168.1.202"; protected String clientIP = "192.168.1.201"; @Override public String getName() { // TODO Auto-generated method stub return cgnIPDecap.class.getSimpleName(); } @Override public boolean isCallbackOrderingPrereq(OFType type, String name) { // TODO Auto-generated method stub return false; } @Override public boolean isCallbackOrderingPostreq(OFType type, String name) { // TODO Auto-generated method stub return false; } @Override public Collection<Class<? extends IFloodlightService>> getModuleServices() { // TODO Auto-generated method stub return null; } @Override public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() { // TODO Auto-generated method stub return null; } @Override public Collection<Class<? extends IFloodlightService>> getModuleDependencies() { // TODO Auto-generated method stub Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>(); l.add(IFloodlightProviderService.class); return l; } @Override public void init(FloodlightModuleContext context) throws FloodlightModuleException { // TODO Auto-generated method stub floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class); logger = LoggerFactory.getLogger(cgnIPDecap.class); } @Override public void startUp(FloodlightModuleContext context) throws FloodlightModuleException { // TODO Auto-generated method stub floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this); } @Override public Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) { // TODO Auto-generated method stub Ethernet eth = IFloodlightProviderService.bcStore.get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD); if (eth.getEtherType() != EthType.IPv4) { OFMessage outMessage; outMessage = createHubPacketOut(sw, msg); sw.write(outMessage); return Command.CONTINUE; } IPv4 ipv4 = (IPv4) eth.getPayload(); // *********************************************************Controller as Hub*************************************************************** // logger.info("Received packet and sent out"); // OFMessage outMessage2; // outMessage2 = createHubPacketOut(sw, msg); // sw.write(outMessage2); // return Command.CONTINUE; // ***************************************************************************************************************************************** if (clientIP.equals(ipv4.getSourceAddress().toString()) && serverIP.equals(ipv4.getDestinationAddress().toString())) { // Client => Server // Encapsulate the packet to indicate support IPv4 innerIP = (IPv4) ipv4.clone(); // 0x33 = '3' byte[] options = ByteBuffer .allocate(4) .put((byte)0xde).put((byte)0x28).put((byte)0x33).put((byte)0x00) .array(); innerIP.setOptions(options); innerIP.resetChecksum(); ipv4.setProtocol(IpProtocol.IPv4); ipv4.setPayload(innerIP); ipv4.resetChecksum(); eth.setPayload(ipv4); logger.info("Encapsulated the packet indicates protocol support"); OFPacketIn pi = (OFPacketIn) msg; OFPacketOut po = sw.getOFFactory().buildPacketOut() /* mySwitch is some IOFSwitch object */ .setData(eth.serialize()) .setXid(pi.getXid()) .setInPort((pi.getVersion().compareTo(OFVersion.OF_12) < 0 ? pi.getInPort() : pi.getMatch().get(MatchField.IN_PORT))) .setActions(Collections.singletonList((OFAction) sw.getOFFactory().actions().output(OFPort.FLOOD, 0xffFFffFF))) .build(); sw.write(po); logger.info("Encapsulated packet sent out"); return Command.CONTINUE; } else if (serverIP.equals(ipv4.getSourceAddress().toString()) && clientIP.equals(ipv4.getDestinationAddress().toString())) { // Server => Client // Check if the packet is IP-in-IP if (ipv4.getProtocol() != IpProtocol.IPv4) { logger.info("cgnIPDecap: Not IP-in-IP packet, let it go"); OFMessage outMessage; outMessage = createHubPacketOut(sw, msg); sw.write(outMessage); return Command.CONTINUE; } logger.info("cgnIPDecap: Received target IP-in-IP packet"); TCP tcpp = new TCP(); byte[] tcpBytes = Arrays.copyOfRange(ipv4.serialize(), 80, 120); // logger.info("TCP hex: " + bytesToHex(tcpBytes)); try { tcpp.deserialize(tcpBytes, 0, 40); } catch (PacketParsingException e) { // TODO Auto-generated catch block e.printStackTrace(); } tcpp.resetChecksum(); logger.info("TCP deserialized successfully"); logger.info("TCP dst port: " + tcpp.getDestinationPort()); ipv4.setPayload(tcpp); ipv4.setProtocol(IpProtocol.TCP); ipv4.resetChecksum(); eth.setPayload(ipv4); OFPacketIn pi = (OFPacketIn) msg; OFPacketOut po = sw.getOFFactory().buildPacketOut() /* mySwitch is some IOFSwitch object */ .setData(eth.serialize()) .setXid(pi.getXid()) .setInPort((pi.getVersion().compareTo(OFVersion.OF_12) < 0 ? pi.getInPort() : pi.getMatch().get(MatchField.IN_PORT))) .setActions(Collections.singletonList((OFAction) sw.getOFFactory().actions().output(OFPort.FLOOD, 0xffFFffFF))) .build(); sw.write(po); logger.info("cgnIPDecap: decapsulated and sent packet out"); OFMessage outMessage; outMessage = createHubPacketOut(sw, msg); sw.write(outMessage); return Command.CONTINUE; } else { // Send PACKET_OUT OFMessage outMessage; outMessage = createHubPacketOut(sw, msg); sw.write(outMessage); return Command.CONTINUE; } } private OFMessage createHubPacketOut(IOFSwitch sw, OFMessage msg) { OFPacketIn pi = (OFPacketIn) msg; OFPacketOut.Builder pob = sw.getOFFactory().buildPacketOut(); pob.setBufferId(pi.getBufferId()).setXid(pi.getXid()).setInPort((pi.getVersion().compareTo(OFVersion.OF_12) < 0 ? pi.getInPort() : pi.getMatch().get(MatchField.IN_PORT))); // set actions OFActionOutput.Builder actionBuilder = sw.getOFFactory().actions().buildOutput(); actionBuilder.setPort(OFPort.NORMAL); pob.setActions(Collections.singletonList((OFAction) actionBuilder.build())); // set data if it is included in the packetin if (pi.getBufferId() == OFBufferId.NO_BUFFER) { byte[] packetData = pi.getData(); pob.setData(packetData); } return pob.build(); } private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray(); public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_ARRAY[v >>> 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return new String(hexChars); } private void parseOptions(byte[] options) { logger.info("cgnIPDecap: Parsing inner IP options."); // Get the String strOptions = options.toString(); if (strOptions.length() < 40) { logger.info("cgnIPDecap: Length of options is less than 40 bytes, return"); return; } // Uid: 5, nonce1:2, SSH224: 28 String uid = strOptions.substring(3, 8); String nonce1 = strOptions.substring(8, 10); String clientKeySSH224 = strOptions.substring(10, 38); BigInteger no = new BigInteger(1, clientKeySSH224.getBytes()); String clientKeyHex = no.toString(16); logger.info("cgnIPDecap: Uid: " + uid); logger.info("cgnIPDecap: Nonce1: " + nonce1); logger.info("cgnIPDecap: clientKeyHex: " + clientKeyHex); logger.info("cgnIPDecap: Key information is stored on controller"); } }
import java.util.List; /** * A generic B+ Tree interface (DO NOT edit this file) * * @author sapan (sapan@cs.wisc.edu) */ public interface BPTreeADT<K, V> { /** * Inserts the key and value in the appropriate nodes in the tree * * Note: key-value pairs with duplicate keys can be inserted into the tree. * * @param key * @param value */ public void insert(K key, V value); /** * Gets the values that satisfy the given range * search arguments. * * Value of comparator can be one of these: * "<=", "==", ">=" * * Example: * If given key = 2.5 and comparator = ">=": * return all the values with the corresponding * keys >= 2.5 * * If key is null, return empty list. * If comparator is null, empty, or not according * to required form, return empty list. * * @param key to be searched * @param comparator is a string * @return list of values that are the result of the * range search; if nothing found, return empty list */ public List<V> rangeSearch(K key, String comparator); /** * Returns a string representation for the tree * This method is provided to students in the implementation. * @return a string representation */ public String toString(); }
package seedu.dictionote.commons.core; /** * Container for user visible messages. */ public class Messages { public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command"; public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s"; public static final String MESSAGE_INVALID_PERSON_DISPLAYED_INDEX = "The person index provided is invalid"; public static final String MESSAGE_PERSONS_LISTED_OVERVIEW = "%1$d persons listed!"; }
package ru.holuhoev.bet; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
/* * Copyright (C) 2013, 2014 Brett Wooldridge * * 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.zaxxer.hikari.pool; import com.zaxxer.hikari.SQLExceptionOverride; import com.zaxxer.hikari.util.FastList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.sql.*; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Executor; import static com.zaxxer.hikari.SQLExceptionOverride.Override.DO_NOT_EVICT; import static com.zaxxer.hikari.util.ClockSource.currentTime; /** * This is the proxy class for java.sql.Connection. * * @author Brett Wooldridge */ public abstract class ProxyConnection implements Connection { static final int DIRTY_BIT_READONLY = 0b000001; static final int DIRTY_BIT_AUTOCOMMIT = 0b000010; static final int DIRTY_BIT_ISOLATION = 0b000100; static final int DIRTY_BIT_CATALOG = 0b001000; static final int DIRTY_BIT_NETTIMEOUT = 0b010000; static final int DIRTY_BIT_SCHEMA = 0b100000; private static final Logger LOGGER; private static final Set<String> ERROR_STATES; private static final Set<Integer> ERROR_CODES; @SuppressWarnings("WeakerAccess") protected Connection delegate; private final PoolEntry poolEntry; private final ProxyLeakTask leakTask; private final FastList<Statement> openStatements; private int dirtyBits; private long lastAccess; private boolean isCommitStateDirty; private boolean isReadOnly; private boolean isAutoCommit; private int networkTimeout; private int transactionIsolation; private String dbcatalog; private String dbschema; // static initializer static { LOGGER = LoggerFactory.getLogger(ProxyConnection.class); ERROR_STATES = new HashSet<>(); ERROR_STATES.add("0A000"); // FEATURE UNSUPPORTED ERROR_STATES.add("57P01"); // ADMIN SHUTDOWN ERROR_STATES.add("57P02"); // CRASH SHUTDOWN ERROR_STATES.add("57P03"); // CANNOT CONNECT NOW ERROR_STATES.add("01002"); // SQL92 disconnect error ERROR_STATES.add("JZ0C0"); // Sybase disconnect error ERROR_STATES.add("JZ0C1"); // Sybase disconnect error ERROR_CODES = new HashSet<>(); ERROR_CODES.add(500150); ERROR_CODES.add(2399); } protected ProxyConnection(final PoolEntry poolEntry, final Connection connection, final FastList<Statement> openStatements, final ProxyLeakTask leakTask, final long now, final boolean isReadOnly, final boolean isAutoCommit) { this.poolEntry = poolEntry; this.delegate = connection; this.openStatements = openStatements; this.leakTask = leakTask; this.lastAccess = now; this.isReadOnly = isReadOnly; this.isAutoCommit = isAutoCommit; } /** {@inheritDoc} */ @Override public final String toString() { return this.getClass().getSimpleName() + '@' + System.identityHashCode(this) + " wrapping " + delegate; } // *********************************************************************** // Connection State Accessors // *********************************************************************** final boolean getAutoCommitState() { return isAutoCommit; } final String getCatalogState() { return dbcatalog; } final String getSchemaState() { return dbschema; } final int getTransactionIsolationState() { return transactionIsolation; } final boolean getReadOnlyState() { return isReadOnly; } final int getNetworkTimeoutState() { return networkTimeout; } // *********************************************************************** // Internal methods // *********************************************************************** final PoolEntry getPoolEntry() { return poolEntry; } @SuppressWarnings("ConstantConditions") final SQLException checkException(SQLException sqle) { boolean evict = false; SQLException nse = sqle; final SQLExceptionOverride exceptionOverride = poolEntry.getPoolBase().exceptionOverride; for (int depth = 0; delegate != ClosedConnection.CLOSED_CONNECTION && nse != null && depth < 10; depth++) { final String sqlState = nse.getSQLState(); if (sqlState != null && sqlState.startsWith("08") || nse instanceof SQLTimeoutException || ERROR_STATES.contains(sqlState) || ERROR_CODES.contains(nse.getErrorCode())) { if (exceptionOverride != null && exceptionOverride.adjudicate(nse) == DO_NOT_EVICT) { break; } // broken connection evict = true; break; } else { nse = nse.getNextException(); } } if (evict) { SQLException exception = (nse != null) ? nse : sqle; LOGGER.warn("{} - Connection {} marked as broken because of SQLSTATE({}), ErrorCode({})", poolEntry.getPoolName(), delegate, exception.getSQLState(), exception.getErrorCode(), exception); leakTask.cancel(); poolEntry.evict("(connection is broken)"); delegate = ClosedConnection.CLOSED_CONNECTION; } return sqle; } final synchronized void untrackStatement(final Statement statement) { openStatements.remove(statement); } final void markCommitStateDirty() { if (isAutoCommit) { lastAccess = currentTime(); } else { isCommitStateDirty = true; } } void cancelLeakTask() { leakTask.cancel(); } private synchronized <T extends Statement> T trackStatement(final T statement) { openStatements.add(statement); return statement; } @SuppressWarnings("EmptyTryBlock") private synchronized void closeStatements() { final int size = openStatements.size(); if (size > 0) { for (int i = 0; i < size && delegate != ClosedConnection.CLOSED_CONNECTION; i++) { try (Statement ignored = openStatements.get(i)) { // 遍历所有打开的语句 // automatic resource cleanup } catch (SQLException e) { LOGGER.warn("{} - Connection {} marked as broken because of an exception closing open statements during Connection.close()", poolEntry.getPoolName(), delegate); leakTask.cancel(); poolEntry.evict("(exception closing Statements during Connection.close())"); delegate = ClosedConnection.CLOSED_CONNECTION; } } openStatements.clear(); } } // ********************************************************************** // "Overridden" java.sql.Connection Methods // ********************************************************************** // 通过 inheritDoc 可以继承注释,归还 Connection /** {@inheritDoc} */ @Override public final void close() throws SQLException { // Closing statements can cause connection eviction, so this must run before the conditional below // 关闭语句可能导致连接被驱逐,因此优先执行 closeStatements(); if (delegate != ClosedConnection.CLOSED_CONNECTION) { // 取消链接泄漏监测 leakTask.cancel(); try { if (isCommitStateDirty && !isAutoCommit) { // 脏提交/非自动提交,进行回滚 delegate.rollback(); lastAccess = currentTime(); LOGGER.debug("{} - Executed rollback on connection {} due to dirty commit state on close().", poolEntry.getPoolName(), delegate); } if (dirtyBits != 0) { poolEntry.resetConnectionState(this, dirtyBits); lastAccess = currentTime(); } delegate.clearWarnings(); } catch (SQLException e) { // when connections are aborted, exceptions are often thrown that should not reach the application if (!poolEntry.isMarkedEvicted()) { throw checkException(e); } } finally { // 调用 PoolEntry 的 recycle 方法(delegate 使用一个已经关闭连接的代理,不能操作数据库) delegate = ClosedConnection.CLOSED_CONNECTION; // poolEntry 返回到 HikariPool 中 // 存在疑问,poolEntry 和 delegate 的关系是什么? // 1. 在创建 poolEntry 的时候,delegate 和 poolEntry 中的 connection 是相同的 // 2. 在关闭 poolEntry 的时候,poolEntry 中的 connection 还是保持和数据库之间的连接,但是 delegate 设置为一个 CLOSED_CONNECTION // 3. 最后调用 ConcurrentBag.requite 方法,归还 poolEntry poolEntry.recycle(lastAccess); } } } /** {@inheritDoc} */ @Override @SuppressWarnings("RedundantThrows") public boolean isClosed() throws SQLException { return (delegate == ClosedConnection.CLOSED_CONNECTION); } /** {@inheritDoc} */ @Override public Statement createStatement() throws SQLException { return ProxyFactory.getProxyStatement(this, trackStatement(delegate.createStatement())); } /** {@inheritDoc} */ @Override public Statement createStatement(int resultSetType, int concurrency) throws SQLException { return ProxyFactory.getProxyStatement(this, trackStatement(delegate.createStatement(resultSetType, concurrency))); } /** {@inheritDoc} */ @Override public Statement createStatement(int resultSetType, int concurrency, int holdability) throws SQLException { return ProxyFactory.getProxyStatement(this, trackStatement(delegate.createStatement(resultSetType, concurrency, holdability))); } /** {@inheritDoc} */ @Override public CallableStatement prepareCall(String sql) throws SQLException { return ProxyFactory.getProxyCallableStatement(this, trackStatement(delegate.prepareCall(sql))); } /** {@inheritDoc} */ @Override public CallableStatement prepareCall(String sql, int resultSetType, int concurrency) throws SQLException { return ProxyFactory.getProxyCallableStatement(this, trackStatement(delegate.prepareCall(sql, resultSetType, concurrency))); } /** {@inheritDoc} */ @Override public CallableStatement prepareCall(String sql, int resultSetType, int concurrency, int holdability) throws SQLException { return ProxyFactory.getProxyCallableStatement(this, trackStatement(delegate.prepareCall(sql, resultSetType, concurrency, holdability))); } /** {@inheritDoc} */ @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return ProxyFactory.getProxyPreparedStatement(this, trackStatement(delegate.prepareStatement(sql))); } /** {@inheritDoc} */ @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return ProxyFactory.getProxyPreparedStatement(this, trackStatement(delegate.prepareStatement(sql, autoGeneratedKeys))); } /** {@inheritDoc} */ @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int concurrency) throws SQLException { return ProxyFactory.getProxyPreparedStatement(this, trackStatement(delegate.prepareStatement(sql, resultSetType, concurrency))); } /** {@inheritDoc} */ @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int concurrency, int holdability) throws SQLException { return ProxyFactory.getProxyPreparedStatement(this, trackStatement(delegate.prepareStatement(sql, resultSetType, concurrency, holdability))); } /** {@inheritDoc} */ @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return ProxyFactory.getProxyPreparedStatement(this, trackStatement(delegate.prepareStatement(sql, columnIndexes))); } /** {@inheritDoc} */ @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return ProxyFactory.getProxyPreparedStatement(this, trackStatement(delegate.prepareStatement(sql, columnNames))); } /** {@inheritDoc} */ @Override public DatabaseMetaData getMetaData() throws SQLException { markCommitStateDirty(); return ProxyFactory.getProxyDatabaseMetaData(this, delegate.getMetaData()); } /** {@inheritDoc} */ @Override public void commit() throws SQLException { delegate.commit(); isCommitStateDirty = false; lastAccess = currentTime(); } /** {@inheritDoc} */ @Override public void rollback() throws SQLException { delegate.rollback(); isCommitStateDirty = false; lastAccess = currentTime(); } /** {@inheritDoc} */ @Override public void rollback(Savepoint savepoint) throws SQLException { delegate.rollback(savepoint); isCommitStateDirty = false; lastAccess = currentTime(); } /** {@inheritDoc} */ @Override public void setAutoCommit(boolean autoCommit) throws SQLException { delegate.setAutoCommit(autoCommit); isAutoCommit = autoCommit; dirtyBits |= DIRTY_BIT_AUTOCOMMIT; } /** {@inheritDoc} */ @Override public void setReadOnly(boolean readOnly) throws SQLException { delegate.setReadOnly(readOnly); isReadOnly = readOnly; isCommitStateDirty = false; dirtyBits |= DIRTY_BIT_READONLY; } /** {@inheritDoc} */ @Override public void setTransactionIsolation(int level) throws SQLException { delegate.setTransactionIsolation(level); transactionIsolation = level; dirtyBits |= DIRTY_BIT_ISOLATION; } /** {@inheritDoc} */ @Override public void setCatalog(String catalog) throws SQLException { delegate.setCatalog(catalog); dbcatalog = catalog; dirtyBits |= DIRTY_BIT_CATALOG; } /** {@inheritDoc} */ @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { delegate.setNetworkTimeout(executor, milliseconds); networkTimeout = milliseconds; dirtyBits |= DIRTY_BIT_NETTIMEOUT; } /** {@inheritDoc} */ @Override public void setSchema(String schema) throws SQLException { delegate.setSchema(schema); dbschema = schema; dirtyBits |= DIRTY_BIT_SCHEMA; } /** {@inheritDoc} */ @Override public final boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isInstance(delegate) || (delegate != null && delegate.isWrapperFor(iface)); } // 连接池中的链接,关闭的时候是返回到连接池,如果要真实关闭使用这个方法 /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public final <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isInstance(delegate)) { return (T) delegate; } else if (delegate != null) { return delegate.unwrap(iface); } throw new SQLException("Wrapped connection is not an instance of " + iface); } // ********************************************************************** // Private classes // ********************************************************************** private static final class ClosedConnection { static final Connection CLOSED_CONNECTION = getClosedConnection(); private static Connection getClosedConnection() { InvocationHandler handler = (proxy, method, args) -> { final String methodName = method.getName(); if ("isClosed".equals(methodName)) { return Boolean.TRUE; } else if ("isValid".equals(methodName)) { return Boolean.FALSE; } if ("abort".equals(methodName)) { return Void.TYPE; } if ("close".equals(methodName)) { return Void.TYPE; } else if ("toString".equals(methodName)) { return ClosedConnection.class.getCanonicalName(); } throw new SQLException("Connection is closed"); }; return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[] { Connection.class }, handler); } } }
// Targeted by JavaCPP version 1.5.6-SNAPSHOT: DO NOT EDIT THIS FILE package org.bytedeco.cpython; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.cpython.global.python.*; // #endif @Opaque @Properties(inherit = org.bytedeco.cpython.presets.python.class) public class PyDictKeysObject extends Pointer { /** Empty constructor. Calls {@code super((Pointer)null)}. */ public PyDictKeysObject() { super((Pointer)null); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public PyDictKeysObject(Pointer p) { super(p); } }
/** * */ package convex_hull; import java.awt.geom.Line2D; import java.awt.geom.Point2D; /** * <h2>LineSide</h2> * * @author Cristian Abrante Dorta * @company University Of La Laguna * @date 22/04/2018 * @version 1.0.0 */ public enum LineSide { LEFT, RIGHT, CONTAINED; static public final double EPS = 0.00000001; /** * Method that returns the side * * @param line of the points * @param point we want to evaluate. * @return the side */ public static LineSide getSide(Line2D line, Point2D point) { Point2D A = line.getP1(); Point2D B = line.getP2(); double value = (B.getX() - A.getX()) * (point.getY() - A.getY()) - (B.getY() - A.getY()) * (point.getX() - A.getX()); // value > 0 if (value > EPS) { return LEFT; // value == 0 } else if (Math.abs(value) < EPS) { return CONTAINED; // value < 0; } else { return RIGHT; } } /** * Method that compute the distance between a line and a point * @param line * @param point * @return */ public static double distance(Line2D line, Point2D point) { Point2D A = line.getP1(); Point2D B = line.getP2(); double ABx = B.getX() - A.getX(); double ABy = B.getY() - A.getY(); double num = ABx * (A.getY() - point.getY()) - ABy * (A.getX() - point.getX()); // num < 0 if (-num > EPS) { num = -num; } return num; } }
package ch.uzh.ifi.hase.soprafs22.rest.dto; public class BillingGetDTO { private long billingId; private String bookingType; private long bookingId; private String paymentStatus; public long getBillingId() { return billingId; } public void setBillingId(long billingId) { this.billingId = billingId; } public String getBookingType() { return bookingType; } public void setBookingType(String bookingType) { this.bookingType = bookingType; } public long getBookingId() { return bookingId; } public void setBookingId(long bookingId) { this.bookingId = bookingId; } public String getPaymentStatus() { return paymentStatus; } public void setPaymentStatus(String paymentStatus) { this.paymentStatus = paymentStatus; } }
package io.quarkus.mongodb.panache.runtime; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.ReadPreference; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.model.Collation; import io.quarkus.panache.common.Page; import io.quarkus.panache.common.Range; import io.quarkus.panache.common.exception.PanacheQueryException; public class CommonPanacheQueryImpl<Entity> { private MongoCollection collection; private Bson mongoQuery; private Bson sort; private Bson projections; private Page page; private Long count; private Range range; private Collation collation; public CommonPanacheQueryImpl(MongoCollection<? extends Entity> collection, Bson mongoQuery, Bson sort) { this.collection = collection; this.mongoQuery = mongoQuery; this.sort = sort; } private CommonPanacheQueryImpl(CommonPanacheQueryImpl<?> previousQuery, Bson projections, Class<?> documentClass) { this.collection = previousQuery.collection.withDocumentClass(documentClass); this.mongoQuery = previousQuery.mongoQuery; this.sort = previousQuery.sort; this.projections = projections; this.page = previousQuery.page; this.count = previousQuery.count; this.range = previousQuery.range; this.collation = previousQuery.collation; } public <T> CommonPanacheQueryImpl<T> project(Class<T> type) { // collect field names from public fields and getters Set<String> fieldNames = MongoPropertyUtil.collectFields(type); // create the projection document Document projections = new Document(); for (String fieldName : fieldNames) { projections.append(fieldName, 1); } return new CommonPanacheQueryImpl<>(this, projections, type); } @SuppressWarnings("unchecked") public <T extends Entity> CommonPanacheQueryImpl<T> page(Page page) { this.page = page; this.range = null; // reset the range to be able to switch from range to page return (CommonPanacheQueryImpl<T>) this; } public <T extends Entity> CommonPanacheQueryImpl<T> page(int pageIndex, int pageSize) { return page(Page.of(pageIndex, pageSize)); } public <T extends Entity> CommonPanacheQueryImpl<T> nextPage() { checkPagination(); return page(page.next()); } public <T extends Entity> CommonPanacheQueryImpl<T> previousPage() { checkPagination(); return page(page.previous()); } public <T extends Entity> CommonPanacheQueryImpl<T> firstPage() { checkPagination(); return page(page.first()); } public <T extends Entity> CommonPanacheQueryImpl<T> lastPage() { checkPagination(); return page(page.index(pageCount() - 1)); } public boolean hasNextPage() { checkPagination(); return page.index < (pageCount() - 1); } public boolean hasPreviousPage() { checkPagination(); return page.index > 0; } public int pageCount() { checkPagination(); long count = count(); if (count == 0) return 1; // a single page of zero results return (int) Math.ceil((double) count / (double) page.size); } public Page page() { checkPagination(); return page; } private void checkPagination() { if (page == null) { throw new UnsupportedOperationException( "Cannot call a page related method, " + "call page(Page) or page(int, int) to initiate pagination first"); } if (range != null) { throw new UnsupportedOperationException("Cannot call a page related method in a ranged query, " + "call page(Page) or page(int, int) to initiate pagination first"); } } public <T extends Entity> CommonPanacheQueryImpl<T> range(int startIndex, int lastIndex) { this.range = Range.of(startIndex, lastIndex); // reset the page to its default to be able to switch from page to range this.page = null; return (CommonPanacheQueryImpl<T>) this; } public <T extends Entity> CommonPanacheQueryImpl<T> withCollation(Collation collation) { this.collation = collation; return (CommonPanacheQueryImpl<T>) this; } public <T extends Entity> CommonPanacheQueryImpl<T> withReadPreference(ReadPreference readPreference) { this.collection = this.collection.withReadPreference(readPreference); return (CommonPanacheQueryImpl<T>) this; } // Results @SuppressWarnings("unchecked") public long count() { if (count == null) { count = mongoQuery == null ? collection.countDocuments() : collection.countDocuments(mongoQuery); } return count; } public <T extends Entity> List<T> list() { return list(null); } @SuppressWarnings("unchecked") private <T extends Entity> List<T> list(Integer limit) { List<T> list = new ArrayList<>(); FindIterable find = mongoQuery == null ? collection.find() : collection.find(mongoQuery); if (this.projections != null) { find.projection(projections); } if (this.collation != null) { find.collation(collation); } manageOffsets(find, limit); MongoCursor<T> cursor = find.sort(sort).iterator(); try { while (cursor.hasNext()) { T entity = cursor.next(); list.add(entity); } } finally { cursor.close(); } return list; } @SuppressWarnings("unchecked") public <T extends Entity> Stream<T> stream() { return (Stream<T>) list().stream(); } public <T extends Entity> T firstResult() { List<T> list = list(1); return list.isEmpty() ? null : list.get(0); } public <T extends Entity> Optional<T> firstResultOptional() { return Optional.ofNullable(firstResult()); } public <T extends Entity> T singleResult() { List<T> list = list(2); if (list.size() != 1) { throw new PanacheQueryException("There should be only one result"); } return list.get(0); } public <T extends Entity> Optional<T> singleResultOptional() { List<T> list = list(2); if (list.size() > 1) { throw new PanacheQueryException("There should be no more than one result"); } return list.isEmpty() ? Optional.empty() : Optional.of(list.get(0)); } private void manageOffsets(FindIterable find, Integer limit) { if (range != null) { find.skip(range.getStartIndex()); if (limit == null) { // range is 0 based, so we add 1 to the limit find.limit(range.getLastIndex() - range.getStartIndex() + 1); } } else if (page != null) { find.skip(page.index * page.size); if (limit == null) { find.limit(page.size); } } if (limit != null) { find.limit(limit); } } }
package com.ybsystem.tweetmate.fragments.timeline; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.fragment.app.Fragment; import com.ybsystem.tweetmate.R; import com.ybsystem.tweetmate.adapters.recycler.TweetRecyclerAdapter; import com.ybsystem.tweetmate.application.TweetMateApp; import com.ybsystem.tweetmate.models.entities.Column; import com.ybsystem.tweetmate.models.entities.twitter.TwitterStatus; import com.ybsystem.tweetmate.utils.ExceptionUtils; import com.ybsystem.tweetmate.utils.ToastUtils; import java.util.List; import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.observers.DisposableObserver; import io.reactivex.rxjava3.schedulers.Schedulers; import twitter4j.Paging; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import static com.ybsystem.tweetmate.resources.ResString.*; public class ProfileTimeline extends TimelineBase { // Bundle private Column mColumn; private boolean mIsPrivate; // For user media private long mLastTweetId; public Fragment newInstance(Column column, boolean isPrivate) { Bundle bundle = new Bundle(); bundle.putSerializable("COLUMN", column); bundle.putSerializable("PRIVATE", isPrivate); setArguments(bundle); return this; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate View view = inflater.inflate(R.layout.fragment_timeline, container, false); // Init mColumn = (Column) getArguments().getSerializable("COLUMN"); mIsPrivate = (boolean) getArguments().getSerializable("PRIVATE"); mScrollLoad = true; // Set view setRecyclerView(view); setRecyclerAdapter(new TweetRecyclerAdapter()); setUltraPullToRefresh(view); mPtrFrame.setEnabled(false); return view; } protected void loadTweet(boolean isPullLoad, boolean isClickLoad) { // Check if (mIsPrivate) { mFooterText.setText(STR_ACCOUNT_PRIVATE); mFooterProgress.setVisibility(View.GONE); return; } // Change footer mFooterText.setText(STR_LOADING); mFooterProgress.setVisibility(View.VISIBLE); mFooterView.setVisibility(View.VISIBLE); // Load timeline switch (mColumn.getType()) { case USER_TWEET: case USER_FAVORITE: loadUserTweetFavorite(isClickLoad); break; case USER_MEDIA: loadUserMedia(isClickLoad, 1); break; } } private void loadUserTweetFavorite(boolean isClickLoad) { // Create request TweetRecyclerAdapter adapter = (TweetRecyclerAdapter) mRecyclerAdapter; Observable<List<Status>> observable = Observable.create(e -> { try { Paging paging; if (adapter.getObjCount() == 0) { paging = mFirstPaging; } else { paging = mNextPaging; paging.setMaxId(adapter.getLastObj().getId() - 1); } Twitter twitter = TweetMateApp.getTwitter(); switch (mColumn.getType()) { case USER_TWEET: e.onNext(twitter.getUserTimeline(mColumn.getId(), paging)); break; case USER_FAVORITE: e.onNext(twitter.getFavorites(mColumn.getId(), paging)); break; } e.onComplete(); } catch (TwitterException ex) { e.onError(ex); } }); DisposableObserver<List<Status>> disposable = new DisposableObserver<List<Status>>() { @Override public void onNext(List<Status> statusList) { if (statusList.isEmpty()) { // No tweet... if (adapter.isEmpty()) { mFooterText.setText(STR_TWEET_NONE); mFooterProgress.setVisibility(View.GONE); } else mFooterView.setVisibility(View.GONE); } else { // Success for (Status status4j : statusList) { adapter.add(new TwitterStatus(status4j)); } adapter.notifyDataSetChanged(); mScrollLoad = true; } } @Override public void onError(Throwable t) { // Failed... mFooterText.setText(STR_TAP_TO_LOAD); mFooterProgress.setVisibility(View.GONE); // Show error message if loaded by user action if (isClickLoad) { ToastUtils.showShortToast(ExceptionUtils.getErrorMessage(t)); } mFooterClick = true; } @Override public void onComplete() { } }; observable .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(disposable); } private void loadUserMedia(boolean isClickLoad, int count) { // Create request TweetRecyclerAdapter adapter = (TweetRecyclerAdapter) mRecyclerAdapter; Observable<List<Status>> observable = Observable.create(e -> { try { Paging paging; if (mLastTweetId == 0) { paging = mFirstPaging; paging.setCount(200); } else { paging = mNextPaging; paging.setCount(200); paging.setMaxId(mLastTweetId - 1); } Twitter twitter = TweetMateApp.getTwitter(); e.onNext(twitter.getUserTimeline(mColumn.getId(), paging)); e.onComplete(); } catch (TwitterException ex) { e.onError(ex); } }); DisposableObserver<List<Status>> disposable = new DisposableObserver<List<Status>>() { @Override public void onNext(List<Status> statusList) { if (statusList.isEmpty()) { // No tweet... if (adapter.isEmpty()) { mFooterText.setText(STR_TWEET_NONE); mFooterProgress.setVisibility(View.GONE); } else mFooterView.setVisibility(View.GONE); } else { // Success boolean exist = false; for (Status status4j : statusList) { TwitterStatus status = new TwitterStatus(status4j); if (!status.isRetweet() && status.isTwiMedia()) { adapter.add(status); exist = true; } } mLastTweetId = statusList.get(statusList.size() - 1).getId(); if (exist) { adapter.notifyDataSetChanged(); mScrollLoad = true; } else { if (count >= 4) { mFooterText.setText(STR_TAP_TO_LOAD); mFooterProgress.setVisibility(View.GONE); mFooterClick = true; } else { loadUserMedia(isClickLoad, count + 1); } } } } @Override public void onError(Throwable t) { // Failed... mFooterText.setText(STR_TAP_TO_LOAD); mFooterProgress.setVisibility(View.GONE); // Show error message if loaded by user action if (isClickLoad) { ToastUtils.showShortToast(ExceptionUtils.getErrorMessage(t)); } mFooterClick = true; } @Override public void onComplete() { } }; observable .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(disposable); } }
package nachos.network; import nachos.machine.*; /** * A mail message. Includes a packet header, a mail header, and the actual * payload. * * @see nachos.machine.Packet */ public class MailMessage { /** * Allocate a new mail message to be sent, using the specified parameters. * * @param dstLink the destination link address. * @param dstPort the destination port. * @param srcLink the source link address. * @param srcPort the source port. * @param contents the contents of the packet. */ public MailMessage(int dstLink, int dstPort, int srcLink, int srcPort, byte[] contents) throws MalformedPacketException { // make sure the paramters are valid if (dstPort < 0 || dstPort >= portLimit || srcPort < 0 || srcPort >= portLimit || contents.length > maxContentsLength) throw new MalformedPacketException(); this.dstPort = (byte) dstPort; this.srcPort = (byte) srcPort; this.contents = contents; byte[] packetContents = new byte[headerLength + contents.length]; packetContents[0] = (byte) dstPort; packetContents[1] = (byte) srcPort; System.arraycopy(contents, 0, packetContents, headerLength, contents.length); packet = new Packet(dstLink, srcLink, packetContents); } /** * Allocate a new mail message using the specified packet from the network. * * @param packet the packet containg the mail message. */ public MailMessage(Packet packet) throws MalformedPacketException { this.packet = packet; // make sure we have a valid header if (packet.contents.length < headerLength || packet.contents[0] < 0 || packet.contents[0] >= portLimit || packet.contents[1] < 0 || packet.contents[1] >= portLimit) throw new MalformedPacketException(); dstPort = packet.contents[0]; srcPort = packet.contents[1]; contents = new byte[packet.contents.length - headerLength]; System.arraycopy(packet.contents, headerLength, contents, 0, contents.length); } /** * Return a string representation of the message headers. */ public String toString() { return "from (" + packet.srcLink + ":" + srcPort + ") to (" + packet.dstLink + ":" + dstPort + "), " + contents.length + " bytes"; } /** This message, as a packet that can be sent through a network link. */ public Packet packet; /** The port used by this message on the destination machine. */ public int dstPort; /** The port used by this message on the source machine. */ public int srcPort; /** The contents of this message, excluding the mail message header. */ public byte[] contents; /** * The number of bytes in a mail header. The header is formatted as * follows: * * <table> * <tr><td>offset</td><td>size</td><td>value</td></tr> * <tr><td>0</td><td>1</td><td>destination port</td></tr> * <tr><td>1</td><td>1</td><td>source port</td></tr> * </table> */ public static final int headerLength = 2; /** Maximum payload (real data) that can be included in a single mesage. */ public static final int maxContentsLength = Packet.maxContentsLength - headerLength; /** * The upper limit on mail ports. All ports fall between <tt>0</tt> and * <tt>portLimit - 1</tt>. */ public static final int portLimit = 128; }
package org.intermine.bio.dataconversion; /* * Copyright (C) 2002-2017 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.io.Reader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.FormattedTextParser; import org.intermine.xml.full.Item; /** * * @author Julie Sullivan */ public class SignorConverter extends BioFileConverter { // private static final String DATASET_TITLE = "Signor data set"; private static final String DATA_SOURCE_NAME = "Signor"; private static final String PROTEIN = "protein"; private Map<String, String> entities = new HashMap<String, String>(); private Map<String, String> publications = new HashMap<String, String>(); /** * Constructor * @param writer the ItemWriter used to handle the resultant items * @param model the Model */ public SignorConverter(ItemWriter writer, Model model) { super(writer, model, DATA_SOURCE_NAME, DATASET_TITLE); } /** * * * {@inheritDoc} */ public void process(Reader reader) throws Exception { Iterator<?> lineIter = FormattedTextParser.parseDelimitedReader(reader, ';'); // skip header lineIter.next(); // each gene is on a new line while (lineIter.hasNext()) { String[] line = (String[]) lineIter.next(); if (line.length < 27) { continue; } String type1 = line[1]; String identifier1 = line[2]; String participant1 = getEntity(identifier1, type1); String type2 = line[5]; String identifier2 = line[6]; String participant2 = getEntity(identifier2, type2); String effect = line[8]; String effectMechanism = line[9]; String mechanismResidues = line[10]; String mechanismSequences = line[11]; String pubmedId = getPublication(line[21]); String notes = line[23]; String signorId = line[26]; Item signalling = createItem("Signalling"); if (StringUtils.isNotEmpty(signorId)) { signalling.setAttribute("identifier", signorId); } signalling.setReference("participant1", participant1); signalling.setReference("participant2", participant2); store(signalling); Item detail = createItem("SignallingDetail"); if (StringUtils.isNotEmpty(effect)) { detail.setAttribute("effect", effect); } if (StringUtils.isNotEmpty(effectMechanism)) { detail.setAttribute("effectMechanism", effectMechanism); } if (StringUtils.isNotEmpty(mechanismResidues)) { detail.setAttribute("mechanismResidues", mechanismResidues); } if (StringUtils.isNotEmpty(mechanismSequences)) { detail.setAttribute("mechanismSequences", mechanismSequences); } if (StringUtils.isNotEmpty(notes)) { detail.setAttribute("notes", notes); } if (StringUtils.isNotEmpty(pubmedId)) { detail.addToCollection("publications", pubmedId); } detail.setReference("signalling", signalling); store(detail); } } private String getEntity(String primaryIdentifier, String type) throws ObjectStoreException { String refId = entities.get(primaryIdentifier); if (refId == null) { Item item = null; if (PROTEIN.equals(type)) { item = createItem("Protein"); item.setAttribute("primaryAccession", primaryIdentifier); } else { item = createItem("BioEntity"); item.setAttribute("primaryIdentifier", primaryIdentifier); } store(item); refId = item.getIdentifier(); entities.put(primaryIdentifier, refId); } return refId; } private String getPublication(String pubMedId) throws ObjectStoreException { if (StringUtils.isEmpty(pubMedId)) { return null; } String refId = publications.get(pubMedId); if (refId == null) { Item item = createItem("Publication"); item.setAttribute("pubMedId", pubMedId); store(item); refId = item.getIdentifier(); publications.put(pubMedId, refId); } return refId; } }
package me.bassintag.recordshelf.db.provider.dao; import java.util.List; import me.bassintag.recordshelf.db.object.Artist; /* ** Created by Antoine on 02/09/2017. */ public interface IArtistDao { // GET Artist getArtistById(int id); Artist getArtistByName(String name); List<Artist> getAllArtists(); // UPDATE boolean updateArtist(Artist artist); // ADD boolean addArtist(Artist artist); boolean addArtists(List<Artist> artists); // DELETE boolean deleteArtistById(int id); }
/* * MIT License * * Copyright (c) 2021 MASES s.r.l. * * 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. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.windows.automation.peers; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import system.windows.automation.peers.FrameworkElementAutomationPeer; import system.windows.controls.TabItem; /** * The base .NET class managing System.Windows.Automation.Peers.TabItemWrapperAutomationPeer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Automation.Peers.TabItemWrapperAutomationPeer" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Automation.Peers.TabItemWrapperAutomationPeer</a> */ public class TabItemWrapperAutomationPeer extends FrameworkElementAutomationPeer { /** * Fully assembly qualified name: PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 */ public static final String assemblyFullName = "PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; /** * Assembly name: PresentationFramework */ public static final String assemblyShortName = "PresentationFramework"; /** * Qualified class name: System.Windows.Automation.Peers.TabItemWrapperAutomationPeer */ public static final String className = "System.Windows.Automation.Peers.TabItemWrapperAutomationPeer"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public TabItemWrapperAutomationPeer(java.lang.Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public void setJCOInstance(JCObject instance) { classInstance = instance; super.setJCOInstance(classInstance); } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link TabItemWrapperAutomationPeer}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link TabItemWrapperAutomationPeer} instance * @throws java.lang.Throwable in case of error during cast operation */ public static TabItemWrapperAutomationPeer cast(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new TabItemWrapperAutomationPeer(from.getJCOInstance()); } // Constructors section public TabItemWrapperAutomationPeer() throws Throwable { } public TabItemWrapperAutomationPeer(TabItem owner) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject(owner == null ? null : owner.getJCOInstance())); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Methods section // Properties section // Instance Events section }
/******************************************************************************* * * Pentaho Big Data * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.hbase.shim.spi; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.NavigableMap; import java.util.Properties; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.hadoop.shim.api.Configuration; import org.pentaho.hbase.shim.api.ColumnFilter; import org.pentaho.hbase.shim.api.HBaseValueMeta; public abstract class HBaseConnection { // version key public static final String HBASE_VERSION_KEY = "hbase.defaults.for.version"; // constant connection keys public static final String DEFAULTS_KEY = "hbase.default"; public static final String SITE_KEY = "hbase.site"; public static final String ZOOKEEPER_QUORUM_KEY = "hbase.zookeeper.quorum"; public static final String ZOOKEEPER_PORT_KEY = "hbase.zookeeper.property.clientPort"; //constant for active shim configuration id public static final String ACTIVE_SHIM_VERSION = "ACTIVE_SHIM_VERSION"; // constant table creation option keys (commented out keys don't exist as // options for HColumnDescriptor in 0.90.3) // public static final String COL_DESCRIPTOR_MIN_VERSIONS_KEY = // "col.descriptor.minVersions"; public static final String COL_DESCRIPTOR_MAX_VERSIONS_KEY = "col.descriptor.maxVersions"; // public static final String COL_DESCRIPTOR_KEEP_DELETED_CELLS_KEY = // "col.descriptor.keepDeletedCells"; public static final String COL_DESCRIPTOR_COMPRESSION_KEY = "col.descriptor.compression"; // public static final String COL_DESCRIPTOR_ENCODE_ON_DISK_KEY = // "col.descriptor.encodeOnDisk"; // public static final String COL_DESCRIPTOR_DATA_BLOCK_ENCODING_KEY = // "col.descriptor.dataBlockEncoding"; public static final String COL_DESCRIPTOR_IN_MEMORY_KEY = "col.descriptor.inMemory"; public static final String COL_DESCRIPTOR_BLOCK_CACHE_ENABLED_KEY = "col.descriptor.blockCacheEnabled"; public static final String COL_DESCRIPTOR_BLOCK_SIZE_KEY = "col.descriptor.blockSize"; public static final String COL_DESCRIPTOR_TIME_TO_LIVE_KEY = "col.desciptor.timeToLive"; public static final String COL_DESCRIPTOR_BLOOM_FILTER_KEY = "col.descriptor.bloomFilter"; public static final String COL_DESCRIPTOR_SCOPE_KEY = "col.descriptor.scope"; // constant HTable writing keys public static final String HTABLE_WRITE_BUFFER_SIZE_KEY = "htable.writeBufferSize"; /** * Method for getting a byte utility implementation * * @return * @throws Exception */ public abstract HBaseBytesUtilShim getBytesUtil() throws Exception; /** * Configure the HBase connection using the supplied connection properties * * @param connProps the properties supplying connection details * @param logMessages will hold any log messages generated during the * connection configuration process * @throws Exception if a problem occurs */ public abstract void configureConnection( Properties connProps, List<String> logMessages ) throws Exception; /** * Check if HBase is available and running * * @throws Exception if a problem occurs */ public abstract void checkHBaseAvailable() throws Exception; /** * Gets a list of tables from HBase * * @return a list of tables * @throws Exception if a problem occurs */ public abstract List<String> listTableNames() throws Exception; /** * Returns true if the named table exists in HBase * * @param tableName the name of the table to check * @return true if the table exists * @throws Exception if a problem occurs */ public abstract boolean tableExists( String tableName ) throws Exception; /** * Returns true if the named table is disabled in HBase * * @param tableName the name of the table to check * @return true if the table is disabled * @throws Exception if a problem occurs */ public abstract boolean isTableDisabled( String tableName ) throws Exception; /** * Returns true if the named table is available * * @param tableName the name of the table to check * @return true if the table is available * @throws Exception if a problem occurs */ public abstract boolean isTableAvailable( String tableName ) throws Exception; /** * Disable the named table * * @param tableName the name of the table to disable * @throws Exception if a problem occurs */ public abstract void disableTable( String tableName ) throws Exception; /** * Enable the named table * * @param tableName the name of the table to enable * @throws Exception if a problem occurs */ public abstract void enableTable( String tableName ) throws Exception; /** * Delete the named table from HBase * * @param tableName the name of the table to delete * @throws Exception if a problem occurs */ public abstract void deleteTable( String tableName ) throws Exception; /** * Delete a row from the current target table * * @param rowKey the key of the row to delete * @throws Exception if no target table has been specified yet via * <code>newTargetTable</code> or a problem occurs during the * operation. */ public abstract void executeTargetTableDelete( byte[] rowKey ) throws Exception; /** * Create the named table in HBase * * @param tableName the name of the table to create * @param colFamilyNames a list of column families to create in the new table * @param creationProps options for table creation (see the constant table * creation keys). * @throws Exception a problem occurs */ public abstract void createTable( String tableName, List<String> colFamilyNames, Properties creationProps ) throws Exception; /** * Return a list of column families for the supplied table name * * @param tableName the name of the table to list column families for * @return a list of column families existing in the named table * @throws Exception if a problem occurs */ public abstract List<String> getTableFamiles( String tableName ) throws Exception; /** * Specify a new source table to use for read operations * * @param tableName the name of the table to read from * @throws Exception if a problem occurs */ public abstract void newSourceTable( String tableName ) throws Exception; /** * Returns true if the source table contains a row with the given row key * * @param rowKey the row key to check for * @return true if the source table contains a row with the given row key * @throws Exception if a problem occurs */ public abstract boolean sourceTableRowExists( byte[] rowKey ) throws Exception; /** * Configure a new source table scan. HBase can do a full table scan if no * lower and upper bound are supplied or an open upper-ended scan if a lower * bound but no upper bound is specified. An upper bound with no lower bound * is not allowed. * * @param keyLowerBound the lower bound of the scan range (may be null for no * lower bound) * @param keyUpperBound the upper bound of the scan range (man be null for no * upper bound). * @param cacheSize the size of the scanner cache * @throws Exception no source table has been specified or if a problem occurs */ public abstract void newSourceTableScan( byte[] keyLowerBound, byte[] keyUpperBound, int cacheSize ) throws Exception; /** * Configure a new target table put * * @param key the key of the row that will be inserted into the target table * @param writeToWAL false to disable the write to WAL * @throws Exception if no target table has been specified or if a problem * occurs */ public abstract void newTargetTablePut( byte[] key, boolean writeToWAL ) throws Exception; /** * Returns true if the target table is set up to automatically flush commits * * @return true if the target table is auto flush * @throws Exception if no target table has been specified or if a problem * occurs */ public abstract boolean targetTableIsAutoFlush() throws Exception; /** * Executes the last configured target table push * * @throws Exception if no target table has been specified or if a problem * occurs */ public abstract void executeTargetTablePut() throws Exception; /** * Flush any buffered commits for the target table * * @throws Exception if a problem occurs */ public abstract void flushCommitsTargetTable() throws Exception; /** * Add a column value to the current target table push * * @param columnFamily the column family to add the column to * @param columnName the name of the column to add * @param colNameIsBinary true if the column name is binary * @param colValue the encoded column value to add * @throws Exception if a problem occurs */ public abstract void addColumnToTargetPut( String columnFamily, String columnName, boolean colNameIsBinary, byte[] colValue ) throws Exception; /** * Add a column filter to the list of filters that the scanner will apply to * rows server-side. * * @param cf the column filter to add * @param columnMeta the meta data for the column used in the filter to add * @param vars environment variables * @param matchAny true if the list of filters (if not created yet) should be * "match one" (and false if it should be "match all") * @throws Exception if a problem occurs */ public abstract void addColumnFilterToScan( ColumnFilter cf, HBaseValueMeta columnMeta, VariableSpace vars, boolean matchAny ) throws Exception; /** * Add a specific column to the current source table scan * * @param colFamilyName the name of the column family containing the column to * add * @param colName the name of the column * @param colNameIsBinary true if the column name is binary * @throws Exception if a problem occurs */ public abstract void addColumnToScan( String colFamilyName, String colName, boolean colNameIsBinary ) throws Exception; /** * Execute the current source table scan * * @throws Exception if a problem occurs */ public abstract void executeSourceTableScan() throws Exception; /** * Advance the source table scanner to the next row. * * @return true if the scanner was advanced and the next row is now the * current row; false if there is no next row. * @throws Exception if a source table or source scan has not been specified, * if the scan has not been "executed" or if a problem occurs. */ public abstract boolean resultSetNextRow() throws Exception; /** * Get the row key of the supplied row object. * * @param aRow an HBase row * @return the raw row key * @throws Exception if the supplied object is not of the correct type for the * current instance/version of HBase wrapped by this HBaseAdmin or * if a problem occurs */ public abstract byte[] getRowKey( Object aRow ) throws Exception; /** * Get the row key of the current row from the current source table scan * * @return the raw row key of the current source table row. * @throws Exception if source table or source scan has not been configured, * the source scan has not been "executed" or a problem occurs */ public abstract byte[] getResultSetCurrentRowKey() throws Exception; /** * get the latest version of a column in the supplied row object * * @param aRow an HBase row * @param colFamilyName the name of the column family that the column belongs * to * @param colName the name of the column in question * @param colNameIsBinary true if the column name is binary * @return the raw column value * @throws Exception if the supplied object is not of the correct type for the * current instance/version of HBase wrapped by this HBaseAdmin or * if a problem occurs */ public abstract byte[] getRowColumnLatest( Object aRow, String colFamilyName, String colName, boolean colNameIsBinary ) throws Exception; /** * Checks if the supplied object is a HBase "row" for the instance/version of * HBase wrapped by this HBaseAdmin * * @param rowToCheck an HBase row to check for validity * @return true if the supplied object is an HBase "row" object */ public abstract boolean checkForHBaseRow( Object rowToCheck ); /** * Gets the value of a column from the current row from the source table scan * * @param colFamilyName the name of the column family to look for the column * in * @param colName the name of the column * @param colNameIsBinary true if the column name is binary * * @return the value of the column or null if the column is not in the row (or * in the subset of columns specified in the scan for the current * row). * @throws Exception if the source table or scan isn't configured, the source * scan has not been "executed" or a problem occurs */ public abstract byte[] getResultSetCurrentRowColumnLatest( String colFamilyName, String colName, boolean colNameIsBinary ) throws Exception; /** * Return a map of columns to values from the supplied HBase row object for * the supplied column family name * * @param aRow an HBase row object * @param familyName the column family to return columns from * @return a map of column names to values * @throws Exception if the supplied row object isn't valid with respect to * the instance/versions of HBase wrapped by this HBaseAdmin or a * problem occurs */ public abstract NavigableMap<byte[], byte[]> getRowFamilyMap( Object aRow, String familyName ) throws Exception; /** * Return a map of columns to values from the current source table scan row * for the supplied column family name. * * @param familyName the column family to return rows from * @return a map of column names to values * @throws Exception if the supplied row object isn't valid with respect to * the instance/versions of HBase wrapped by this HBaseAdmin or a * problem occurs */ public abstract NavigableMap<byte[], byte[]> getResultSetCurrentRowFamilyMap( String familyName ) throws Exception; /** * Get a full map for the supplied HBase row (i.e. column family -> column * name -> col value). * * @param aRow an HBase row object * @return a map of column families to columns to column values * @throws Exception if the supplied row object is not valid with respect to * the instance/version of HBase wrapped by this HBaseAdmin or a * problem occurs */ public abstract NavigableMap<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> getRowMap( Object aRow ) throws Exception; /** * Get a full map from the current source table scan row (i.e. column family * -> column name -> col value). * * @return a map of column families to columns to column values * @throws Exception if the source table or scan is not configured, the scan * hasn't been "executed" or a problem occurs */ public abstract NavigableMap<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> getResultSetCurrentRowMap() throws Exception; /** * Close the current source table * * @throws Exception if a problem occurs */ public abstract void closeSourceTable() throws Exception; /** * Close the current source scan's result set * * @throws Exception if a problem occurs */ public abstract void closeSourceResultSet() throws Exception; /** * Specify an new target table to write to * * @param tableName the name of the target table * @param props properties for writing (constant HTable writing keys) * @throws Exception if the connection HBaseAdmin hasn't been configured or a * problem occurs */ public abstract void newTargetTable( String tableName, Properties props ) throws Exception; /** * Close the target table * * @throws Exception if a problem occurs */ public abstract void closeTargetTable() throws Exception; /** * Determines if the object is an * {@link org.apache.hadoop.hbase.io.ImmutableBytesWritable}. * * @return {@code true} if {@code o} is an * {@link org.apache.hadoop.hbase.io.ImmutableBytesWritable}. */ public abstract boolean isImmutableBytesWritable( Object o ); /** * Utility method to covert a string to a URL object. * * @param pathOrURL file or http URL as a string * @return a URL * @throws MalformedURLException if there is a problem with the URL. */ public static URL stringToURL( String pathOrURL ) throws MalformedURLException { URL result = null; if ( !isEmpty( pathOrURL ) ) { if ( pathOrURL.toLowerCase().startsWith( "http://" ) || pathOrURL.toLowerCase().startsWith( "file://" ) ) { result = new URL( pathOrURL ); } else { String c = "file://" + pathOrURL; result = new URL( c ); } } return result; } public static boolean isEmpty( String toCheck ) { return ( toCheck == null || toCheck.length() == 0 ); } /** * Is used to close all backed resources * @throws Exception is thrown in case of any failure */ public abstract void close() throws Exception; public abstract void obtainAuthTokenForJob( Configuration conf ) throws Exception; }
// Copyright 2016 Google 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. /** * ReportJobStatus.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201608; public class ReportJobStatus implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected ReportJobStatus(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _COMPLETED = "COMPLETED"; public static final java.lang.String _IN_PROGRESS = "IN_PROGRESS"; public static final java.lang.String _FAILED = "FAILED"; public static final ReportJobStatus COMPLETED = new ReportJobStatus(_COMPLETED); public static final ReportJobStatus IN_PROGRESS = new ReportJobStatus(_IN_PROGRESS); public static final ReportJobStatus FAILED = new ReportJobStatus(_FAILED); public java.lang.String getValue() { return _value_;} public static ReportJobStatus fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { ReportJobStatus enumeration = (ReportJobStatus) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static ReportJobStatus fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} 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.EnumSerializer( _javaType, _xmlType); } 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.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(ReportJobStatus.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201608", "ReportJobStatus")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
package io.dkozak.jobscheduler.mainview; import io.dkozak.jobscheduler.personView.PersonView; import io.dkozak.jobscheduler.services.MessageService; import io.dkozak.jobscheduler.services.database.dao.DaoManager; import io.dkozak.jobscheduler.taskview.TaskView; import io.dkozak.jobscheduler.utils.NotifiablePresenter; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Tab; import javafx.scene.text.Text; import lombok.extern.log4j.Log4j; import javax.inject.Inject; import java.net.URL; import java.util.ResourceBundle; @Log4j public class MainPresenter implements Initializable, NotifiablePresenter { @FXML private Tab peopleTab; @FXML private Tab tasksTab; @FXML private Text infoText; @Inject private DaoManager daoManager; @Inject private MessageService messageService; @Override public void initialize(URL location, ResourceBundle resources) { log.info("initializing main view"); daoManager.getPrepareDatabaseTask() .setOnSucceeded(event -> showInfoMessage("Database initialized successfully")); daoManager.getPrepareDatabaseTask() .exceptionProperty() .addListener((observable, oldValue, newValue) -> showErrorMessage("Database initialization failed :" + newValue.getMessage())); PersonView personView = new PersonView(); peopleTab.setContent(personView.getView()); TaskView taskView = new TaskView(); tasksTab.setContent(taskView.getView()); messageService.setMessageDestination(infoText); } @Override public void showInfoMessage(String message) { log.info("Info message: " + message); messageService.infoMessage(message); } @Override public void showErrorMessage(String message) { log.error("Error message: " + message); messageService.errorMessage(message); } }
package org.mvel2.jsr223; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.script.SimpleBindings; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MvelScriptEngineTest { @Test public void testScriptEngine() throws ScriptException { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); scriptEngineManager.registerEngineName( "mvel", new MvelScriptEngineFactory()); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("mvel"); SimpleBindings simpleBindings = new SimpleBindings(); simpleBindings.put("a", 1); simpleBindings.put("b", 2); int c = (Integer) scriptEngine.eval("a + b", simpleBindings); assertEquals(c, 3); } @Test public void testScriptEngineCompiledScript() throws ScriptException { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); scriptEngineManager.registerEngineName( "mvel", new MvelScriptEngineFactory()); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("mvel"); SimpleBindings simpleBindings = new SimpleBindings(); simpleBindings.put("a", 1); simpleBindings.put("b", 2); Compilable compilableScriptEngine = (Compilable) scriptEngine; CompiledScript compiledScript = compilableScriptEngine.compile("a+ b"); int c = (Integer) compiledScript.eval(simpleBindings); assertEquals(c, 3); } }
package hashindex; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import btree.AddFileEntryException; import btree.GetFileEntryException; import global.AttrType; import global.PageId; import global.SystemDefs; public class HashUtils { public final static int getKeyLength(HashKey key) throws IOException { switch (key.type) { case AttrType.attrInteger: return 4; case AttrType.attrReal: return 4; case AttrType.attrString: OutputStream out = new ByteArrayOutputStream(); DataOutputStream outstr = new DataOutputStream(out); outstr.writeUTF(((String) key.value)); return outstr.size(); default: throw new IOException("key types do not match"); } } public static byte[] intToBytes(int x) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(bos); out.writeInt(x); out.close(); byte[] int_bytes = bos.toByteArray(); bos.close(); return int_bytes; } //util function to debug log stuff // if no debug log wanted, comment the print statement public static void log(String str) { if(false)System.out.println(str); //comment this line to disable logs return; } public static void printPinnedPages() { System.out.println(Thread.currentThread().getStackTrace()[2].getMethodName()+"pin: "+(SystemDefs.JavabaseBM.getNumBuffers()- SystemDefs.JavabaseBM.getNumUnpinnedBuffers())); } // static methods /////// public static PageId get_file_entry(String filename) throws GetFileEntryException { try { return SystemDefs.JavabaseDB.get_file_entry(filename); } catch (Exception e) { e.printStackTrace(); throw new GetFileEntryException(e, ""); } } public static void add_file_entry(String fileName, PageId pageno) throws AddFileEntryException { try { SystemDefs.JavabaseDB.add_file_entry(fileName, pageno); } catch (Exception e) { e.printStackTrace(); throw new AddFileEntryException(e, ""); } } /** * A wrapper to store 2 values<br> * useful if we want to return 2 values from a function * <pre>{@code * Pair<String,Integer> pair = new Pair<>(); * pair.first="hello"; * pair.second=1; * return pair; * }</pre> * @param <M> * @param <N> */ public static class Pair<M,N> { public M first; public N second; } }
/* * Copyright (c) 2019 VMware Inc. All Rights Reserved. * SPDX-License-Identifier: MIT * * 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 (including the next paragraph) shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.vmware.ddlog.ir; import com.vmware.ddlog.util.Linq; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class DDlogProgram extends DDlogNode { // We are missing some of the fields that can never be generated from SQL public final List<DDlogTypeDef> typedefs; public final List<DDlogFunction> functions; public final List<DDlogRelationDeclaration> relations; public final List<DDlogRule> rules; public final List<DDlogImport> imports; DDlogProgram(List<DDlogTypeDef> typedefs, List<DDlogFunction> functions, List<DDlogRelationDeclaration> relations, List<DDlogRule> rules, List<DDlogImport> imports) { super(null); this.typedefs = typedefs; this.functions = functions; this.relations = relations; this.rules = rules; this.imports = imports; } public DDlogProgram() { this(new ArrayList<DDlogTypeDef>(), new ArrayList<DDlogFunction>(), new ArrayList<DDlogRelationDeclaration>(), new ArrayList<DDlogRule>(), new ArrayList<DDlogImport>()); } @Override public String toString() { String[] parts = new String[5]; parts[0] = String.join("\n", Linq.map(this.imports, DDlogImport::toString)) + "\n"; parts[1] = String.join("\n", Linq.map(this.typedefs, DDlogTypeDef::toString)); parts[2] = String.join("\n", Linq.map(this.functions, DDlogFunction::toString)); parts[3] = String.join("\n", Linq.map(this.relations, DDlogRelationDeclaration::toString)); parts[4] = String.join("\n", Linq.map(this.rules, DDlogRule::toString)); return String.join("\n", parts); } public boolean compare(DDlogProgram other, IComparePolicy policy) { if (this.typedefs.size() != other.typedefs.size()) return false; if (this.functions.size() != other.functions.size()) return false; if (this.relations.size() != other.relations.size()) return false; if (this.rules.size() != other.rules.size()) return false; if (this.imports.size() != other.imports.size()) return false; for (int i = 0; i < this.typedefs.size(); i++) if (!this.typedefs.get(i).compare(other.typedefs.get(i), policy)) return false; for (int i = 0; i < this.functions.size(); i++) if (!this.functions.get(i).compare(other.functions.get(i), policy)) return false; for (int i = 0; i < this.relations.size(); i++) if (!this.relations.get(i).compare(other.relations.get(i), policy)) return false; for (int i = 0; i < this.rules.size(); i++) if (!this.rules.get(i).compare(other.rules.get(i), policy)) return false; for (int i = 0; i < this.imports.size(); i++) if (!this.imports.get(i).compare(other.imports.get(i), policy)) return false; return true; } public void toFile(String filename) throws FileNotFoundException { try (PrintWriter out = new PrintWriter(filename)) { out.println(this.toString()); } } }
/* * Copyright (C) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.training.dataanalyst.sandiego; import java.util.ArrayList; import java.util.List; import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.io.PubsubIO; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.windowing.SlidingWindows; import org.apache.beam.sdk.transforms.windowing.Window; import org.apache.beam.sdk.values.PCollection; import org.joda.time.Duration; import com.google.api.services.bigquery.model.TableFieldSchema; import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.TableSchema; /** * A dataflow pipeline that pulls from Pub/Sub and writes to BigQuery * * @author vlakshmanan * */ public class CurrentConditions { public static interface MyOptions extends DataflowPipelineOptions { } @SuppressWarnings("serial") public static void main(String[] args) { MyOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(MyOptions.class); options.setStreaming(true); Pipeline p = Pipeline.create(options); String topic = "projects/" + options.getProject() + "/topics/sandiego"; String currConditionsTable = options.getProject() + ":demos.current_conditions"; // Build the table schema for the output table. List<TableFieldSchema> fields = new ArrayList<>(); fields.add(new TableFieldSchema().setName("timestamp").setType("TIMESTAMP")); fields.add(new TableFieldSchema().setName("latitude").setType("FLOAT")); fields.add(new TableFieldSchema().setName("longitude").setType("FLOAT")); fields.add(new TableFieldSchema().setName("highway").setType("STRING")); fields.add(new TableFieldSchema().setName("direction").setType("STRING")); fields.add(new TableFieldSchema().setName("lane").setType("INTEGER")); fields.add(new TableFieldSchema().setName("speed").setType("FLOAT")); fields.add(new TableFieldSchema().setName("sensorId").setType("STRING")); TableSchema schema = new TableSchema().setFields(fields); PCollection<LaneInfo> laneInfo = p // .apply("GetMessages", PubsubIO.<String>read() .topic(topic) .withCoder(StringUtf8Coder.of())) // .apply("TimeWindow", Window.into(SlidingWindows// .of(Duration.standardSeconds(300))// .every(Duration.standardSeconds(60)))) // .apply("ExtractData", ParDo.of(new DoFn<String, LaneInfo>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { String line = c.element(); c.output(LaneInfo.newLaneInfo(line)); } })); laneInfo.apply("ToBQRow", ParDo.of(new DoFn<LaneInfo, TableRow>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { TableRow row = new TableRow(); LaneInfo info = c.element(); row.set("timestamp", info.getTimestamp()); row.set("latitude", info.getLatitude()); row.set("longitude", info.getLongitude()); row.set("highway", info.getHighway()); row.set("direction", info.getDirection()); row.set("lane", info.getLane()); row.set("speed", info.getSpeed()); row.set("sensorId", info.getSensorKey()); c.output(row); } })) // .apply(BigQueryIO.Write.to(currConditionsTable)// .withSchema(schema)// .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND) .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)); p.run(); } }
package com.technology.oracle.scheduler.batch.shared.service; import com.google.gwt.user.client.rpc.AsyncCallback; import com.technology.jep.jepria.shared.record.JepRecord; import com.technology.oracle.scheduler.main.shared.service.SchedulerServiceAsync; public interface BatchServiceAsync extends SchedulerServiceAsync { void activateBatch(Integer batchId, String dataSource, AsyncCallback<JepRecord> callback); void deactivateBatch(Integer batchId, String dataSource, AsyncCallback<JepRecord> callback); void executeBatch(Integer batchId, String dataSource, AsyncCallback<JepRecord> callback); void abortBatch(Integer batchId, String dataSource, AsyncCallback<JepRecord> callback); }
/* * Copyright (c) Steven P. Goldsmith. All rights reserved. */ package com.codeferm.periphery.demo; import com.codeferm.periphery.I2c; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; /** * ADXL345 3-Axis, ±2 g/±4 g/±8 g/±16 g digital accelerometer example. I'm using I2C to communicate with the ADXL345 although SPI is * supported as well. * * @author Steven P. Goldsmith * @version 1.0.0 * @since 1.0.0 */ @Command(name = "adxl345", mixinStandardHelpOptions = true, version = "adxl345 1.0.0", description = "ADXL345 3-Axis, ±2 g/±4 g/±8 g/±16 g digital accelerometer example.") public class Adxl345 implements Callable<Integer> { /** * Logger. */ private final org.apache.logging.log4j.Logger logger = LogManager.getLogger(Adxl345.class); /** * Device option. */ @Option(names = {"-d", "--device"}, description = "I2C device defaults to /dev/i2c-0") private String device = "/dev/i2c-0"; /** * Address option. */ @Option(names = {"-a", "--address"}, description = "Address defaults to 0x53") private short address = 0x53; /** * Main parsing, error handling and handling user requests for usage help or version help are done with one line of code. * * @param args Argument list. */ public static void main(String... args) { var exitCode = new CommandLine(new Adxl345()).execute(args); System.exit(exitCode); } /** * Get data range setting. * * Register 0x31 -- DATA_FORMAT (Read/Write) * * These bits set the g range as described below. * * <pre> * Range Setting * | Setting | g Range | Value | * | 00 | +/- 2 g | 0 | * | 01 | +/- 4 g | 1 | * | 10 | +/- 8 g | 2 | * | 11 | +/- 16 g | 3 | * </pre> * * @param handle I2C file handle. * @param addr Address. * @return Range. */ public short getRange(final long handle, final short addr) { final var buf = new short[1]; I2c.i2cReadReg(handle, addr, (short) 0x31, buf); return (short) (buf[0] & 0x03); } /** * Set data range setting. Read the data format register to preserve bits. Update the data rate, make sure that the FULL-RES bit * is enabled for range scaling. * * Register 0x31 -- DATA_FORMAT (Read/Write) * * These bits set the g range as described below. * * <pre> * g Range Setting * | Setting | g Range | Value | * | 00 | +/- 2 g | 0 | * | 01 | +/- 4 g | 1 | * | 10 | +/- 8 g | 2 | * | 11 | +/- 16 g | 3 | * </pre> * * @param handle I2C file handle. * @param addr Address. * @param value Range. */ public void setRange(final long handle, final short addr, final short value) { // 0x08 sets fill resolution bit to enabled final var buf = new short[1]; I2c.i2cReadReg(handle, addr, (short) 0x31, buf); I2c.i2cWriteReg(handle, addr, (short) 0x31, (short) (((buf[0] & ~0x0f) | value) | 0x08)); } /** * Read full resolution mode setting. * * Register 0x31 -- DATA_FORMAT (Read/Write) * * When this bit is set to a value of 1, the device is in full resolution mode, where the output resolution increases with the g * range set by the range bits to maintain a 4 mg/LSB scale factor. When the FULL_RES bit is set to 0, the device is in 10-bit * mode, and the range bits determine the maximum g range and scale factor. * * @param handle I2C file handle. * @param addr Address. * @return Full resolution enabled setting */ public boolean getFullResolution(final long handle, final short addr) { final var buf = new short[1]; I2c.i2cReadReg(handle, addr, (short) 0x31, buf); return (short) (buf[0] & 0x08) == (short) 0x08; } /** * Get the device bandwidth rate. * * Register 0x2C -- BW_RATE (Read/Write) * * These bits select the device bandwidth and output data rate. The default value is 0x0A, which translates to a 100 Hz output * data rate. An output data rate should be selected that is appropriate for the communication protocol and frequency selected. * Selecting too high of an output data rate with a low communication speed results in samples being discarded. * * <pre> * Typical Current Consumption vs. Data Rate * Output Data Rate (Hz) | Bandwidth (Hz) | Rate Code | Value | Idd (uA) * 3200 | 1600 | 1111 | 0xF or 15 | 140 * 1600 | 800 | 1110 | 0xE or 14 | 90 * 800 | 400 | 1101 | 0xD or 13 | 140 * 400 | 200 | 1100 | 0xC or 12 | 140 * 200 | 100 | 1011 | 0xB or 11 | 140 * 100 | 50 | 1010 | 0xA or 10 | 140 * 50 | 25 | 1001 | 0x9 or 9 | 90 * 25 | 12.5 | 1000 | 0x8 or 8 | 60 * 12.5 | 6.25 | 0111 | 0x7 or 7 | 50 * 6.25 | 3.13 | 0110 | 0x6 or 6 | 45 * 3.13 | 1.56 | 0101 | 0x5 or 5 | 40 * 1.56 | 0.78 | 0100 | 0x4 or 4 | 34 * 0.78 | 0.39 | 0011 | 0x3 or 3 | 23 * 0.39 | 0.20 | 0010 | 0x2 or 2 | 23 * 0.20 | 0.10 | 0001 | 0x1 or 1 | 23 * 0.10 | 0.05 | 0000 | 0x0 or 0 | 23 * </pre> * * @param handle I2C file handle. * @param addr Address. * @return Range. */ public short getDataRate(final long handle, final short addr) { final var buf = new short[1]; I2c.i2cReadReg(handle, addr, (short) 0x2c, buf); return (short) (buf[0] & 0x0f); } /** * Set the device bandwidth rate. * * Register 0x2C -- BW_RATE (Read/Write) * * These bits select the device bandwidth and output data rate. The default value is 0x0A, which translates to a 100 Hz output * data rate. An output data rate should be selected that is appropriate for the communication protocol and frequency selected. * Selecting too high of an output data rate with a low communication speed results in samples being discarded. Note: The * LOW_POWER bits are currently ignored, we always keep the device in 'normal' mode. * * <pre> * Typical Current Consumption vs. Data Rate * Output Data Rate (Hz) | Bandwidth (Hz) | Rate Code | Value | Idd (uA) * 3200 | 1600 | 1111 | 0xF or 15 | 140 * 1600 | 800 | 1110 | 0xE or 14 | 90 * 800 | 400 | 1101 | 0xD or 13 | 140 * 400 | 200 | 1100 | 0xC or 12 | 140 * 200 | 100 | 1011 | 0xB or 11 | 140 * 100 | 50 | 1010 | 0xA or 10 | 140 * 50 | 25 | 1001 | 0x9 or 9 | 90 * 25 | 12.5 | 1000 | 0x8 or 8 | 60 * 12.5 | 6.25 | 0111 | 0x7 or 7 | 50 * 6.25 | 3.13 | 0110 | 0x6 or 6 | 45 * 3.13 | 1.56 | 0101 | 0x5 or 5 | 40 * 1.56 | 0.78 | 0100 | 0x4 or 4 | 34 * 0.78 | 0.39 | 0011 | 0x3 or 3 | 23 * 0.39 | 0.20 | 0010 | 0x2 or 2 | 23 * 0.20 | 0.10 | 0001 | 0x1 or 1 | 23 * 0.10 | 0.05 | 0000 | 0x0 or 0 | 23 * </pre> * * @param handle I2C file handle. * @param addr Address. * @param value Data rate. */ public void setDataRate(final long handle, final short addr, final short value) { I2c.i2cWriteReg(handle, addr, (short) 0x2c, (short) (value & 0x0f)); } /** * Convert low and high bytes to 10-bit integer. * * @param lowByte Low byte from register. * @param highByte High byte from register. * @return Integer value composed of low and high bytes. */ public int bytesToInt(final byte lowByte, final byte highByte) { // Convert the data to 10-bits var value = ((highByte & 0x03) * 256 + (lowByte & 0xff)); if (value > 511) { value -= 1024; } return value; } /** * Retrieve x, y, z 10 bit data in 6 bytes. * * @param handle I2C file handle. * @param addr Address. * @return Map of Integers keyed by x, y, z. */ public Map<String, Integer> read(final long handle, final short addr) { // Read all 6 registers at once final var data = new byte[6]; I2c.i2cReadReg(handle, addr, (short) 0x32, data); final Map<String, Integer> map = new HashMap<>(); map.put("x", bytesToInt(data[0], data[1])); map.put("y", bytesToInt(data[2], data[3])); map.put("z", bytesToInt(data[4], data[5])); return map; } /** * Determines the scaling factor of raw values to obtain Gs. * * The scale factor changes dependent on other device settings, so be sure to get the scaling factor after writing desired * settings. * * @param range Use getRange. * @param resolution Use getFullResolution. * @return Raw value scaling factor. */ public float getScalingFactor(final short range, final boolean resolution) { final var bits = resolution ? 10 + range : 10; final var gRange = 4f * (float) Math.pow(2, range); final var bitRange = (float) Math.pow(2, bits); return gRange / bitRange; } /** * Calculate scaling value. * * @param value raw value. * @param scalingFactor Use getScalingFactor. * @return Scaled value. */ public float scaling(final int value, final float scalingFactor) { return value * scalingFactor * 9.8f; } /** * Main program. * * @return Exit code. * @throws InterruptedException Possible exception. */ @Override public Integer call() throws InterruptedException { var exitCode = 0; try (final var i2c = new I2c(device)) { // Check device ID final var buf = new short[1]; I2c.i2cReadReg(i2c.getHandle(), address, (short) 0x00, buf); if (buf[0] == 0xe5) { // Enable the accelerometer I2c.i2cWriteReg(i2c.getHandle(), address, (short) 0x2d, (short) 0x08); // +/- 2g setRange(i2c.getHandle(), address, (short) 0x00); // 100 Hz setDataRate(i2c.getHandle(), address, (short) 0x0a); // Save off range and data rate final var range = getRange(i2c.getHandle(), address); final var dataRate = getDataRate(i2c.getHandle(), address); final var scalingFactor = getScalingFactor(range, getFullResolution(i2c.getHandle(), address)); logger.info(String.format("Range = %d, data rate = %d, scaling factor = %f", range, dataRate, scalingFactor)); for (var i = 0; i < 100; i++) { final var data = read(i2c.getHandle(), address); logger.info(String.format("x: %+5.2f, y: %+5.2f, z: %+5.2f", scaling(data.get("x"), scalingFactor), scaling( data.get("y"), scalingFactor), scaling(data.get("z"), scalingFactor))); TimeUnit.MILLISECONDS.sleep(500); } } else { logger.error("Not ADXL345?"); } } catch (RuntimeException e) { logger.error(e.getMessage()); exitCode = 1; } return exitCode; } }
// Copyright 2019 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 // // 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.google.api.ads.admanager.jaxws.v201905; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * * A {@code Package} represents a group of proposal line items which will be sold together. * * * <p>Java class for Package complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Package"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="proposalId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="productPackageId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="rateCardId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="comments" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="status" type="{https://www.google.com/apis/ads/publisher/v201905}PackageStatus" minOccurs="0"/> * &lt;element name="startDateTime" type="{https://www.google.com/apis/ads/publisher/v201905}DateTime" minOccurs="0"/> * &lt;element name="endDateTime" type="{https://www.google.com/apis/ads/publisher/v201905}DateTime" minOccurs="0"/> * &lt;element name="lastModifiedDateTime" type="{https://www.google.com/apis/ads/publisher/v201905}DateTime" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Package", propOrder = { "id", "proposalId", "productPackageId", "rateCardId", "name", "comments", "status", "startDateTime", "endDateTime", "lastModifiedDateTime" }) public class Package { protected Long id; protected Long proposalId; protected Long productPackageId; protected Long rateCardId; protected String name; protected String comments; @XmlSchemaType(name = "string") protected PackageStatus status; protected DateTime startDateTime; protected DateTime endDateTime; protected DateTime lastModifiedDateTime; /** * Gets the value of the id property. * * @return * possible object is * {@link Long } * */ public Long getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Long } * */ public void setId(Long value) { this.id = value; } /** * Gets the value of the proposalId property. * * @return * possible object is * {@link Long } * */ public Long getProposalId() { return proposalId; } /** * Sets the value of the proposalId property. * * @param value * allowed object is * {@link Long } * */ public void setProposalId(Long value) { this.proposalId = value; } /** * Gets the value of the productPackageId property. * * @return * possible object is * {@link Long } * */ public Long getProductPackageId() { return productPackageId; } /** * Sets the value of the productPackageId property. * * @param value * allowed object is * {@link Long } * */ public void setProductPackageId(Long value) { this.productPackageId = value; } /** * Gets the value of the rateCardId property. * * @return * possible object is * {@link Long } * */ public Long getRateCardId() { return rateCardId; } /** * Sets the value of the rateCardId property. * * @param value * allowed object is * {@link Long } * */ public void setRateCardId(Long value) { this.rateCardId = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the comments property. * * @return * possible object is * {@link String } * */ public String getComments() { return comments; } /** * Sets the value of the comments property. * * @param value * allowed object is * {@link String } * */ public void setComments(String value) { this.comments = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link PackageStatus } * */ public PackageStatus getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link PackageStatus } * */ public void setStatus(PackageStatus value) { this.status = value; } /** * Gets the value of the startDateTime property. * * @return * possible object is * {@link DateTime } * */ public DateTime getStartDateTime() { return startDateTime; } /** * Sets the value of the startDateTime property. * * @param value * allowed object is * {@link DateTime } * */ public void setStartDateTime(DateTime value) { this.startDateTime = value; } /** * Gets the value of the endDateTime property. * * @return * possible object is * {@link DateTime } * */ public DateTime getEndDateTime() { return endDateTime; } /** * Sets the value of the endDateTime property. * * @param value * allowed object is * {@link DateTime } * */ public void setEndDateTime(DateTime value) { this.endDateTime = value; } /** * Gets the value of the lastModifiedDateTime property. * * @return * possible object is * {@link DateTime } * */ public DateTime getLastModifiedDateTime() { return lastModifiedDateTime; } /** * Sets the value of the lastModifiedDateTime property. * * @param value * allowed object is * {@link DateTime } * */ public void setLastModifiedDateTime(DateTime value) { this.lastModifiedDateTime = value; } }
package cn.leancloud.logging; import cn.leancloud.AVLogger; public abstract class InternalLogger { private AVLogger.Level level = AVLogger.Level.INFO; public void setLevel(AVLogger.Level level) { this.level = level; } protected abstract void internalWriteLog(AVLogger.Level level, String msg); protected abstract void internalWriteLog(AVLogger.Level level, String msg, Throwable tr); protected abstract void internalWriteLog(AVLogger.Level level, Throwable tr); public void writeLog(AVLogger.Level level, String msg) { internalWriteLog(level, msg); } public void writeLog(AVLogger.Level level, String msg, Throwable tr) { internalWriteLog(level, msg, tr); } public void writeLog(AVLogger.Level level, Throwable tr) { internalWriteLog(level, tr); } }
/* * @lc app=leetcode id=387 lang=java * * [387] First Unique Character in a String * * https://leetcode.com/problems/first-unique-character-in-a-string/description/ * * algorithms * Easy (50.17%) * Likes: 1055 * Dislikes: 80 * Total Accepted: 283.3K * Total Submissions: 563.2K * Testcase Example: '"leetcode"' * * * Given a string, find the first non-repeating character in it and return it's * index. If it doesn't exist, return -1. * * Examples: * * s = "leetcode" * return 0. * * s = "loveleetcode", * return 2. * * * * * Note: You may assume the string contain only lowercase letters. * */ class Solution { public int firstUniqChar(String s) { int[] result = new int[26]; Arrays.fill(result, 0); for (char t : s.toCharArray()) { result[t - 'a']++; } for (int i = 0; i < s.length(); i++) { if (result[s.charAt(i) - 'a'] == 1) { return i; } } return -1; } }
/** * Copyright 2013-2019 Valery Silaev (http://vsilaev.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.javaflow.providers.asm3; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Type; import org.apache.commons.javaflow.spi.ClassMatcher; import org.apache.commons.javaflow.spi.ResourceLoader; class IContinuableClassInfoResolver implements ContinuableClassInfoResolver { private final Map<String, IContinuableClassInfo> visitedClasses = new HashMap<String, IContinuableClassInfo>(); private final Set<String> processedAnnotations = new HashSet<String>(); private final Set<String> continuableAnnotations = new HashSet<String>(); private final Set<String> refreshClasses = new HashSet<String>(); private final ResourceLoader resourceLoader; private final SharedContinuableClassInfos cciShared; IContinuableClassInfoResolver(ResourceLoader resourceLoader, SharedContinuableClassInfos cciShared) { this.resourceLoader = resourceLoader; this.cciShared = cciShared; } public IContinuableClassInfo resolve(String classInternalName) throws IOException { IContinuableClassInfo classInfo = getResolved(classInternalName); if (classInfo == null) { InputStream classBytes = resourceLoader.getResourceAsStream(classInternalName + ".class"); try { return resolveContinuableClassInfo(classInternalName, new ClassReader(classBytes)); } finally { if (null != classBytes) { try { classBytes.close(); } catch (IOException exIgnore) {} } } } else { return unmask(classInfo); } } public boolean isContinuableAnnotation(String annotationClassDescriptor) { switch (getAnnotationProcessingState(annotationClassDescriptor)) { case SUPPORTED: return true; case UNSUPPORTED: return false; case UNKNON: markProcessedAnnotation(annotationClassDescriptor); final Type type = Type.getType(annotationClassDescriptor); try { InputStream annotationBytes= resourceLoader.getResourceAsStream(type.getInternalName() + ".class"); try { return resolveContinuableAnnotation(annotationClassDescriptor, new ClassReader(annotationBytes)); } finally { if (null != annotationBytes) { try { annotationBytes.close(); } catch (IOException exIgnore) {} } } } catch (IOException ex) { throw new RuntimeException(ex); } default: throw new RuntimeException("Unknown annotation kind"); } } public void release() { cciShared.mergeWith(visitedClasses, processedAnnotations, continuableAnnotations); } public void reset(Collection<String> classNames) { visitedClasses.keySet().removeAll(classNames); refreshClasses.addAll(classNames); } IContinuableClassInfo resolve(String classInternalName, byte[] classBytes) { IContinuableClassInfo classInfo = getResolved(classInternalName); if (classInfo == null) { return resolveContinuableClassInfo(classInternalName, new ClassReader(classBytes)); } else { return unmask(classInfo); } } ClassMatcher veto() { return cciShared.veto(); } private IContinuableClassInfo getResolved(String classInternalName) { if (refreshClasses.contains(classInternalName)) { return null; } IContinuableClassInfo result; result = visitedClasses.get(classInternalName); if (null != result) { return result; } result = cciShared.getResolved(classInternalName); if (null != result) { return result; } return null; } private IContinuableClassInfo resolveContinuableClassInfo(String classInternalName, ClassReader reader) { MaybeContinuableClassVisitor maybeContinuableClassVisitor = new MaybeContinuableClassVisitor(this); reader.accept(maybeContinuableClassVisitor, ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG); IContinuableClassInfo classInfo; if (maybeContinuableClassVisitor.isContinuable()) { classInfo = new IContinuableClassInfo( maybeContinuableClassVisitor.isProcessed(), maybeContinuableClassVisitor.continuableMethods ); } else { classInfo = UNSUPPORTED_CLASS_INFO; } visitedClasses.put(classInternalName, classInfo); refreshClasses.remove(classInternalName); return unmask(classInfo); } private boolean resolveContinuableAnnotation(String annotationClassDescriptor, ClassReader reader) { MaybeContinuableAnnotationVisitor maybeContinuableAnnotationVisitor = new MaybeContinuableAnnotationVisitor(this); reader.accept( maybeContinuableAnnotationVisitor, ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG ); if (maybeContinuableAnnotationVisitor.isContinuable()) { markContinuableAnnotation(annotationClassDescriptor); return true; } else { return false; } } private AnnotationProcessingState getAnnotationProcessingState(String annotationClassDescriptor) { // Check already resolved shared state first if (cciShared.isContinuableAnnotation(annotationClassDescriptor)) { return AnnotationProcessingState.SUPPORTED; } else if (cciShared.isProcessedAnnotation(annotationClassDescriptor)) { return AnnotationProcessingState.UNSUPPORTED; } // Now check own state if (continuableAnnotations.contains(annotationClassDescriptor)) return AnnotationProcessingState.SUPPORTED; else if (processedAnnotations.contains(annotationClassDescriptor)) return AnnotationProcessingState.UNSUPPORTED; else return AnnotationProcessingState.UNKNON; } private void markProcessedAnnotation(String annotationClassDescriptor) { processedAnnotations.add(annotationClassDescriptor); } private void markContinuableAnnotation(String annotationClassDescriptor) { markProcessedAnnotation(annotationClassDescriptor); continuableAnnotations.add(annotationClassDescriptor); } private static IContinuableClassInfo unmask(IContinuableClassInfo classInfo) { return classInfo == UNSUPPORTED_CLASS_INFO ? null : classInfo; } private static final IContinuableClassInfo UNSUPPORTED_CLASS_INFO = new IContinuableClassInfo(true, Collections.<String>emptySet()); private static enum AnnotationProcessingState { UNKNON, UNSUPPORTED, SUPPORTED; } }
/* This file is part of the iText (R) project. Copyright (c) 1998-2020 iText Group NV Authors: iText Software. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation with the addition of the following permission added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS This program 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, see http://www.gnu.org/licenses or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA, 02110-1301 USA, or download the license from the following URL: http://itextpdf.com/terms-of-use/ The interactive user interfaces in modified source and object code versions of this program must display Appropriate Legal Notices, as required under Section 5 of the GNU Affero General Public License. In accordance with Section 7(b) of the GNU Affero General Public License, a covered work must retain the producer line in every PDF that is created or manipulated using iText. You can be released from the requirements of the license by purchasing a commercial license. Buying such a license is mandatory as soon as you develop commercial activities involving the iText software without disclosing the source code of your own applications. These activities include: offering paid services to customers as an ASP, serving PDFs on the fly in a web application, shipping iText with a closed source product. For more information, please contact iText Software Corp. at this address: sales@itextpdf.com */ package com.itextpdf.html2pdf.css.w3c.css21.text; import com.itextpdf.html2pdf.css.w3c.W3CCssAhemFontTest; public class WhiteSpaceProcessing009Test extends W3CCssAhemFontTest { @Override protected String getHtmlFileName() { return "white-space-processing-009.xht"; } }
/* w * Copyright (c) 2020 Martin Koster * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package com.github.actionfx.bookstore.spring.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.github.actionfx.core.ActionFX; import com.github.actionfx.core.annotation.AFXApplication; import javafx.application.Application; import javafx.stage.Stage; /** * Main entry point in the sample application. * * @author koster * */ @SpringBootApplication public class BookstoreAppWithSpringBeanContainer { public static void main(final String[] argv) { ActionFX.builder().configurationClass(SampleActionFXApplication.class).build(); Application.launch(SampleActionFXApplication.class); } @AFXApplication(mainViewId = "mainView", scanPackage = "com.github.actionfx.bookstore.controller") public static class SampleActionFXApplication extends Application { @Override public void init() throws Exception { SpringApplication.run(BookstoreAppWithSpringBeanContainer.class); } @Override public void start(final Stage primaryStage) throws Exception { ActionFX.getInstance().showMainView(primaryStage); } } }
package com.atguigu.gmall.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication //@EnableDiscoveryClient public class GmallGatewayApplication { public static void main(String[] args) { SpringApplication.run(GmallGatewayApplication.class, args); } }
/* * 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.adb.transform.v20190315; import java.util.ArrayList; import java.util.List; import com.aliyuncs.adb.model.v20190315.DescribeElasticDailyPlanResponse; import com.aliyuncs.adb.model.v20190315.DescribeElasticDailyPlanResponse.ElasticDailyPlanInfo; import com.aliyuncs.transform.UnmarshallerContext; public class DescribeElasticDailyPlanResponseUnmarshaller { public static DescribeElasticDailyPlanResponse unmarshall(DescribeElasticDailyPlanResponse describeElasticDailyPlanResponse, UnmarshallerContext _ctx) { describeElasticDailyPlanResponse.setRequestId(_ctx.stringValue("DescribeElasticDailyPlanResponse.RequestId")); List<ElasticDailyPlanInfo> elasticDailyPlanList = new ArrayList<ElasticDailyPlanInfo>(); for (int i = 0; i < _ctx.lengthValue("DescribeElasticDailyPlanResponse.ElasticDailyPlanList.Length"); i++) { ElasticDailyPlanInfo elasticDailyPlanInfo = new ElasticDailyPlanInfo(); elasticDailyPlanInfo.setPlanName(_ctx.stringValue("DescribeElasticDailyPlanResponse.ElasticDailyPlanList["+ i +"].PlanName")); elasticDailyPlanInfo.setResourcePoolName(_ctx.stringValue("DescribeElasticDailyPlanResponse.ElasticDailyPlanList["+ i +"].ResourcePoolName")); elasticDailyPlanInfo.setElasticNodeNum(_ctx.integerValue("DescribeElasticDailyPlanResponse.ElasticDailyPlanList["+ i +"].ElasticNodeNum")); elasticDailyPlanInfo.setPlanStartTs(_ctx.stringValue("DescribeElasticDailyPlanResponse.ElasticDailyPlanList["+ i +"].PlanStartTs")); elasticDailyPlanInfo.setPlanEndTs(_ctx.stringValue("DescribeElasticDailyPlanResponse.ElasticDailyPlanList["+ i +"].PlanEndTs")); elasticDailyPlanInfo.setStartTs(_ctx.stringValue("DescribeElasticDailyPlanResponse.ElasticDailyPlanList["+ i +"].StartTs")); elasticDailyPlanInfo.setEndTs(_ctx.stringValue("DescribeElasticDailyPlanResponse.ElasticDailyPlanList["+ i +"].EndTs")); elasticDailyPlanInfo.setDay(_ctx.stringValue("DescribeElasticDailyPlanResponse.ElasticDailyPlanList["+ i +"].Day")); elasticDailyPlanInfo.setStatus(_ctx.integerValue("DescribeElasticDailyPlanResponse.ElasticDailyPlanList["+ i +"].Status")); elasticDailyPlanList.add(elasticDailyPlanInfo); } describeElasticDailyPlanResponse.setElasticDailyPlanList(elasticDailyPlanList); return describeElasticDailyPlanResponse; } }
/* * Copyright (c) 2004, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package nsk.jvmti.scenarios.events.EM06; import java.lang.reflect.Field; import java.io.PrintStream; import java.io.File; import nsk.share.*; import nsk.share.jvmti.*; public class em06t001 extends DebugeeClass { // load native library if required static { System.loadLibrary("em06t001"); } // run test from command line public static void main(String argv[]) { argv = nsk.share.jvmti.JVMTITest.commonInit(argv); // JCK-compatible exit System.exit(run(argv, System.out) + Consts.JCK_STATUS_BASE); } // run test from JCK-compatible environment public static int run(String argv[], PrintStream out) { return new em06t001().runIt(argv, out); } /* =================================================================== */ // scaffold objects ArgumentHandler argHandler = null; static Log log = null; Log.Logger logger; int status = Consts.TEST_PASSED; /* =================================================================== */ static final String PACKAGE_NAME = "nsk.jvmti.scenarios.events.EM06"; static final String TESTED_CLASS_NAME = PACKAGE_NAME + ".em06t001a"; static final String TESTED_FIELD_NAME = "toProvokePreparation"; int classLoaderCount; // run debuggee public int runIt(String argv[], PrintStream out) { argHandler = new ArgumentHandler(argv); log = new Log(out, argHandler); logger = new Log.Logger(log,"debuggee> "); classLoaderCount = argHandler.findOptionIntValue("classLoaderCount", 100); String args[] = argHandler.getArguments(); if (args.length <= 0) { throw new Failure("Path for tested class file to load not specified"); } String path = args[0]; int currStatus; status = em06t001.checkStatus(Consts.TEST_PASSED); logger.display("Loading " + TESTED_CLASS_NAME); CustomClassLoader classLoader; Class loadedClass = null; Field fld; for (int i = 0; i < classLoaderCount; i++) { classLoader = new CustomClassLoader(); classLoader.setClassPath(path); try { loadedClass = classLoader.loadClass(TESTED_CLASS_NAME); } catch (ClassNotFoundException e) { logger.complain("class not found!!! " + TESTED_CLASS_NAME); return Consts.TEST_FAILED; } // to provoke class preparation try { fld = loadedClass.getField(TESTED_FIELD_NAME); } catch (NoSuchFieldException e) { logger.complain("field not found!!! " + TESTED_FIELD_NAME); return Consts.TEST_FAILED; } } currStatus = em06t001.checkStatus(Consts.TEST_PASSED); if (currStatus != Consts.TEST_PASSED) status = currStatus; return status; } }
package org.colorcoding.ibas.bobas.core.fields; import org.colorcoding.ibas.bobas.MyConfiguration; import org.colorcoding.ibas.bobas.mapping.DbField; public abstract class FieldDataDbBase<T> extends FieldDataBase<T> implements IFieldDataDb { private String dbField; @Override public String getDbField() { if (this.fieldMapping != null) { return this.fieldMapping.name(); } return this.dbField; } public void setDbField(String value) { this.dbField = value; } private String dbTable; @Override public String getDbTable() { if (this.fieldMapping != null) { return MyConfiguration.applyVariables(this.fieldMapping.table()); } return this.dbTable; } public void setDbTable(String value) { this.dbTable = value; } private int dbIndex = -1; @Override public int getDbIndex() { return this.dbIndex; } public void setDbIndex(int value) { this.dbIndex = value; } private DbField fieldMapping; public void mapping(DbField mapping) { this.setPrimaryKey(mapping.primaryKey()); this.setUniqueKey(mapping.uniqueKey()); this.setSavable(true); this.setOriginal(true); this.fieldMapping = mapping; } }
/* * Copyright 2019-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.elipcero.carisa.core.data; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import net.minidev.json.annotate.JsonIgnore; import org.springframework.data.cassandra.core.cql.PrimaryKeyType; import org.springframework.data.cassandra.core.mapping.PrimaryKeyColumn; import java.util.HashMap; import java.util.Map; import java.util.UUID; @AllArgsConstructor @NoArgsConstructor @Getter @Setter public abstract class ManyRelation implements Relation { public static String PARENTID_COLUMN_NAME = "parentId"; public static String CHILDID_COLUMN_NAME = "childId"; @PrimaryKeyColumn(ordinal = 0, type = PrimaryKeyType.PARTITIONED) private UUID parentId; @PrimaryKeyColumn(ordinal = 1, type = PrimaryKeyType.CLUSTERED) private UUID childId; @Override public UUID getParentId() { return this.parentId; } @Override @JsonIgnore public UUID getChildId() { return this.childId; } public static Map<String, Object> GetMapId(UUID parentId, UUID childId) { return new HashMap<String, Object>() {{ put(PARENTID_COLUMN_NAME, parentId); put(CHILDID_COLUMN_NAME, childId); }}; } }
package com.github.hypfvieh.paulmann.features; import java.nio.charset.StandardCharsets; import com.github.hypfvieh.bluetooth.wrapper.BluetoothGattCharacteristic; /** * Abstraction for all Paulmann bluetooth features which were String based (characteristics supports (ASCII) String values). * * @author David M. * */ public abstract class AbstractStringValFeature extends AbstractFeature { protected AbstractStringValFeature(BluetoothGattCharacteristic _characteristic) { super(_characteristic); } /** * Default value. * @return default string */ public abstract String getDefaultValue(); /** * Write a String. * @param _value to write * @return true on successful write, false otherwise */ public boolean writeString(String _value) { if (_value == null) { return false; } return writeValue(_value.getBytes(StandardCharsets.US_ASCII)); } /** * Use cached write to send the value. * @see AbstractFeature#writeCached(byte[]) * @param _value to write */ public void writeCached(String _value) { if (_value != null) { writeCached(_value.getBytes(StandardCharsets.US_ASCII)); } } /** * Read a string. * @return the read string, maybe null or empty */ public String readString() { return new String(readValue(), StandardCharsets.US_ASCII); } @Override public String toString() { return getClass().getSimpleName() + " [defaultValue=" + getDefaultValue() + "]"; } }
package com.tomkasp.fitapp.activitytrackers.readmodel.impl; import com.tomkasp.fitapp.activitytrackers.domain.Activity; import com.tomkasp.fitapp.activitytrackers.infrastructure.dto.ActivityDto; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author Tomasz Kasprzycki */ @Component class ActivityFactory { public ActivityDto buildDto(Activity activity) { ActivityDto activityDto = new ActivityDto() .activityAverageSpeed(activity.getActivityAverageSpeed()) .activityDuration(activity.getActivityDuration()) .activitySource(activity.getActivitySource()) .activityType(activity.getActivityType()) .dateTime(activity.getDateTime()) .id(activity.getId()) .integrationId(activity.getIntegrationId()); return activityDto; } List<ActivityDto> buildDtos(List<Activity> activities) { List<ActivityDto> activityDtos = new ArrayList<>(); for (Activity activity : activities) { activityDtos.add(buildDto(activity)); } return activityDtos; } List<ActivityDto> buildEmptyDtoList(){ return Collections.emptyList(); } }
package com.baomidou.jobs.rpc.remoting.invoker.route; import com.baomidou.jobs.rpc.remoting.invoker.route.impl.*; /** * @author xuxueli 2018-12-04 */ public enum LoadBalance { RANDOM(new XxlRpcLoadBalanceRandomStrategy()), ROUND(new XxlRpcLoadBalanceRoundStrategy()), LRU(new XxlRpcLoadBalanceLRUStrategy()), LFU(new XxlRpcLoadBalanceLFUStrategy()), CONSISTENT_HASH(new XxlRpcLoadBalanceConsistentHashStrategy()); public final JobsRpcLoadBalance xxlRpcInvokerRouter; LoadBalance(JobsRpcLoadBalance xxlRpcInvokerRouter) { this.xxlRpcInvokerRouter = xxlRpcInvokerRouter; } public static LoadBalance match(String name, LoadBalance defaultRouter) { for (LoadBalance item : LoadBalance.values()) { if (item.equals(name)) { return item; } } return defaultRouter; } }
/** * Copyright (C) 2019 Cambridge Systematics * * 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.onebusaway.nextbus.impl.exceptions; import org.onebusaway.nextbus.validation.ErrorMsg; public class StopNullException extends Exception{ private static final long serialVersionUID = 1L; public StopNullException(){ super(ErrorMsg.STOP_S_NULL.getDescription()); } }
/* * Copyright 2013 MovingBlocks * * 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.terasology.logic.characters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.audio.StaticSound; import org.terasology.audio.events.PlaySoundEvent; import org.terasology.engine.Time; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.event.ReceiveEvent; import org.terasology.entitySystem.systems.BaseComponentSystem; import org.terasology.entitySystem.systems.RegisterMode; import org.terasology.entitySystem.systems.RegisterSystem; import org.terasology.logic.characters.events.FootstepEvent; import org.terasology.logic.characters.events.JumpEvent; import org.terasology.logic.characters.events.OnEnterBlockEvent; import org.terasology.logic.characters.events.SwimStrokeEvent; import org.terasology.logic.characters.events.VerticalCollisionEvent; import org.terasology.logic.health.DoDestroyEvent; import org.terasology.logic.location.LocationComponent; import org.terasology.logic.players.event.OnPlayerSpawnedEvent; import org.terasology.math.geom.Vector3f; import org.terasology.math.geom.Vector3i; import org.terasology.registry.In; import org.terasology.utilities.random.FastRandom; import org.terasology.utilities.random.Random; import org.terasology.world.WorldProvider; import org.terasology.world.block.Block; import java.util.List; /** */ @RegisterSystem(RegisterMode.ALWAYS) public class CharacterSoundSystem extends BaseComponentSystem { private static final Logger logger = LoggerFactory.getLogger(CharacterSoundSystem.class); public static final long MIN_TIME = 10; private static final float LANDING_VOLUME_MODIFIER = 0.2f; //The sound volume is multiplied by this number private static final float LANDING_VELOCITY_THRESHOLD = 7; //How fast do you have to be falling for the sound to play private static final float LANDING_VOLUME_MAX = 2; //The maximum modifier value private Random random = new FastRandom(); @In private Time time; @In private WorldProvider worldProvider; @ReceiveEvent public void onFootstep(FootstepEvent event, EntityRef entity, LocationComponent locationComponent, CharacterSoundComponent characterSounds) { List<StaticSound> footstepSounds = characterSounds.footstepSounds; // Check if the block the character is standing on has footstep sounds Vector3i blockPos = new Vector3i(locationComponent.getLocalPosition()); blockPos.y--; // The block *below* the character's feet is interesting to us Block block = worldProvider.getBlock(blockPos); if (block != null) { if (block.getSounds() == null) { logger.error("Block '{}' has no sounds", block.getURI()); } else if (!block.getSounds().getStepSounds().isEmpty()) { footstepSounds = block.getSounds().getStepSounds(); } } if (footstepSounds.size() > 0 && characterSounds.lastSoundTime + MIN_TIME < time.getGameTimeInMs()) { StaticSound sound = random.nextItem(footstepSounds); entity.send(new PlaySoundEvent(entity, sound, characterSounds.footstepVolume)); characterSounds.lastSoundTime = time.getGameTimeInMs(); entity.saveComponent(characterSounds); } } @ReceiveEvent public void onJump(JumpEvent event, EntityRef entity, CharacterSoundComponent characterSounds) { if (characterSounds.lastSoundTime + MIN_TIME < time.getGameTimeInMs()) { StaticSound sound = null; if (characterSounds.jumpSounds.size() > 0) { sound = random.nextItem(characterSounds.jumpSounds); } else if (characterSounds.footstepSounds.size() > 0) { sound = random.nextItem(characterSounds.footstepSounds); } if (sound != null) { entity.send(new PlaySoundEvent(entity, sound, characterSounds.jumpVolume)); characterSounds.lastSoundTime = time.getGameTimeInMs(); entity.saveComponent(characterSounds); } } } @ReceiveEvent public void onLanded(VerticalCollisionEvent event, EntityRef entity, CharacterSoundComponent characterSounds) { Vector3f velocity = event.getVelocity(); float soundVolumeModifier = (velocity.y * -1 - LANDING_VELOCITY_THRESHOLD) * LANDING_VOLUME_MODIFIER; if (soundVolumeModifier <= 0f) { return; } if (soundVolumeModifier > LANDING_VOLUME_MAX) { soundVolumeModifier = LANDING_VOLUME_MAX; } if (characterSounds.lastSoundTime + MIN_TIME < time.getGameTimeInMs()) { StaticSound sound = null; if (characterSounds.landingSounds.size() > 0) { sound = random.nextItem(characterSounds.landingSounds); } else if (characterSounds.footstepSounds.size() > 0) { sound = random.nextItem(characterSounds.footstepSounds); } if (sound != null) { entity.send(new PlaySoundEvent(entity, sound, characterSounds.landingVolume * soundVolumeModifier)); characterSounds.lastSoundTime = time.getGameTimeInMs(); entity.saveComponent(characterSounds); } } } @ReceiveEvent public void onDeath(DoDestroyEvent event, EntityRef entity, CharacterSoundComponent characterSounds) { if (characterSounds.deathSounds.size() > 0) { StaticSound sound = random.nextItem(characterSounds.deathSounds); entity.send(new PlaySoundEvent(entity, sound, characterSounds.deathVolume)); } } @ReceiveEvent public void onRespawn(OnPlayerSpawnedEvent event, EntityRef character, CharacterSoundComponent characterSounds) { if (characterSounds.respawnSounds.size() > 0) { StaticSound sound = random.nextItem(characterSounds.respawnSounds); character.send(new PlaySoundEvent(character, sound, characterSounds.respawnVolume)); } } @ReceiveEvent public void onSwimStroke(SwimStrokeEvent event, EntityRef entity, CharacterSoundComponent characterSounds) { if (characterSounds.swimSounds.size() > 0 && characterSounds.lastSoundTime + MIN_TIME < time.getGameTimeInMs()) { StaticSound sound = random.nextItem(characterSounds.swimSounds); entity.send(new PlaySoundEvent(entity, sound, characterSounds.swimmingVolume)); characterSounds.lastSoundTime = time.getGameTimeInMs(); entity.saveComponent(characterSounds); } } @ReceiveEvent public void onEnterBlock(OnEnterBlockEvent event, EntityRef entity, CharacterSoundComponent characterSounds) { // only play this sound if the feet hit the water if (event.getCharacterRelativePosition().y == 0 && characterSounds.lastSoundTime + MIN_TIME < time.getGameTimeInMs()) { boolean oldBlockIsLiquid = event.getOldBlock().isLiquid(); boolean newBlockIsLiquid = event.getNewBlock().isLiquid(); StaticSound sound = null; if (!oldBlockIsLiquid && newBlockIsLiquid) { sound = random.nextItem(characterSounds.enterWaterSounds); } else if (oldBlockIsLiquid && !newBlockIsLiquid) { sound = random.nextItem(characterSounds.leaveWaterSounds); } if (sound != null) { entity.send(new PlaySoundEvent(entity, sound, characterSounds.diveVolume)); characterSounds.lastSoundTime = time.getGameTimeInMs(); entity.saveComponent(characterSounds); } } } }
package UI.dashboard.domain; import java.util.Date; public final class Transaction { private Date time; private String country; private String city; private String theater; private String room; private int seats; private double price; private long movieId; private String title; public long getMovieId() { return movieId; } public void setMovieId(final long movieId) { this.movieId = movieId; } public String getTitle() { return title; } public void setTitle(final String title) { this.title = title; } public Date getTime() { return time; } public void setTime(final Date time) { this.time = time; } public String getCountry() { return country; } public void setCountry(final String country) { this.country = country; } public String getCity() { return city; } public void setCity(final String city) { this.city = city; } public String getTheater() { return theater; } public void setTheater(final String theater) { this.theater = theater; } public String getRoom() { return room; } public void setRoom(final String room) { this.room = room; } public int getSeats() { return seats; } public void setSeats(final int seats) { this.seats = seats; } public double getPrice() { return price; } public void setPrice(final double price) { this.price = price; } }
package edu.rise.ihnilatis; import android.app.Application; import android.content.Context; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.horcrux.svg.SvgPackage; import com.reactnativecommunity.webview.RNCWebViewPackage; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.soloader.SoLoader; import java.lang.reflect.InvocationTargetException; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List<ReactPackage> packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new ReactPackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); initializeFlipper(this); // Remove this line if you don't want Flipper enabled } /** * Loads Flipper in React Native templates. * * @param context */ private static void initializeFlipper(Context context) { if (BuildConfig.DEBUG) { try { /* We use reflection here to pick up the class that initializes Flipper, since Flipper library is not available in release mode */ Class<?> aClass = Class.forName("com.facebook.flipper.ReactNativeFlipper"); aClass.getMethod("initializeFlipper", Context.class).invoke(null, context); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } }
package org.ovirt.engine.core.common; import java.util.HashMap; public enum AuditLogType { UNASSIGNED(0), // -- VDC Log types -- VDC_START(1), VDC_STOP(2), // -- VDS Log types -- VDS_FAILURE(12), // When VDS changes status to up -> down or in VDC // initialization the VDS is down VDS_DETECTED(13), // When VDC initializes and detects a running VDS VDS_RECOVER(14), // When VDS changes status down->up VDS_MAINTENANCE(15), // When VDS is transferred to maintenance mode VDS_ACTIVATE(16), // When VDS is reactivated VDS_MAINTENANCE_FAILED(17, AuditLogTimeInterval.MINUTE.getValue()), // When VDS is transferred to maintenance mode VDS_ACTIVATE_FAILED(18, AuditLogTimeInterval.MINUTE.getValue()), // When VDS is reactivated VDS_RECOVER_FAILED(19, AuditLogTimeInterval.MINUTE.getValue()), // When VDS changes status down->up VDS_SLOW_STORAGE_RESPONSE_TIME(123, AuditLogTimeInterval.MINUTE.getValue() * 5), // ? VDS_ALREADY_IN_REQUESTED_STATUS(493), VDS_MANUAL_FENCE_STATUS(494), VDS_MANUAL_FENCE_STATUS_FAILED(495), VDS_MANUAL_FENCE_FAILED_CALL_FENCE_SPM(530), VDS_LOW_MEM(531, AuditLogTimeInterval.MINUTE.getValue() * 30), VDS_HIGH_MEM_USE(532, AuditLogTimeInterval.MINUTE.getValue() * 30), VDS_HIGH_NETWORK_USE(533, AuditLogTimeInterval.MINUTE.getValue() * 30), VDS_HIGH_CPU_USE(534, AuditLogTimeInterval.MINUTE.getValue() * 30), VDS_HIGH_SWAP_USE(535, AuditLogTimeInterval.MINUTE.getValue() * 30), VDS_LOW_SWAP(536, AuditLogTimeInterval.MINUTE.getValue() * 30), VDS_FENCE_STATUS(496), VDS_FENCE_STATUS_FAILED(497), VDS_APPROVE(498), VDS_APPROVE_FAILED(499), VDS_FAILED_TO_RUN_VMS(500, AuditLogTimeInterval.MINUTE.getValue()), VDS_INSTALL(504), VDS_INSTALL_FAILED(505), VDS_INITIATED_RUN_VM(506), VDS_INITIATED_RUN_VM_AS_STATELESS(537), VDS_INITIATED_RUN_VM_FAILED(507), // VDS_INITIATED_RUN_VM_CHECKOUT_FAILED = 508, VDS_INSTALL_IN_PROGRESS(509), VDS_INSTALL_IN_PROGRESS_WARNING(510), VDS_INSTALL_IN_PROGRESS_ERROR(511), VDS_RECOVER_FAILED_VMS_UNKNOWN(513), VDS_INITIALIZING(514, AuditLogTimeInterval.SECOND.getValue() * 30), VDS_CPU_LOWER_THAN_CLUSTER(515), VDS_CPU_RETRIEVE_FAILED(516), VDS_FAILED_TO_GET_HOST_HARDWARE_INFO(517), @Deprecated VDS_STORAGE_CONNECTION_FAILED_BUT_LAST_VDS(533), VDS_STORAGES_CONNECTION_FAILED(535), VDS_STORAGE_VDS_STATS_FAILED(534), VDS_SET_NONOPERATIONAL(517, AuditLogTimeInterval.MINUTE.getValue()), VDS_SET_NONOPERATIONAL_FAILED(518, AuditLogTimeInterval.MINUTE.getValue()), VDS_SET_NONOPERATIONAL_NETWORK(519, AuditLogTimeInterval.MINUTE.getValue()), VDS_SET_NONOPERATIONAL_IFACE_DOWN(603, AuditLogTimeInterval.MINUTE.getValue()), VDS_SET_NONOPERATIONAL_DOMAIN(522, AuditLogTimeInterval.MINUTE.getValue()), VDS_SET_NONOPERATIONAL_DOMAIN_FAILED(523, AuditLogTimeInterval.MINUTE.getValue()), VDS_DOMAIN_DELAY_INTERVAL(524, AuditLogTimeInterval.HOUR.getValue()), VDS_LOW_DISK_SPACE(23, AuditLogTimeInterval.HOUR.getValue() * 12), VDS_LOW_DISK_SPACE_ERROR(24, AuditLogTimeInterval.MINUTE.getValue() * 15), USER_VDS_MAINTENANCE(600), // When VDS is transferred to CPU_FLAGS_NX_IS_MISSING(601), // maintenance mode USER_VDS_MAINTENANCE_MIGRATION_FAILED(602), SYSTEM_VDS_RESTART(121, AuditLogTimeInterval.MINUTE.getValue()), SYSTEM_FAILED_VDS_RESTART(122, AuditLogTimeInterval.MINUTE.getValue()), // Host time drift Alert VDS_TIME_DRIFT_ALERT(604, AuditLogTimeInterval.MINUTE.getValue() * 60), // Proxy host selection PROXY_HOST_SELECTION(605), // -- IRS Log types -- IRS_FAILURE(22, AuditLogTimeInterval.HOUR.getValue() * 12), IRS_DISK_SPACE_LOW(26, AuditLogTimeInterval.HOUR.getValue() * 12), IRS_DISK_SPACE_LOW_ERROR(201, AuditLogTimeInterval.MINUTE.getValue() * 15), IRS_HOSTED_ON_VDS(204), // -- USER Log types -- USER_VDC_LOGIN(30), // user logged in to VDC USER_VDC_LOGIN_FAILED(114), // user logged in to VDC USER_VDC_LOGOUT(31), // User logged out from VDC USER_VDC_LOGOUT_FAILED(815), // User logged out failed USER_INITIATED_RUN_VM(150), USER_STARTED_VM(153), USER_INITIATED_RUN_VM_FAILED(151), USER_RUN_VM(32), // User issued runVm command USER_RUN_VM_AS_STATELESS(538), // User issued runVm command in stateless mode USER_FAILED_RUN_VM(54), // User issued runVm command USER_RUN_VM_AS_STATELESS_FINISHED_FAILURE(70), USER_RUN_VM_AS_STATELESS_WITH_DISKS_NOT_ALLOWING_SNAPSHOT(171), USER_RUN_VM_FAILURE_STATELESS_SNAPSHOT_LEFT(1001), USER_RUN_VM_ON_NON_DEFAULT_VDS(152), USER_STOP_VM(33), // User issued stopVm command USER_STOP_SUSPENDED_VM(111), USER_STOP_SUSPENDED_VM_FAILED(112), USER_FAILED_STOP_VM(56), USER_ADD_VM(34), USER_ADD_VM_STARTED(37), USER_ADD_VM_FINISHED_SUCCESS(53), USER_ADD_VM_FINISHED_FAILURE(60), USER_FAILED_ADD_VM(57), USER_UPDATE_VM(35), USER_FAILED_UPDATE_VM(58), USER_UPDATE_VM_CLUSTER_DEFAULT_HOST_CLEARED(250), USER_REMOVE_VM_FINISHED(113), USER_REMOVE_VM_FINISHED_WITH_ILLEGAL_DISKS(172), USER_ADD(149), USER_FAILED_REMOVE_VM(59), USER_CHANGE_DISK_VM(38), USER_FAILED_CHANGE_DISK_VM(102), USER_CHANGE_FLOPPY_VM(72), USER_FAILED_CHANGE_FLOPPY_VM(75), USER_PAUSE_VM(39), USER_FAILED_PAUSE_VM(55), USER_SUSPEND_VM(501), @Deprecated USER_SUSPEND_VM_FINISH_SUCCESS(512), USER_SUSPEND_VM_FINISH_FAILURE(521), USER_SUSPEND_VM_FINISH_FAILURE_WILL_TRY_AGAIN(532), USER_FAILED_SUSPEND_VM(502), USER_SUSPEND_VM_OK(503), USER_RESUME_VM(40), USER_FAILED_RESUME_VM(103), USER_INITIATED_SHUTDOWN_VM(73), USER_FAILED_SHUTDOWN_VM(74), USER_STOPPED_VM_INSTEAD_OF_SHUTDOWN(76), USER_FAILED_STOPPING_VM_INSTEAD_OF_SHUTDOWN(77), USER_ADD_DISK_TO_VM(78), USER_ADD_DISK_TO_VM_FINISHED_SUCCESS(97), USER_ADD_DISK_TO_VM_FINISHED_FAILURE(98), USER_FAILED_ADD_DISK_TO_VM(79), @Deprecated USER_REMOVE_DISK_FROM_VM(80), @Deprecated USER_FAILED_REMOVE_DISK_FROM_VM(81), USER_MOVED_VM(82), USER_MOVED_VM_FINISHED_SUCCESS(91), USER_MOVED_VM_FINISHED_FAILURE(92), USER_FAILED_MOVE_VM(83), USER_MOVED_TEMPLATE(84), USER_MOVED_TEMPLATE_FINISHED_SUCCESS(93), USER_MOVED_TEMPLATE_FINISHED_FAILURE(94), USER_FAILED_MOVE_TEMPLATE(85), USER_COPIED_TEMPLATE(86), USER_COPIED_TEMPLATE_FINISHED_SUCCESS(95), USER_COPIED_TEMPLATE_FINISHED_FAILURE(96), USER_FAILED_COPY_TEMPLATE(87), USER_UPDATE_VM_DISK(88), USER_FAILED_UPDATE_VM_DISK(89), USER_HOTPLUG_DISK(2000), USER_FAILED_HOTPLUG_DISK(2001), USER_HOTUNPLUG_DISK(2002), USER_FAILED_HOTUNPLUG_DISK(2003), USER_COPIED_TEMPLATE_DISK(2004), USER_FAILED_COPY_TEMPLATE_DISK(2005), USER_COPIED_TEMPLATE_DISK_FINISHED_SUCCESS(2006), USER_COPIED_TEMPLATE_DISK_FINISHED_FAILURE(2007), USER_MOVED_VM_DISK(2008), USER_FAILED_MOVED_VM_DISK(2009), USER_MOVED_VM_DISK_FINISHED_SUCCESS(2010), USER_MOVED_VM_DISK_FINISHED_FAILURE(2011), USER_FINISHED_REMOVE_DISK(2014), USER_FINISHED_FAILED_REMOVE_DISK(2015), USER_ATTACH_DISK_TO_VM(2016), USER_FAILED_ATTACH_DISK_TO_VM(2017), USER_DETACH_DISK_FROM_VM(2018), USER_FAILED_DETACH_DISK_FROM_VM(2019), USER_ADD_DISK(2020), USER_ADD_DISK_FINISHED_SUCCESS(2021), USER_ADD_DISK_FINISHED_FAILURE(2022), USER_FAILED_ADD_DISK(2023), // Used only from SQL script, therefor should not have severity & message USER_RUN_UNLOCK_ENTITY_SCRIPT(2024), // Quota audit logs USER_ADD_QUOTA(3000), USER_FAILED_ADD_QUOTA(3001), USER_UPDATE_QUOTA(3002), USER_FAILED_UPDATE_QUOTA(3003), USER_DELETE_QUOTA(3004), USER_FAILED_DELETE_QUOTA(3005), USER_EXCEEDED_QUOTA_VDS_GROUP_GRACE_LIMIT(3006), USER_EXCEEDED_QUOTA_VDS_GROUP_LIMIT(3007), USER_EXCEEDED_QUOTA_VDS_GROUP_THRESHOLD(3008), USER_EXCEEDED_QUOTA_STORAGE_GRACE_LIMIT(3009), USER_EXCEEDED_QUOTA_STORAGE_LIMIT(3010), USER_EXCEEDED_QUOTA_STORAGE_THRESHOLD(3011), QUOTA_STORAGE_RESIZE_LOWER_THEN_CONSUMPTION(3012), MISSING_QUOTA_STORAGE_PARAMETERS_PERMISSIVE_MODE(3013), MISSING_QUOTA_CLUSTER_PARAMETERS_PERMISSIVE_MODE(3014), // Gluster Audit Logs GLUSTER_VOLUME_CREATE(4000), GLUSTER_VOLUME_CREATE_FAILED(4001), GLUSTER_VOLUME_OPTION_ADDED(4002), GLUSTER_VOLUME_OPTION_SET_FAILED(4003), GLUSTER_VOLUME_START(4004), GLUSTER_VOLUME_START_FAILED(4005), GLUSTER_VOLUME_STOP(4006), GLUSTER_VOLUME_STOP_FAILED(4007), GLUSTER_VOLUME_OPTIONS_RESET(4008), GLUSTER_VOLUME_OPTIONS_RESET_FAILED(4009), GLUSTER_VOLUME_DELETE(4010), GLUSTER_VOLUME_DELETE_FAILED(4011), GLUSTER_VOLUME_REBALANCE_START(4012), GLUSTER_VOLUME_REBALANCE_START_FAILED(4013), GLUSTER_VOLUME_REMOVE_BRICKS(4014), GLUSTER_VOLUME_REMOVE_BRICKS_FAILED(4015), GLUSTER_VOLUME_REPLACE_BRICK_FAILED(4016), GLUSTER_VOLUME_REPLACE_BRICK_START(4017), GLUSTER_VOLUME_REPLACE_BRICK_START_FAILED(4018), GLUSTER_VOLUME_ADD_BRICK(4019), GLUSTER_VOLUME_ADD_BRICK_FAILED(4020), GLUSTER_SERVER_REMOVE_FAILED(4021), GLUSTER_VOLUME_PROFILE_START(4022), GLUSTER_VOLUME_PROFILE_START_FAILED(4023), GLUSTER_VOLUME_PROFILE_STOP(4024), GLUSTER_VOLUME_PROFILE_STOP_FAILED(4025), GLUSTER_VOLUME_CREATED_FROM_CLI(4026), GLUSTER_VOLUME_DELETED_FROM_CLI(4027), GLUSTER_VOLUME_OPTION_SET_FROM_CLI(4028), GLUSTER_VOLUME_OPTION_RESET_FROM_CLI(4029), GLUSTER_VOLUME_PROPERTIES_CHANGED_FROM_CLI(4030), GLUSTER_VOLUME_BRICK_ADDED_FROM_CLI(4031), GLUSTER_VOLUME_BRICK_REMOVED_FROM_CLI(4032), GLUSTER_SERVER_REMOVED_FROM_CLI(4033), GLUSTER_VOLUME_INFO_FAILED(4034), GLUSTER_COMMAND_FAILED(4035), GLUSTER_SERVER_ADD_FAILED(4436), GLUSTER_SERVERS_LIST_FAILED(4437), GLUSTER_SERVER_REMOVE(4038), GLUSTER_VOLUME_STARTED_FROM_CLI(4039), GLUSTER_VOLUME_STOPPED_FROM_CLI(4040), GLUSTER_VOLUME_OPTION_CHANGED_FROM_CLI(4041), GLUSTER_HOOK_ENABLE(4042), GLUSTER_HOOK_ENABLE_FAILED(4043), GLUSTER_HOOK_ENABLE_PARTIAL(4044), GLUSTER_HOOK_DISABLE(4045), GLUSTER_HOOK_DISABLE_FAILED(4046), GLUSTER_HOOK_DISABLE_PARTIAL(4047), GLUSTER_HOOK_LIST_FAILED(4048), GLUSTER_HOOK_CONFLICT_DETECTED(4049), GLUSTER_HOOK_DETECTED_NEW(4050), GLUSTER_HOOK_DETECTED_DELETE(4051), GLUSTER_VOLUME_OPTION_MODIFIED(4052), GLUSTER_HOOK_GETCONTENT_FAILED(4053), GLUSTER_SERVICES_LIST_FAILED(4054), GLUSTER_SERVICE_TYPE_ADDED_TO_CLUSTER(4055), GLUSTER_CLUSTER_SERVICE_STATUS_CHANGED(4056), GLUSTER_SERVICE_ADDED_TO_SERVER(4057), GLUSTER_SERVER_SERVICE_STATUS_CHANGED(4058), GLUSTER_HOOK_UPDATED(4059), GLUSTER_HOOK_UPDATE_FAILED(4060), GLUSTER_HOOK_ADDED(4061), GLUSTER_HOOK_ADD_FAILED(4062), GLUSTER_HOOK_REMOVED(4063), GLUSTER_HOOK_REMOVE_FAILED(4064), USER_VDS_RESTART(41), USER_FAILED_VDS_RESTART(107), USER_VDS_START(20), USER_FAILED_VDS_START(118), USER_VDS_STOP(21), USER_FAILED_VDS_STOP(137), USER_ADD_VDS(42), USER_FAILED_ADD_VDS(104), USER_UPDATE_VDS(43), USER_FAILED_UPDATE_VDS(105), USER_REMOVE_VDS(44), USER_FAILED_REMOVE_VDS(106), USER_CREATE_SNAPSHOT(45), USER_CREATE_SNAPSHOT_FINISHED_SUCCESS(68), USER_CREATE_SNAPSHOT_FINISHED_FAILURE(69), USER_CREATE_LIVE_SNAPSHOT_FINISHED_FAILURE(170), USER_FAILED_CREATE_SNAPSHOT(117), USER_REMOVE_SNAPSHOT(342), USER_FAILED_REMOVE_SNAPSHOT(343), USER_REMOVE_SNAPSHOT_FINISHED_SUCCESS(356), USER_REMOVE_SNAPSHOT_FINISHED_FAILURE(357), USER_TRY_BACK_TO_SNAPSHOT(46), USER_TRY_BACK_TO_SNAPSHOT_FINISH_SUCCESS(71), USER_TRY_BACK_TO_SNAPSHOT_FINISH_FAILURE(99), USER_FAILED_TRY_BACK_TO_SNAPSHOT(115), USER_RESTORE_FROM_SNAPSHOT(47), USER_RESTORE_FROM_SNAPSHOT_START(1190), USER_RESTORE_FROM_SNAPSHOT_FINISH_SUCCESS(100), USER_RESTORE_FROM_SNAPSHOT_FINISH_FAILURE(101), USER_FAILED_RESTORE_FROM_SNAPSHOT(116), USER_ADD_VM_TEMPLATE(48), USER_ADD_VM_TEMPLATE_FINISHED_SUCCESS(51), USER_ADD_VM_TEMPLATE_FINISHED_FAILURE(52), USER_FAILED_ADD_VM_TEMPLATE(108), USER_UPDATE_VM_TEMPLATE(49), USER_FAILED_UPDATE_VM_TEMPLATE(109), USER_REMOVE_VM_TEMPLATE(50), USER_REMOVE_VM_TEMPLATE_FINISHED(251), USER_FAILED_REMOVE_VM_TEMPLATE(110), TEMPLATE_IMPORT(135), TEMPLATE_IMPORT_FAILED(136), USER_ATTACH_USER_TO_VM(520), USER_DETACH_USER_FROM_VM(360), USER_FAILED_DETACH_USER_FROM_VM(361), USER_FAILED_ATTACH_USER_TO_VM(182), USER_REMOVE_ADUSER(325), USER_FAILED_REMOVE_ADUSER(326), USER_FAILED_ADD_ADUSER(327), USER_PASSWORD_CHANGED(346), USER_PASSWORD_CHANGE_FAILED(347), USER_CLEAR_UNKNOWN_VMS(348), USER_FAILED_CLEAR_UNKNOWN_VMS(349), AUTO_SUSPEND_VM(524), @Deprecated AUTO_SUSPEND_VM_FINISH_SUCCESS(525), AUTO_SUSPEND_VM_FINISH_FAILURE(526), AUTO_FAILED_SUSPEND_VM(527), USER_EJECT_VM_DISK(528), USER_EJECT_VM_FLOPPY(529), // -- VM Log types -- VM_DOWN(61), VM_DOWN_ERROR(119), VM_MIGRATION_START(62), VM_MIGRATION_DONE(63), VM_MIGRATION_ABORT(64), VM_MIGRATION_FAILED(65), VM_FAILURE(66), VM_MIGRATION_START_SYSTEM_INITIATED(67), VM_MIGRATION_FAILED_FROM_TO(120), VM_MIGRATION_TRYING_RERUN(128), VM_CANCEL_MIGRATION(161), VM_CANCEL_MIGRATION_FAILED(162), VM_STATUS_RESTORED(163), VM_MIGRATION_FAILED_DURING_MOVE_TO_MAINTENANCE(140), VM_SET_TO_UNKNOWN_STATUS(142), VM_WAS_SET_DOWN_DUE_TO_HOST_REBOOT_OR_MANUAL_FENCE(143), USER_EXPORT_VM(131), USER_EXPORT_VM_FAILED(132), USER_EXPORT_TEMPLATE(133), USER_EXPORT_TEMPLATE_FAILED(134), VM_IMPORT(124), VM_IMPORT_FAILED(125), VM_NOT_RESPONDING(126), VDS_RUN_IN_NO_KVM_MODE(127), VDS_VERSION_NOT_SUPPORTED_FOR_CLUSTER(141), VM_CLEARED(129), VM_PAUSED_ENOSPC(138), VM_PAUSED_ERROR(139), VM_IMPORT_INFO(144), VM_PAUSED_EIO(145), VM_PAUSED_EPERM(146), VM_POWER_DOWN_FAILED(147), USER_ADD_VM_POOL(300), USER_ADD_VM_POOL_FAILED(301), USER_ADD_VM_POOL_WITH_VMS(302), USER_ADD_VM_POOL_WITH_VMS_FAILED(303), USER_ADD_VM_POOL_WITH_VMS_ADD_VDS_FAILED(320), USER_REMOVE_VM_POOL(304), USER_REMOVE_VM_POOL_FAILED(305), USER_ADD_VM_TO_POOL(306), USER_ADD_VM_TO_POOL_FAILED(307), USER_REMOVE_VM_FROM_POOL(308), USER_REMOVE_VM_FROM_POOL_FAILED(309), USER_ATTACH_USER_TO_POOL(310), USER_ATTACH_USER_TO_POOL_INTERNAL(472), USER_ATTACH_USER_TO_POOL_FAILED(311), USER_ATTACH_USER_TO_POOL_FAILED_INTERNAL(473), USER_DETACH_USER_FROM_POOL(312), USER_DETACH_USER_FROM_POOL_FAILED(313), USER_UPDATE_VM_POOL(314), USER_UPDATE_VM_POOL_FAILED(315), USER_ATTACH_USER_TO_VM_FROM_POOL(316), USER_ATTACH_USER_TO_VM_FROM_POOL_FINISHED_SUCCESS(318), USER_ATTACH_USER_TO_VM_FROM_POOL_FINISHED_FAILURE(319), USER_ATTACH_USER_TO_VM_FROM_POOL_FAILED(317), USER_UPDATE_VM_POOL_WITH_VMS(344), USER_UPDATE_VM_POOL_WITH_VMS_FAILED(345), USER_VM_POOL_MAX_SUBSEQUENT_FAILURES_REACHED(358), @Deprecated USER_ATTACH_USER_TO_TIME_LEASED_POOL(328), @Deprecated USER_ATTACH_USER_TO_TIME_LEASED_POOL_FAILED(329), @Deprecated USER_DETACH_USER_FROM_TIME_LEASED_POOL(330), @Deprecated USER_DETACH_USER_FROM_TIME_LEASED_POOL_FAILED(331), @Deprecated USER_ATTACH_AD_GROUP_TO_TIME_LEASED_POOL(332), @Deprecated USER_ATTACH_AD_GROUP_TO_TIME_LEASED_POOL_FAILED(333), @Deprecated USER_DETACH_AD_GROUP_FROM_TIME_LEASED_POOL(334), @Deprecated USER_DETACH_AD_GROUP_FROM_TIME_LEASED_POOL_FAILED(335), @Deprecated USER_UPDATE_USER_TO_TIME_LEASED_POOL(336), @Deprecated USER_UPDATE_USER_TO_TIME_LEASED_POOL_FAILED(337), @Deprecated USER_UPDATE_AD_GROUP_TO_TIME_LEASED_POOL(338), @Deprecated USER_UPDATE_AD_GROUP_TO_TIME_LEASED_POOL_FAILED(339), USER_ADD_BOOKMARK(350), USER_ADD_BOOKMARK_FAILED(351), USER_UPDATE_BOOKMARK(352), USER_UPDATE_BOOKMARK_FAILED(353), USER_REMOVE_BOOKMARK(354), USER_REMOVE_BOOKMARK_FAILED(355), /** * AdGroups */ USER_ATTACH_VM_TO_AD_GROUP(400), USER_ATTACH_VM_TO_AD_GROUP_FAILED(401), USER_DETACH_VM_TO_AD_GROUP(402), USER_DETACH_VM_TO_AD_GROUP_FAILED(403), USER_ATTACH_VM_POOL_TO_AD_GROUP(404), USER_ATTACH_VM_POOL_TO_AD_GROUP_INTERNAL(470), USER_ATTACH_VM_POOL_TO_AD_GROUP_FAILED(405), USER_ATTACH_VM_POOL_TO_AD_GROUP_FAILED_INTERNAL(471), USER_DETACH_VM_POOL_TO_AD_GROUP(406), USER_DETACH_VM_POOL_TO_AD_GROUP_FAILED(407), USER_REMOVE_AD_GROUP(408), USER_REMOVE_AD_GROUP_FAILED(409), USER_UPDATE_TAG(430), USER_UPDATE_TAG_FAILED(431), USER_ADD_TAG(432), USER_ADD_TAG_FAILED(433), USER_REMOVE_TAG(434), USER_REMOVE_TAG_FAILED(435), USER_ATTACH_TAG_TO_USER(436), USER_ATTACH_TAG_TO_USER_FAILED(437), USER_ATTACH_TAG_TO_USER_GROUP(438), USER_ATTACH_TAG_TO_USER_GROUP_FAILED(439), USER_ATTACH_TAG_TO_VM(440), USER_ATTACH_TAG_TO_VM_FAILED(441), USER_ATTACH_TAG_TO_VDS(442), USER_ATTACH_TAG_TO_VDS_FAILED(443), USER_DETACH_VDS_FROM_TAG(444), USER_DETACH_VDS_FROM_TAG_FAILED(445), USER_DETACH_VM_FROM_TAG(446), USER_DETACH_VM_FROM_TAG_FAILED(447), USER_DETACH_USER_FROM_TAG(448), USER_DETACH_USER_FROM_TAG_FAILED(449), USER_DETACH_USER_GROUP_FROM_TAG(450), USER_DETACH_USER_GROUP_FROM_TAG_FAILED(451), USER_ATTACH_TAG_TO_USER_EXISTS(452), USER_ATTACH_TAG_TO_USER_GROUP_EXISTS(453), USER_ATTACH_TAG_TO_VM_EXISTS(454), USER_ATTACH_TAG_TO_VDS_EXISTS(455), USER_MOVE_TAG(555), USER_MOVE_TAG_FAILED(556), USER_LOGGED_IN_VM(456), USER_LOGGED_OUT_VM(457), USER_LOCKED_VM(458), USER_UNLOCKED_VM(459), USER_DETACH_USER_FROM_TIME_LEASED_POOL_INTERNAL(460), USER_DETACH_USER_FROM_TIME_LEASED_POOL_FAILED_INTERNAL(461), USER_DETACH_AD_GROUP_FROM_TIME_LEASED_POOL_INTERNAL(462), USER_DETACH_AD_GROUP_FROM_TIME_LEASED_POOL_FAILED_INTERNAL(463), UPDATE_TAGS_VM_DEFAULT_DISPLAY_TYPE(467), UPDATE_TAGS_VM_DEFAULT_DISPLAY_TYPE_FAILED(468), USER_ADD_VDS_GROUP(809), USER_ADD_VDS_GROUP_FAILED(810), USER_UPDATE_VDS_GROUP(811), USER_UPDATE_VDS_GROUP_FAILED(812), SYSTEM_UPDATE_VDS_GROUP(835, AuditLogTimeInterval.MINUTE.getValue()), SYSTEM_UPDATE_VDS_GROUP_FAILED(836, AuditLogTimeInterval.MINUTE.getValue()), USER_REMOVE_VDS_GROUP(813), USER_REMOVE_VDS_GROUP_FAILED(814), MAC_POOL_EMPTY(816), MAC_ADDRESS_IS_IN_USE(833), MAC_ADDRESS_IS_IN_USE_UNPLUG(838), CERTIFICATE_FILE_NOT_FOUND(817), RUN_VM_FAILED(818), MAC_ADDRESSES_POOL_NOT_INITIALIZED(837,AuditLogTimeInterval.HOUR.getValue()), // CBC VDS_REGISTER_ERROR_UPDATING_HOST(819), VDS_REGISTER_ERROR_UPDATING_HOST_ALL_TAKEN(820), VDS_REGISTER_HOST_IS_ACTIVE(821), VDS_REGISTER_ERROR_UPDATING_NAME(822), VDS_REGISTER_ERROR_UPDATING_NAMES_ALL_TAKEN(823), VDS_REGISTER_NAME_IS_ACTIVE(824), VDS_REGISTER_AUTO_APPROVE_PATTERN(825), VDS_REGISTER_FAILED(826), VDS_REGISTER_EXISTING_VDS_UPDATE_FAILED(827), VDS_REGISTER_SUCCEEDED(828), VDS_REGISTER_EMPTY_ID(834), VM_MIGRATION_ON_CONNECT_CHECK_FAILED(829), VM_MIGRATION_ON_CONNECT_CHECK_SUCCEEDED(830), // Network NETWORK_ATTACH_NETWORK_TO_VDS(920), NETWORK_ATTACH_NETWORK_TO_VDS_FAILED(921), NETWORK_DETACH_NETWORK_FROM_VDS(922), NETWORK_DETACH_NETWORK_FROM_VDS_FAILED(923), NETWORK_ADD_BOND(924), NETWORK_ADD_BOND_FAILED(925), NETWORK_REMOVE_BOND(926), NETWORK_REMOVE_BOND_FAILED(927), NETWORK_VDS_NETWORK_MATCH_CLUSTER(928), NETWORK_VDS_NETWORK_NOT_MATCH_CLUSTER(929), NETWORK_REMOVE_VM_INTERFACE(930), NETWORK_REMOVE_VM_INTERFACE_FAILED(931), NETWORK_ADD_VM_INTERFACE(932), NETWORK_ADD_VM_INTERFACE_FAILED(933), NETWORK_UPDATE_VM_INTERFACE(934), NETWORK_UPDATE_VM_INTERFACE_FAILED(935), NETWORK_ADD_TEMPLATE_INTERFACE(936), NETWORK_ADD_TEMPLATE_INTERFACE_FAILED(937), NETWORK_REMOVE_TEMPLATE_INTERFACE(938), NETWORK_REMOVE_TEMPLATE_INTERFACE_FAILED(939), NETWORK_UPDATE_TEMPLATE_INTERFACE(940), NETWORK_UPDATE_TEMPLATE_INTERFACE_FAILED(941), NETWORK_ADD_NETWORK(942), NETWORK_ADD_NETWORK_FAILED(943), NETWORK_REMOVE_NETWORK(944), NETWORK_REMOVE_NETWORK_FAILED(945), NETWORK_ATTACH_NETWORK_TO_VDS_GROUP(946), NETWORK_ATTACH_NETWORK_TO_VDS_GROUP_FAILED(947), NETWORK_DETACH_NETWORK_TO_VDS_GROUP(948), NETWORK_DETACH_NETWORK_TO_VDS_GROUP_FAILED(949), NETWORK_ACTIVATE_VM_INTERFACE_SUCCESS(1012), NETWORK_ACTIVATE_VM_INTERFACE_FAILURE(1013), NETWORK_DEACTIVATE_VM_INTERFACE_SUCCESS(1014), NETWORK_DEACTIVATE_VM_INTERFACE_FAILURE(1015), NETWORK_UPDATE_DISPLAY_TO_VDS_GROUP(1100), NETWORK_UPDATE_DISPLAY_TO_VDS_GROUP_FAILED(1101), NETWORK_UPDATE_NETWORK_TO_VDS_INTERFACE(1102), NETWORK_UPDATE_NETWORK_TO_VDS_INTERFACE_FAILED(1103), NETWORK_COMMINT_NETWORK_CHANGES(1104), NETWORK_COMMINT_NETWORK_CHANGES_FAILED(1105), @Deprecated NETWORK_HOST_USING_WRONG_CLUSER_VLAN(1106), @Deprecated NETWORK_HOST_MISSING_CLUSER_VLAN(1107), VDS_NETWORK_MTU_DIFFER_FROM_LOGICAL_NETWORK(1108, AuditLogTimeInterval.HOUR.getValue()), BRIDGED_NETWORK_OVER_MULTIPLE_INTERFACES(1109), VDS_NETWORKS_OUT_OF_SYNC(1110), NETWORK_UPDTAE_NETWORK_ON_CLUSTER(1112), NETWORK_UPDTAE_NETWORK_ON_CLUSTER_FAILED(1113), NETWORK_UPDATE_NETWORK(1114), NETWORK_UPDATE_NETWORK_FAILED(1115), NETWORK_UPDATE_VM_INTERFACE_LINK_UP(1116), NETWORK_UPDATE_VM_INTERFACE_LINK_DOWN(1117), INVALID_INTERFACE_FOR_MANAGEMENT_NETWORK_CONFIGURATION(1118), VLAN_ID_MISMATCH_FOR_MANAGEMENT_NETWORK_CONFIGURATION(1119), SETUP_NETWORK_FAILED_FOR_MANAGEMENT_NETWORK_CONFIGURATION(1120), PERSIST_NETWORK_FAILED_FOR_MANAGEMENT_NETWORK(1121), // Import/Export IMPORTEXPORT_STARTING_EXPORT_VM(1162), IMPORTEXPORT_EXPORT_VM(1150), IMPORTEXPORT_EXPORT_VM_FAILED(1151), IMPORTEXPORT_STARTING_IMPORT_VM(1165), IMPORTEXPORT_IMPORT_VM(1152), IMPORTEXPORT_IMPORT_VM_FAILED(1153), IMPORTEXPORT_STARTING_REMOVE_TEMPLATE(1166), IMPORTEXPORT_REMOVE_TEMPLATE(1154), IMPORTEXPORT_REMOVE_TEMPLATE_FAILED(1155), IMPORTEXPORT_EXPORT_TEMPLATE(1156), IMPORTEXPORT_STARTING_EXPORT_TEMPLATE(1164), IMPORTEXPORT_EXPORT_TEMPLATE_FAILED(1157), IMPORTEXPORT_STARTING_IMPORT_TEMPLATE(1163), IMPORTEXPORT_IMPORT_TEMPLATE(1158), IMPORTEXPORT_IMPORT_TEMPLATE_FAILED(1159), IMPORTEXPORT_STARTING_REMOVE_VM(1167), IMPORTEXPORT_REMOVE_VM(1160), IMPORTEXPORT_REMOVE_VM_FAILED(1161), IMPORTEXPORT_GET_VMS_INFO_FAILED(1162, AuditLogTimeInterval.MINUTE.getValue() * 30), IMPORTEXPORT_FAILED_TO_IMPORT_VM(1168), IMPORTEXPORT_FAILED_TO_IMPORT_TEMPLATE(1169), IMPORTEXPORT_IMPORT_TEMPLATE_INVALID_INTERFACES(1170, AuditLogTimeInterval.MINUTE.getValue()), USER_ADD_PERMISSION(850), USER_ADD_PERMISSION_FAILED(851), USER_REMOVE_PERMISSION(852), USER_REMOVE_PERMISSION_FAILED(853), USER_ADD_ROLE(854), USER_ADD_ROLE_FAILED(855), USER_UPDATE_ROLE(856), USER_UPDATE_ROLE_FAILED(857), USER_REMOVE_ROLE(858), USER_REMOVE_ROLE_FAILED(859), USER_ATTACHED_ACTION_GROUP_TO_ROLE(860), USER_ATTACHED_ACTION_GROUP_TO_ROLE_FAILED(861), USER_DETACHED_ACTION_GROUP_FROM_ROLE(862), USER_DETACHED_ACTION_GROUP_FROM_ROLE_FAILED(863), USER_ADD_ROLE_WITH_ACTION_GROUP(864), USER_ADD_ROLE_WITH_ACTION_GROUP_FAILED(865), // AD Computer Account AD_COMPUTER_ACCOUNT_SUCCEEDED(900), AD_COMPUTER_ACCOUNT_FAILED(901), USER_ADD_STORAGE_POOL(950), USER_ADD_STORAGE_POOL_FAILED(951), USER_UPDATE_STORAGE_POOL(952), USER_UPDATE_STORAGE_POOL_FAILED(953), USER_REMOVE_STORAGE_POOL(954), USER_REMOVE_STORAGE_POOL_FAILED(955), USER_ADD_STORAGE_DOMAIN(956), USER_ADD_STORAGE_DOMAIN_FAILED(957), USER_UPDATE_STORAGE_DOMAIN(958), USER_UPDATE_STORAGE_DOMAIN_FAILED(959), USER_REMOVE_STORAGE_DOMAIN(960), USER_REMOVE_STORAGE_DOMAIN_FAILED(961), USER_ATTACH_STORAGE_DOMAIN_TO_POOL(962), USER_ATTACH_STORAGE_DOMAIN_TO_POOL_FAILED(963), USER_DETACH_STORAGE_DOMAIN_FROM_POOL(964), USER_DETACH_STORAGE_DOMAIN_FROM_POOL_FAILED(965), USER_ACTIVATED_STORAGE_DOMAIN(966), USER_ACTIVATE_STORAGE_DOMAIN_FAILED(967), USER_DEACTIVATED_STORAGE_DOMAIN(968), USER_DEACTIVATE_STORAGE_DOMAIN_FAILED(969), SYSTEM_DEACTIVATED_STORAGE_DOMAIN(970, AuditLogTimeInterval.MINUTE.getValue()), SYSTEM_DEACTIVATE_STORAGE_DOMAIN_FAILED(971, AuditLogTimeInterval.MINUTE.getValue()), USER_EXTENDED_STORAGE_DOMAIN(972), USER_EXTENDED_STORAGE_DOMAIN_FAILED(973), @Deprecated USER_REMOVE_VG(974), @Deprecated USER_REMOVE_VG_FAILED(975), USER_ACTIVATE_STORAGE_POOL(976), USER_ACTIVATE_STORAGE_POOL_FAILED(977), SYSTEM_FAILED_CHANGE_STORAGE_POOL_STATUS(978, AuditLogTimeInterval.MINUTE.getValue()), SYSTEM_CHANGE_STORAGE_POOL_STATUS_NO_HOST_FOR_SPM(979, AuditLogTimeInterval.MINUTE.getValue()), SYSTEM_CHANGE_STORAGE_POOL_STATUS_PROBLEMATIC(980, AuditLogTimeInterval.MINUTE.getValue()), USER_FORCE_REMOVE_STORAGE_DOMAIN(981), USER_FORCE_REMOVE_STORAGE_DOMAIN_FAILED(982), RECONSTRUCT_MASTER_FAILED_NO_MASTER(983, AuditLogTimeInterval.HOUR.getValue()), RECONSTRUCT_MASTER_DONE(984), RECONSTRUCT_MASTER_FAILED(985, AuditLogTimeInterval.HOUR.getValue()), SYSTEM_CHANGE_STORAGE_POOL_STATUS_PROBLEMATIC_SEARCHING_NEW_SPM(986, AuditLogTimeInterval.MINUTE.getValue()), SYSTEM_CHANGE_STORAGE_POOL_STATUS_PROBLEMATIC_WITH_ERROR(987, AuditLogTimeInterval.MINUTE.getValue()), USER_CONNECT_HOSTS_TO_LUN_FAILED(988), SYSTEM_CHANGE_STORAGE_POOL_STATUS_PROBLEMATIC_FROM_NON_OPERATIONAL(989, AuditLogTimeInterval.MINUTE.getValue()), SYSTEM_MASTER_DOMAIN_NOT_IN_SYNC(990, AuditLogTimeInterval.MINUTE.getValue()), RECOVERY_STORAGE_POOL(991), RECOVERY_STORAGE_POOL_FAILED(992), SYSTEM_CHANGE_STORAGE_POOL_STATUS_RESET_IRS(993, AuditLogTimeInterval.MINUTE.getValue()), CONNECT_STORAGE_SERVERS_FAILED(994), CONNECT_STORAGE_POOL_FAILED(995), STORAGE_DOMAIN_ERROR(996), REFRESH_REPOSITORY_FILE_LIST_FAILED(997), REFRESH_REPOSITORY_FILE_LIST_SUCCEEDED(998), STORAGE_ALERT_VG_METADATA_CRITICALLY_FULL(999, AuditLogTimeInterval.MINUTE.getValue() * 10), STORAGE_ALERT_SMALL_VG_METADATA(1000, AuditLogTimeInterval.MINUTE.getValue() * 10), USER_ATTACH_STORAGE_DOMAINS_TO_POOL(1002), USER_ATTACH_STORAGE_DOMAINS_TO_POOL_FAILED(1003), STORAGE_DOMAIN_TASKS_ERROR(1004), UPDATE_OVF_FOR_STORAGE_POOL_FAILED(1005), UPGRADE_STORAGE_POOL_ENCOUNTERED_PROBLEMS(1006), RELOAD_CONFIGURATIONS_SUCCESS(1010), RELOAD_CONFIGURATIONS_FAILURE(1011), // Authentication USER_ACCOUNT_DISABLED_OR_LOCKED(1100, AuditLogTimeInterval.HOUR.getValue()), USER_ACCOUNT_PASSWORD_EXPIRED(1101, AuditLogTimeInterval.HOUR.getValue()), // Providers PROVIDER_ADDED(1150), PROVIDER_ADDITION_FAILED(1151), PROVIDER_UPDATED(1152), PROVIDER_UPDATE_FAILED(1153), PROVIDER_REMOVED(1154), PROVIDER_REMOVAL_FAILED(1155), // General ENTITY_RENAMED(1200), VDS_ALERT_FENCE_IS_NOT_CONFIGURED(9000), VDS_ALERT_FENCE_TEST_FAILED(9001), VDS_ALERT_FENCE_OPERATION_FAILED(9002), VDS_ALERT_FENCE_OPERATION_SKIPPED(9003), VDS_ALERT_FENCE_NO_PROXY_HOST(9004), VDS_ALERT_FENCE_STATUS_VERIFICATION_FAILED(9005), CANNOT_HIBERNATE_RUNNING_VMS_AFTER_CLUSTER_CPU_UPGRADE(9006), VDS_ALERT_SECONDARY_AGENT_USED_FOR_FENCE_OPERATION(9007), TASK_STOPPING_ASYNC_TASK(9500, AuditLogTimeInterval.MINUTE.getValue()), TASK_CLEARING_ASYNC_TASK(9501, AuditLogTimeInterval.MINUTE.getValue()), VDS_ACTIVATE_ASYNC(9502, AuditLogTimeInterval.HOUR.getValue() * 3), // When VDS is reactivated by autorecovery VDS_ACTIVATE_FAILED_ASYNC(9503, AuditLogTimeInterval.HOUR.getValue() * 3), // When VDS is reactivated STORAGE_ACTIVATE_ASYNC(9504, AuditLogTimeInterval.HOUR.getValue() * 3), // When VDS is reactivated by autorecovery USER_ACTIVATED_STORAGE_DOMAIN_ASYNC(9505, AuditLogTimeInterval.HOUR.getValue() * 3), USER_ACTIVATE_STORAGE_DOMAIN_FAILED_ASYNC(9506, AuditLogTimeInterval.HOUR.getValue() * 3), IMPORTEXPORT_IMPORT_VM_INVALID_INTERFACES(9600, AuditLogTimeInterval.MINUTE.getValue()), VDS_SET_NON_OPERATIONAL_VM_NETWORK_IS_BRIDGELESS(9601, AuditLogTimeInterval.MINUTE.getValue()), /** * A highly available virtual machine went down. */ HA_VM_FAILED(9602), /** * Restart of a highly available virtual machine failed. */ HA_VM_RESTART_FAILED(9603), // DWH DWH_STOPPED(9701), DWH_STARTED(9700), DWH_ERROR(9704), // External Events/Alerts EXTERNAL_EVENT_NORMAL(9801), EXTERNAL_EVENT_WARNING(9802), EXTERNAL_EVENT_ERROR(9803), EXTERNAL_ALERT(9804), //watchdog WATCHDOG_EVENT(9901), ; private int intValue; // indicates time interval in seconds on which identical events from same instance are supressed. private int duplicateEventsIntervalValue; private static java.util.HashMap<Integer, AuditLogType> mappings = new HashMap<Integer, AuditLogType>(); static { for (AuditLogType logType : values()) { mappings.put(logType.getValue(), logType); } } private AuditLogType(int value) { this(value, 0); } private AuditLogType(int value, int duplicateEventsInterval) { intValue = value; duplicateEventsIntervalValue = duplicateEventsInterval; } public int getValue() { return intValue; } public int getDuplicateEventsIntervalValue() { return duplicateEventsIntervalValue; } public static AuditLogType forValue(int value) { return mappings.get(value); } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.core.gui; import java.util.List; import org.pentaho.di.core.AddUndoPositionInterface; public class SnapAllignDistribute { private List<? extends GUIPositionInterface> elements; private AddUndoPositionInterface addUndoPositionInterface; private int[] indices; private Redrawable redrawable; private UndoInterface undoInterface; public SnapAllignDistribute(UndoInterface undoInterface, List<? extends GUIPositionInterface> elements, int[] indices, AddUndoPositionInterface addUndoPositionInterface, Redrawable redrawable) { this.undoInterface = undoInterface; this.elements = elements; this.indices = indices; this.addUndoPositionInterface = addUndoPositionInterface; this.redrawable = redrawable; } public void snaptogrid(int size) { if (elements.isEmpty()) return; // First look for the minimum x coordinate... GUIPositionInterface elemArray[] = new GUIPositionInterface[elements.size()]; Point before[] = new Point[elements.size()]; Point after[] = new Point[elements.size()]; for (int i = 0; i < elements.size(); i++) { GUIPositionInterface positionInterface = elements.get(i); elemArray[i] = positionInterface; Point p = positionInterface.getLocation(); before[i] = new Point(p.x, p.y); // What's the modulus ? int dx = p.x % size; int dy = p.y % size; // Correct the location to the nearest grid line! // This means for size = 10 // x = 3: dx=3, dx<=5 --> x=3-3 = 0; // x = 7: dx=7, dx> 5 --> x=3+10-3 = 10; // x = 10: dx=0, dx<=5 --> x=10-0 = 10; if (dx > size / 2) p.x += size - dx; else p.x -= dx; if (dy > size / 2) p.y += size - dy; else p.y -= dy; after[i] = new Point(p.x, p.y); } if (addUndoPositionInterface!=null) addUndoPositionInterface.addUndoPosition(undoInterface, elemArray, indices, before, after); redrawable.redraw(); } public void allignleft() { if (elements.isEmpty()) return; GUIPositionInterface elemArray[] = elements.toArray(new GUIPositionInterface[elements.size()]); Point before[] = new Point[elements.size()]; Point after[] = new Point[elements.size()]; int min = 99999; // First look for the minimum x coordinate... for (int i = 0; i < elements.size(); i++) { GUIPositionInterface element = elements.get(i); Point p = element.getLocation(); if (p.x < min) min = p.x; } // Then apply the coordinate... for (int i = 0; i < elements.size(); i++) { GUIPositionInterface element = elements.get(i); Point p = element.getLocation(); before[i] = new Point(p.x, p.y); element.setLocation(min, p.y); after[i] = new Point(min, p.y); } if (addUndoPositionInterface!=null) addUndoPositionInterface.addUndoPosition(undoInterface, elemArray, indices, before, after); redrawable.redraw(); } public void allignright() { if (elements.isEmpty()) return; GUIPositionInterface elemArray[] = elements.toArray(new GUIPositionInterface[elements.size()]); Point before[] = new Point[elements.size()]; Point after[] = new Point[elements.size()]; int max = -99999; // First look for the maximum x coordinate... for (int i = 0; i < elements.size(); i++) { GUIPositionInterface element = elements.get(i); Point p = element.getLocation(); if (p.x > max) max = p.x; } // Then apply the coordinate... for (int i = 0; i < elements.size(); i++) { GUIPositionInterface stepMeta = elements.get(i); Point p = stepMeta.getLocation(); before[i] = new Point(p.x, p.y); stepMeta.setLocation(max, p.y); after[i] = new Point(max, p.y); } if (addUndoPositionInterface!=null) addUndoPositionInterface.addUndoPosition(undoInterface, elemArray, indices, before, after); redrawable.redraw(); } public void alligntop() { if (elements.isEmpty()) return; GUIPositionInterface elemArray[] = elements.toArray(new GUIPositionInterface[elements.size()]); Point before[] = new Point[elements.size()]; Point after[] = new Point[elements.size()]; int min = 99999; // First look for the minimum y coordinate... for (int i = 0; i < elements.size(); i++) { GUIPositionInterface element = elements.get(i); Point p = element.getLocation(); if (p.y < min) min = p.y; } // Then apply the coordinate... for (int i = 0; i < elements.size(); i++) { GUIPositionInterface element = elements.get(i); Point p = element.getLocation(); before[i] = new Point(p.x, p.y); element.setLocation(p.x, min); after[i] = new Point(p.x, min); } if (addUndoPositionInterface!=null) addUndoPositionInterface.addUndoPosition(undoInterface, elemArray, indices, before, after); redrawable.redraw(); } public void allignbottom() { if (elements.isEmpty()) return; GUIPositionInterface elemArray[] = elements.toArray(new GUIPositionInterface[elements.size()]); Point before[] = new Point[elements.size()]; Point after[] = new Point[elements.size()]; int max = -99999; // First look for the maximum y coordinate... for (int i = 0; i < elements.size(); i++) { GUIPositionInterface element = elements.get(i); Point p = element.getLocation(); if (p.y > max) max = p.y; } // Then apply the coordinate... for (int i = 0; i < elements.size(); i++) { GUIPositionInterface element = elements.get(i); Point p = element.getLocation(); before[i] = new Point(p.x, p.y); element.setLocation(p.x, max); after[i] = new Point(p.x, max); } if (addUndoPositionInterface!=null) addUndoPositionInterface.addUndoPosition(undoInterface, elemArray, indices, before, after); redrawable.redraw(); } public void distributehorizontal() { if (elements.size() <= 1) return; GUIPositionInterface elemArray[] = elements.toArray(new GUIPositionInterface[elements.size()]); Point before[] = new Point[elements.size()]; Point after[] = new Point[elements.size()]; int min = 99999; int max = -99999; int order[] = new int[elements.size()]; // First look for the minimum & maximum x coordinate... for (int i = 0; i < elements.size(); i++) { GUIPositionInterface element = elements.get(i); Point p = element.getLocation(); if (p.x < min) min = p.x; if (p.x > max) max = p.x; order[i] = i; } // Difficult to keep the steps in the correct order. // If you just set the x-coordinates, you get special effects. // Best is to keep the current order of things. // First build an arraylist and store the order there. // Then sort order[], based upon the coordinate of the step. for (int i = 0; i < elements.size(); i++) { for (int j = 0; j < elements.size() - 1; j++) { Point p1 = (elements.get(order[j])).getLocation(); Point p2 = (elements.get(order[j+1])).getLocation(); if (p1.x > p2.x) // swap { int dummy = order[j]; order[j] = order[j + 1]; order[j + 1] = dummy; dummy = indices[j]; indices[j] = indices[j + 1]; indices[j + 1] = dummy; } } } // The distance between two steps becomes. int distance = (max - min) / (elements.size() - 1); for (int i = 0; i < elements.size(); i++) { GUIPositionInterface element = elements.get(order[i]); Point p = element.getLocation(); before[i] = new Point(p.x, p.y); p.x = min + (i * distance); after[i] = new Point(p.x, p.y); elemArray[i] = element; } // Undo! if (addUndoPositionInterface!=null) addUndoPositionInterface.addUndoPosition(undoInterface, elemArray, indices, before, after); redrawable.redraw(); } public void distributevertical() { if (elements.size() <= 1) return; GUIPositionInterface elemArray[] = elements.toArray(new GUIPositionInterface[elements.size()]); Point before[] = new Point[elements.size()]; Point after[] = new Point[elements.size()]; int min = 99999; int max = -99999; int order[] = new int[elements.size()]; // First look for the minimum & maximum y coordinate... for (int i = 0; i < elements.size(); i++) { GUIPositionInterface element = elements.get(i); Point p = element.getLocation(); if (p.y < min) min = p.y; if (p.y > max) max = p.y; order[i] = i; } // Difficult to keep the steps in the correct order. // If you just set the y-coordinates, you get special effects. // Best is to keep the current order of things. // First build an arraylist and store the order there. // Then sort order[], based upon the coordinate of the step. for (int i = 0; i < elements.size(); i++) { for (int j = 0; j < elements.size() - 1; j++) { Point p1 = (elements.get(order[j])).getLocation(); Point p2 = (elements.get(order[j+1])).getLocation(); if (p1.y > p2.y) // swap { int dummy = order[j]; order[j] = order[j + 1]; order[j + 1] = dummy; dummy = indices[j]; indices[j] = indices[j + 1]; indices[j + 1] = dummy; } } } // The distance between two steps becomes. int distance = (max - min) / (elements.size() - 1); for (int i = 0; i < elements.size(); i++) { GUIPositionInterface element = elements.get(order[i]); Point p = element.getLocation(); before[i] = new Point(p.x, p.y); p.y = min + (i * distance); after[i] = new Point(p.x, p.y); elemArray[i] = element; } // Undo! if (addUndoPositionInterface!=null) addUndoPositionInterface.addUndoPosition(undoInterface, elemArray, indices, before, after); redrawable.redraw(); } }
/** * Copyright © 2016-2018 dujoy.cn */ package org.thingsboard.server.dao.model.nosql; import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import com.fasterxml.jackson.databind.JsonNode; import lombok.EqualsAndHashCode; import lombok.ToString; import org.thingsboard.server.common.data.id.RuleId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.plugin.ComponentLifecycleState; import org.thingsboard.server.common.data.rule.RuleMetaData; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.model.SearchTextEntity; import org.thingsboard.server.dao.model.type.ComponentLifecycleStateCodec; import org.thingsboard.server.dao.model.type.JsonCodec; import java.util.UUID; import static org.thingsboard.server.dao.model.ModelConstants.*; @Table(name = RULE_COLUMN_FAMILY_NAME) @EqualsAndHashCode @ToString public class RuleMetaDataEntity implements SearchTextEntity<RuleMetaData> { @PartitionKey @Column(name = ID_PROPERTY) private UUID id; @ClusteringColumn @Column(name = RULE_TENANT_ID_PROPERTY) private UUID tenantId; @Column(name = RULE_NAME_PROPERTY) private String name; @Column(name = RULE_STATE_PROPERTY, codec = ComponentLifecycleStateCodec.class) private ComponentLifecycleState state; @Column(name = RULE_WEIGHT_PROPERTY) private int weight; @Column(name = SEARCH_TEXT_PROPERTY) private String searchText; @Column(name = RULE_PLUGIN_TOKEN_PROPERTY) private String pluginToken; @Column(name = RULE_FILTERS, codec = JsonCodec.class) private JsonNode filters; @Column(name = RULE_PROCESSOR, codec = JsonCodec.class) private JsonNode processor; @Column(name = RULE_ACTION, codec = JsonCodec.class) private JsonNode action; @Column(name = ADDITIONAL_INFO_PROPERTY, codec = JsonCodec.class) private JsonNode additionalInfo; public RuleMetaDataEntity() { } public RuleMetaDataEntity(RuleMetaData rule) { if (rule.getId() != null) { this.id = rule.getUuidId(); } this.tenantId = DaoUtil.getId(rule.getTenantId()); this.name = rule.getName(); this.pluginToken = rule.getPluginToken(); this.state = rule.getState(); this.weight = rule.getWeight(); this.searchText = rule.getName(); this.filters = rule.getFilters(); this.processor = rule.getProcessor(); this.action = rule.getAction(); this.additionalInfo = rule.getAdditionalInfo(); } @Override public String getSearchTextSource() { return getSearchText(); } @Override public void setSearchText(String searchText) { this.searchText = searchText; } @Override public UUID getId() { return id; } @Override public void setId(UUID id) { this.id = id; } public UUID getTenantId() { return tenantId; } public void setTenantId(UUID tenantId) { this.tenantId = tenantId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ComponentLifecycleState getState() { return state; } public void setState(ComponentLifecycleState state) { this.state = state; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public String getPluginToken() { return pluginToken; } public void setPluginToken(String pluginToken) { this.pluginToken = pluginToken; } public String getSearchText() { return searchText; } public JsonNode getFilters() { return filters; } public void setFilters(JsonNode filters) { this.filters = filters; } public JsonNode getProcessor() { return processor; } public void setProcessor(JsonNode processor) { this.processor = processor; } public JsonNode getAction() { return action; } public void setAction(JsonNode action) { this.action = action; } public JsonNode getAdditionalInfo() { return additionalInfo; } public void setAdditionalInfo(JsonNode additionalInfo) { this.additionalInfo = additionalInfo; } @Override public RuleMetaData toData() { RuleMetaData rule = new RuleMetaData(new RuleId(id)); rule.setTenantId(new TenantId(tenantId)); rule.setName(name); rule.setState(state); rule.setWeight(weight); rule.setCreatedTime(UUIDs.unixTimestamp(id)); rule.setPluginToken(pluginToken); rule.setFilters(filters); rule.setProcessor(processor); rule.setAction(action); rule.setAdditionalInfo(additionalInfo); return rule; } }
package com.fxgraph.graph; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fxgraph.layout.Layout; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.scene.Parent; import javafx.scene.input.MouseEvent; import javafx.scene.input.ScrollEvent; import javafx.scene.layout.Region; public class Graph { private final Model model; private final PannableCanvas pannableCanvas; private final Map<IGraphNode, Region> graphics; private final NodeGestures nodeGestures; private final ViewportGestures viewportGestures; private final BooleanProperty useNodeGestures; private final BooleanProperty useViewportGestures; public Graph() { this(new Model()); } public Graph(Model model) { this.model = model; nodeGestures = new NodeGestures(this); useNodeGestures = new SimpleBooleanProperty(true); useNodeGestures.addListener((obs, oldVal, newVal) -> { if (newVal) { model.getAllCells().forEach(cell -> nodeGestures.makeDraggable(getGraphic(cell))); } else { model.getAllCells().forEach(cell -> nodeGestures.makeUndraggable(getGraphic(cell))); } }); pannableCanvas = new PannableCanvas(); viewportGestures = new ViewportGestures(pannableCanvas); useViewportGestures = new SimpleBooleanProperty(true); useViewportGestures.addListener((obs, oldVal, newVal) -> { final Parent parent = pannableCanvas.parentProperty().get(); if (parent == null) { return; } if (newVal) { parent.addEventHandler(MouseEvent.MOUSE_PRESSED, viewportGestures.getOnMousePressedEventHandler()); parent.addEventHandler(MouseEvent.MOUSE_DRAGGED, viewportGestures.getOnMouseDraggedEventHandler()); parent.addEventHandler(ScrollEvent.ANY, viewportGestures.getOnScrollEventHandler()); } else { parent.removeEventHandler(MouseEvent.MOUSE_PRESSED, viewportGestures.getOnMousePressedEventHandler()); parent.removeEventHandler(MouseEvent.MOUSE_DRAGGED, viewportGestures.getOnMouseDraggedEventHandler()); parent.removeEventHandler(ScrollEvent.ANY, viewportGestures.getOnScrollEventHandler()); } }); pannableCanvas.parentProperty().addListener((obs, oldVal, newVal) -> { if (oldVal != null) { oldVal.removeEventHandler(MouseEvent.MOUSE_PRESSED, viewportGestures.getOnMousePressedEventHandler()); oldVal.removeEventHandler(MouseEvent.MOUSE_DRAGGED, viewportGestures.getOnMouseDraggedEventHandler()); oldVal.removeEventHandler(ScrollEvent.ANY, viewportGestures.getOnScrollEventHandler()); } if (newVal != null) { newVal.addEventHandler(MouseEvent.MOUSE_PRESSED, viewportGestures.getOnMousePressedEventHandler()); newVal.addEventHandler(MouseEvent.MOUSE_DRAGGED, viewportGestures.getOnMouseDraggedEventHandler()); newVal.addEventHandler(ScrollEvent.ANY, viewportGestures.getOnScrollEventHandler()); } }); graphics = new HashMap<>(); addEdges(getModel().getAllEdges()); addCells(getModel().getAllCells()); } public PannableCanvas getCanvas() { return pannableCanvas; } public Model getModel() { return model; } public void beginUpdate() { getCanvas().getChildren().clear(); } public void endUpdate() { // add components to graph pane addEdges(model.getAddedEdges()); addCells(model.getAddedCells()); // remove components to graph pane removeEdges(model.getRemovedEdges()); removeCells(model.getRemovedCells()); // clean up the model getModel().endUpdate(); } private void addEdges(List<IEdge> edges) { edges.forEach(edge -> { try { Region edgeGraphic = getGraphic(edge); getCanvas().getChildren().add(edgeGraphic); edge.onAddedToGraph(this, edgeGraphic); } catch (final Exception e) { throw new RuntimeException("failed to add " + edge, e); } }); } private void removeEdges(List<IEdge> edges) { edges.forEach(edge -> { try { Region edgeGraphic = getGraphic(edge); getCanvas().getChildren().remove(edgeGraphic); edge.onRemovedFromGraph(this, edgeGraphic); } catch (final Exception e) { throw new RuntimeException("failed to remove " + edge, e); } }); } private void addCells(List<ICell> cells) { cells.forEach(cell -> { try { Region cellGraphic = getGraphic(cell); getCanvas().getChildren().add(cellGraphic); if (useNodeGestures.get()) { nodeGestures.makeDraggable(cellGraphic); } cell.onAddedToGraph(this, cellGraphic); } catch (final Exception e) { throw new RuntimeException("failed to add " + cell, e); } }); } private void removeCells(List<ICell> cells) { cells.forEach(cell -> { try { Region cellGraphic = getGraphic(cell); getCanvas().getChildren().remove(cellGraphic); cell.onRemovedFromGraph(this, cellGraphic); } catch (final Exception e) { throw new RuntimeException("failed to remove " + cell, e); } }); } public Region getGraphic(IGraphNode node) { try { if (!graphics.containsKey(node)) { graphics.put(node, createGraphic(node)); } return graphics.get(node); } catch (final Exception e) { e.printStackTrace(); throw e; } } public Region createGraphic(IGraphNode node) { return node.getGraphic(this); } public double getScale() { return getCanvas().getScale(); } public void layout(Layout layout) { layout.execute(this); } public NodeGestures getNodeGestures() { return nodeGestures; } public BooleanProperty getUseNodeGestures() { return useNodeGestures; } public ViewportGestures getViewportGestures() { return viewportGestures; } public BooleanProperty getUseViewportGestures() { return useViewportGestures; } }
/* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cache.config; /** * Basic service interface. * * @author Costin Leau * @author Phillip Webb * @author Stephane Nicoll */ public interface CacheableService<T> { T cache(Object arg1); T cacheNull(Object arg1); T cacheSync(Object arg1); T cacheSyncNull(Object arg1); void invalidate(Object arg1); void evictEarly(Object arg1); void evictAll(Object arg1); void evictWithException(Object arg1); void evict(Object arg1, Object arg2); void invalidateEarly(Object arg1, Object arg2); T conditional(int field); T conditionalSync(int field); T unless(int arg); T key(Object arg1, Object arg2); T varArgsKey(Object... args); T name(Object arg1); T nullValue(Object arg1); T update(Object arg1); T conditionalUpdate(Object arg2); Number nullInvocations(); T rootVars(Object arg1); T customKeyGenerator(Object arg1); T unknownCustomKeyGenerator(Object arg1); T customCacheManager(Object arg1); T unknownCustomCacheManager(Object arg1); T throwChecked(Object arg1) throws Exception; T throwUnchecked(Object arg1); T throwCheckedSync(Object arg1) throws Exception; T throwUncheckedSync(Object arg1); // multi annotations T multiCache(Object arg1); T multiEvict(Object arg1); T multiCacheAndEvict(Object arg1); T multiConditionalCacheAndEvict(Object arg1); T multiUpdate(Object arg1); TestEntity putRefersToResult(TestEntity arg1); }
/** * Copyright (c) 2009 Pyxis Technologies inc. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * 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 program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, * or see the FSF site: http://www.fsf.org. */ package com.greenpepper.interpreter; import com.greenpepper.interpreter.flow.AbstractFlowInterpreter; import com.greenpepper.interpreter.flow.scenario.ScenarioRowSelector; import com.greenpepper.reflect.Fixture; public class ScenarioInterpreter extends AbstractFlowInterpreter { public ScenarioInterpreter(Fixture fixture) { setRowSelector( new ScenarioRowSelector( fixture ) ); } }
// Copyright 2020 Mavenir // // 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.xgvela.updateconfig; import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.databind.JsonNode; import org.xgvela.cnf.Constants; import org.xgvela.cnf.notification.NotificationUtil; import org.xgvela.cnf.util.MetricsUtil; import io.prometheus.client.Counter; @RestController public class UpdateConfigController { private static Logger LOG = LogManager.getLogger(UpdateConfigController.class); private static final Counter fmaasConfigUpdateattemptTotal = MetricsUtil .addCounter("fmaas_config_update_attempt_total", "The number of times FMaaS config update attempted"); @Autowired UpdateConfigHelper updateConfigHelper; @PostMapping(path = "/updateConfig") @ResponseStatus(HttpStatus.OK) public @ResponseBody String updateConfig(@RequestBody JsonNode diffNode) throws IOException { fmaasConfigUpdateattemptTotal.inc(); LOG.debug("Recieved request for config update"); try { NotificationUtil.sendEvent("FmaasConfigUpdateAttempted", updateConfigHelper.getAttemptMgdObjs(diffNode)); LOG.info(Constants.ACTIVITY + Constants.INIT + "FMaaS config update attempt starts "); } catch (Exception e1) { LOG.error(e1.getMessage(), e1 + "Error occured while raising FmaasConfigUpdateAttempted event"); } LOG.info("Json object recieved from cim:" + diffNode.toString()); Boolean done = false; if (diffNode.get("config-patch").asText() != null) { done = updateConfigHelper.updateFmaasConfig(diffNode.get("config-patch").asText()); } else { LOG.error("config-patch is null, check diffnode provided by CIM"); } String status = "failure"; if (done) { status = "success"; } updateConfigHelper.publishToCim(diffNode, done); LOG.debug("Config update request completed"); return status; } }
package cz.mg.entity.common; import cz.mg.annotations.classes.Entity; import cz.mg.annotations.storage.Value; import cz.mg.entity.services.factories.EntityClassFactory; import cz.mg.entity.utilities.EntityClass; public @Entity class TestEntitySubClass extends TestEntityClass { public static EntityClass entity = EntityClassFactory.getInstance().create(TestEntitySubClass.class); private @Value String fooBar; public TestEntitySubClass() { } @Value public String getFooBar() { return fooBar; } public void setFooBar(String fooBar) { this.fooBar = fooBar; } }
/* * Copyright 2008-present MongoDB, 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. */ /** * Contains classes that manage connecting to MongoDB servers. */ package com.mongodb.connection;
/* * Copyright (C) 2020 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.systemui.screenshot; import static com.android.systemui.screenshot.LogConfig.DEBUG_ACTIONS; import static com.android.systemui.screenshot.ScreenshotController.EXTRA_ACTION_INTENT; import static com.android.systemui.screenshot.ScreenshotController.EXTRA_ACTION_TYPE; import static com.android.systemui.screenshot.ScreenshotController.EXTRA_ID; import android.app.ActivityOptions; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import javax.inject.Inject; /** * Executes the smart action tapped by the user in the notification. */ public class SmartActionsReceiver extends BroadcastReceiver { private static final String TAG = "SmartActionsReceiver"; private final ScreenshotSmartActions mScreenshotSmartActions; @Inject SmartActionsReceiver(ScreenshotSmartActions screenshotSmartActions) { mScreenshotSmartActions = screenshotSmartActions; } @Override public void onReceive(Context context, Intent intent) { PendingIntent pendingIntent = intent.getParcelableExtra(EXTRA_ACTION_INTENT); String actionType = intent.getStringExtra(EXTRA_ACTION_TYPE); if (DEBUG_ACTIONS) { Log.d(TAG, "Executing smart action [" + actionType + "]:" + pendingIntent.getIntent()); } ActivityOptions opts = ActivityOptions.makeBasic(); try { pendingIntent.send(context, 0, null, null, null, null, opts.toBundle()); } catch (PendingIntent.CanceledException e) { Log.e(TAG, "Pending intent canceled", e); } mScreenshotSmartActions.notifyScreenshotAction( context, intent.getStringExtra(EXTRA_ID), actionType, true, pendingIntent.getIntent()); } }
public class IntegerToEnglishWord { class Solution { public String numberToWords(int num) { if (num == 0){ return "Zero"; } else { StringBuilder sb = new StringBuilder(); while (num > 0){ if (num >= 1_000_000_000){ } } } } public String say(int x){ switch (x){ case 1: return "One"; case 2: return "Two"; case 3: return "Three"; case 4: return "Four"; case 5: return "Five"; case 6: return "Six"; case 7: return "Seven"; case 8: return "Eight"; case 9: return "Nine"; case 10: return "Ten"; case 11: return "Eleven"; case 12: return "Twelve"; } } public int pos(int x){ if (x >= 10){ } } }
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // This file is a part of the 'gewt-material' project. // Copyright 2016 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany // // 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 de.esoco.ewt.impl.gwt.material.widget; import gwt.material.design.client.ui.MaterialLink; import de.esoco.ewt.graphics.Image; import de.esoco.ewt.property.ImageAttribute; import com.google.gwt.user.client.ui.HasText; /******************************************************************** * A {@link MaterialLink} subclass that also implements {@link HasText}. * * @author eso */ public class GewtMaterialLink extends MaterialLink implements HasText, ImageAttribute { //~ Instance fields -------------------------------------------------------- private ImageAttributeMixin<GewtMaterialLink> aImageAttrMixin = new ImageAttributeMixin<>(this); //~ Methods ---------------------------------------------------------------- /*************************************** * {@inheritDoc} */ @Override public Image getImage() { return aImageAttrMixin.getImage(); } /*************************************** * {@inheritDoc} */ @Override public void setImage(Image rImage) { aImageAttrMixin.setImage(rImage); } }
/* * 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. * * Copyright 2012-2018 the original author or authors. */ package org.assertj.swing.monitor; import static org.assertj.core.api.Assertions.assertThat; import java.awt.Window; import java.util.Map; import org.junit.Test; /** * Tests for {@link WindowEventQueueMapping#addQueueFor(java.awt.Toolkit)}. * * @author Alex Ruiz */ public class WindowEventQueueMapping_addQueueForToolkit_Test extends WindowEventQueueMapping_TestCase { @Test public void should_Add_Queue_For_Toolkit() { mapping.addQueueFor(toolkit); assertThat(queueMap).hasSize(1); assertThat(queueMap.keySet()).contains(eventQueue); Map<Window, Boolean> windowMapping = queueMap.get(eventQueue); assertThat(windowMapping).isEmpty(); } }
package java.nio; import java.nio.impl.*; public abstract class ByteBuffer { protected ByteOrder order; public static ByteBuffer allocate(int capacity) { return new ArrayByteBufferImpl(capacity); } public static ByteBuffer allocateDirect(int capacity) { return new DirectByteBufferImpl(capacity); } public abstract CharBuffer asCharBuffer(); public abstract DoubleBuffer asDoubleBuffer(); public abstract FloatBuffer asFloatBuffer(); public abstract IntBuffer asIntBuffer(); public abstract LongBuffer asLongBuffer(); public abstract ShortBuffer asShortBuffer(); public abstract ByteBuffer asReadOnlyBuffer(); public abstract ByteBuffer compact(); public abstract ByteBuffer duplicate(); public abstract byte get(); public abstract byte get(int index); public abstract char getChar(); public abstract char getChar(int index); public abstract double getDouble(); public abstract double getDouble(int index); public abstract float getFloat(); public abstract float getFloat(int index); public abstract int getInt(); public abstract int getInt(int index); public abstract long getLong(); public abstract long getLong(int index); public abstract short getShort(); public abstract short getShort(int index); public abstract ByteBuffer put(byte b); public abstract ByteBuffer put(int index, byte b); public abstract ByteBuffer putChar(char b); public abstract ByteBuffer putChar(int index, char b); public abstract ByteBuffer putDouble(double b); public abstract ByteBuffer putDouble(int index, double b); public abstract ByteBuffer putFloat(float b); public abstract ByteBuffer putFloat(int index, float b); public abstract ByteBuffer putInt(int b); public abstract ByteBuffer putInt(int index, int b); public abstract ByteBuffer putLong(long b); public abstract ByteBuffer putLong(int index, long b); public abstract ByteBuffer putShort(short b); public abstract ByteBuffer putShort(int index, short b); public abstract boolean isDirect(); public abstract ByteBuffer slice(); public final ByteOrder order() { return order; } public final ByteBuffer order(ByteOrder o) { order = o; } public byte[] array() { return null; } public int arrayOffset() { return 0; } public boolean equals(Object o) { if (o instanceof ByteBuffer) { ByteBuffer buf = (ByteBuffer) o; if (buf.capacity() == capacity()) { byte[] array = new byte[buf.capacity()]; buf.get(array, 0, buf.capacity()); for (int i = 0; i < array.length; i++) { if (get(i) != buf.get(i)) { return false; } } return true; } } return false; } public ByteBuffer get(byte[] dst, int offset, int length) { if (remaining() < length) { throw new BufferUnderflowException(); } for (int i = 0; i < length; i++) { dst[i + offset] = get(); } } public ByteBuffer get(byte[] dst) { return get(dst, 0, dst.length); } public ByteBuffer put(ByteBuffer src) { if (isReadOnly()) { throw new ReadOnlyBufferException(); } if (src.remaining() > remaining()) { throw new BufferOverflowException(); } while (src.hasRemaining()) { put(src.get()); } } public ByteBuffer put(byte[] src, int offset, int length) { if (isReadOnly()) { throw new ReadOnlyBufferException(); } if (src.length > remaining()) { throw new BufferOverflowException(); } for (int i = 0; i < length; i++) { put(src[i + offset]); } } public ByteBuffer put(byte[] src) { put(src, 0, src.length); } public final boolean hasArray() { return true; } public int hashCode() { int x = remaining(); x += (int) get(limit() - 1); return x; } }
package org.tec.datastructures; public class DoubleList<T> { private DoubleNode<T> root; private int length = 0; DoubleList(){ this.root = null; } public void addNode(DoubleNode<T> newNode) { if(this.root == null) { this.root = newNode; this.length++; } else { DoubleNode<T> current = this.root; while(current.getNext()!=null) { current = current.getNext(); } current.setNext(newNode); newNode.setPrev(current); this.length++; } } public DoubleNode<T> getNode(int ind) { DoubleNode<T> current = this.root; while(ind > 0) { current = current.getNext(); } return current; } public T getNodeData(int ind) { DoubleNode<T> current = this.root; while(ind > 0) { current = current.getNext(); } return current.getData(); } public void deleteNode(T data) { DoubleNode<T> current = this.root; if(this.root.getData().equals(data)) { DoubleNode<T> next = this.root.getNext(); this.root.setNext(null); this.root.setPrev(null); this.root = next; this.root.setPrev(null); this.length--; } while(!current.getNext().getData().equals(data)) { current = current.getNext(); } current.getNext().setPrev(null); current.setNext(current.getNext().getNext()); current.getNext().getPrev().setNext(null); current.getNext().setPrev(current); this.length--; } public void printNodes() { DoubleNode<T> current = this.root; while(current!= null) { System.out.println(current.getData()); current = current.getNext(); } } public DoubleNode<T> getRoot() { return root; } public void setRoot(DoubleNode<T> root) { this.root = root; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public static void main(String[] args) { // TODO Auto-generated method stub } }
/******************************************************************************* * Copyright (c) 2011, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * dmccann - March 25/2010 - 2.1 - Initial implementation ******************************************************************************/ package org.eclipse.persistence.testing.jaxb.externalizedmetadata.exceptions; import org.eclipse.persistence.testing.jaxb.externalizedmetadata.exceptions.contextfactory.ExceptionHandlingTestCases; import junit.framework.Test; import junit.framework.TestSuite; /** * Suite for testing externalized metadata exception handling. * */ public class ExceptionHandlingTestSuite extends TestSuite { public static Test suite() { TestSuite suite = new TestSuite("Exception Handling Test Suite"); suite.addTestSuite(ExceptionHandlingTestCases.class); return suite; } public static void main(String[] args) { String[] arguments = { "-c", "org.eclipse.persistence.testing.jaxb.externalizedmetadata.exceptions.ExceptionHandlingTestSuite" }; junit.textui.TestRunner.main(arguments); } }
package mage.game.permanent.token; import mage.MageInt; import mage.constants.CardType; import mage.constants.SubType; /** * @author mschatz */ public final class AetherbornGreenToken extends TokenImpl { public AetherbornGreenToken(int power_val, int toughness_val) { super("AetherbornGreen", power_val + "/" + toughness_val + " green Aetherborn creature token"); cardType.add(CardType.CREATURE); color.setGreen(true); subtype.add(SubType.AETHERBORN ); power = new MageInt(power_val); toughness = new MageInt(toughness_val); } public AetherbornGreenToken() { this(1, 1); } public AetherbornGreenToken(final AetherbornGreenToken token) { super(token); } public AetherbornGreenToken copy() { return new AetherbornGreenToken(this); } }
/* * Hibernate Validator, declare and validate application constraints * * License: Apache License, Version 2.0 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. */ package org.hibernate.validator.test.internal.xml; import static org.hibernate.validator.internal.util.CollectionHelper.asSet; import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertNoViolations; import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertThat; import static org.hibernate.validator.testutil.ConstraintViolationAssert.pathWith; import static org.hibernate.validator.testutil.ConstraintViolationAssert.violationOf; import static org.testng.Assert.assertEquals; import java.io.InputStream; import java.lang.annotation.ElementType; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.validation.BootstrapConfiguration; import javax.validation.Configuration; import javax.validation.ConstraintViolation; import javax.validation.ValidationException; import javax.validation.Validator; import javax.validation.ValidatorFactory; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.validation.executable.ExecutableType; import javax.validation.groups.Default; import javax.validation.metadata.MethodDescriptor; import org.hibernate.validator.HibernateValidator; import org.hibernate.validator.HibernateValidatorConfiguration; import org.hibernate.validator.cfg.ConstraintMapping; import org.hibernate.validator.cfg.defs.SizeDef; import org.hibernate.validator.testutil.TestForIssue; import org.hibernate.validator.testutil.ValidationXmlTestHelper; import org.hibernate.validator.testutils.ValidatorUtil; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * @author Hardy Ferentschik * @author Gunnar Morling */ public class XmlMappingTest { private static ValidationXmlTestHelper validationXmlTestHelper; @BeforeClass public static void setupValidationXmlTestHelper() { validationXmlTestHelper = new ValidationXmlTestHelper( XmlMappingTest.class ); } @Test @TestForIssue(jiraKey = "HV-214") public void testConstraintInheritanceWithXmlConfiguration() { final Configuration<?> configuration = ValidatorUtil.getConfiguration(); configuration.addMapping( XmlMappingTest.class.getResourceAsStream( "mapping.xml" ) ); final ValidatorFactory validatorFactory = configuration.buildValidatorFactory(); final Validator validator = validatorFactory.getValidator(); final Set<ConstraintViolation<Customer>> violations = validator.validate( new Customer(), Default.class ); assertThat( violations ).containsOnlyViolations( violationOf( NotNull.class ) ); } @Test @TestForIssue(jiraKey = "HV-252") public void testListOfString() { final Configuration<?> configuration = ValidatorUtil.getConfiguration(); configuration.addMapping( XmlMappingTest.class.getResourceAsStream( "properties-mapping.xml" ) ); final ValidatorFactory validatorFactory = configuration.buildValidatorFactory(); final Validator validator = validatorFactory.getValidator(); List<String> listOfString = new ArrayList<String>(); listOfString.add( "one" ); listOfString.add( "two" ); listOfString.add( "three" ); final Set<ConstraintViolation<Properties>> violations = validator.validateValue( Properties.class, "listOfString", listOfString ); assertNoViolations( violations ); } @Test @TestForIssue(jiraKey = "HV-262") public void testInterfaceConfiguration() { final Configuration<?> configuration = ValidatorUtil.getConfiguration(); configuration.addMapping( XmlMappingTest.class.getResourceAsStream( "my-interface-mapping.xml" ) ); final ValidatorFactory validatorFactory = configuration.buildValidatorFactory(); final Validator validator = validatorFactory.getValidator(); final Set<ConstraintViolation<MyInterfaceImpl>> violations = validator.validate( new MyInterfaceImpl() ); assertThat( violations ).containsOnlyViolations( violationOf( NotNull.class ) ); } @Test @TestForIssue(jiraKey = "HV-262") public void testInterfaceImplementationConfiguration() { final Configuration<?> configuration = ValidatorUtil.getConfiguration(); configuration.addMapping( XmlMappingTest.class.getResourceAsStream( "my-interface-impl-mapping.xml" ) ); final ValidatorFactory validatorFactory = configuration.buildValidatorFactory(); final Validator validator = validatorFactory.getValidator(); final Set<ConstraintViolation<MyInterfaceImpl>> violations = validator.validate( new MyInterfaceImpl() ); assertThat( violations ).containsOnlyViolations( violationOf( NotNull.class ) ); } @Test @TestForIssue(jiraKey = "HV-263") public void testEmptyInterfaceConfiguration() { final Configuration<?> configuration = ValidatorUtil.getConfiguration(); configuration.addMapping( XmlMappingTest.class.getResourceAsStream( "empty-my-interface-mapping.xml" ) ); final ValidatorFactory validatorFactory = configuration.buildValidatorFactory(); final Validator validator = validatorFactory.getValidator(); final Set<ConstraintViolation<MyInterfaceImpl>> violations = validator.validate( new MyInterfaceImpl() ); assertNoViolations( violations ); } @Test @TestForIssue(jiraKey = "HV-480") public void testConstraintsFromXmlAndProgrammaticApiAddUp() { final HibernateValidatorConfiguration configuration = ValidatorUtil.getConfiguration( HibernateValidator.class ); //given final ConstraintMapping programmaticMapping = configuration.createConstraintMapping(); programmaticMapping.type( Customer.class ) .property( "firstName", ElementType.FIELD ) .constraint( new SizeDef().min( 2 ).max( 10 ) ); final InputStream xmlMapping = XmlMappingTest.class.getResourceAsStream( "hv-480-mapping.xml" ); configuration.addMapping( programmaticMapping ); configuration.addMapping( xmlMapping ); final Customer customer = new Customer(); customer.setFirstName( "" ); //when final Set<ConstraintViolation<Customer>> violations = configuration.buildValidatorFactory() .getValidator() .validate( customer ); //then assertThat( violations ).containsOnlyViolations( violationOf( Size.class ).withMessage( "size must be between 1 and 10" ), violationOf( Size.class ).withMessage( "size must be between 2 and 10" ) ); } @Test public void shouldLoadBv11ConstraintMapping() { final Configuration<?> configuration = ValidatorUtil.getConfiguration(); configuration.addMapping( XmlMappingTest.class.getResourceAsStream( "my-interface-impl-mapping-bv-1.1.xml" ) ); final ValidatorFactory validatorFactory = configuration.buildValidatorFactory(); final Validator validator = validatorFactory.getValidator(); final Set<ConstraintViolation<MyInterfaceImpl>> violations = validator.validate( new MyInterfaceImpl() ); assertThat( violations ).containsOnlyViolations( violationOf( NotNull.class ) ); } @Test( expectedExceptions = ValidationException.class, expectedExceptionsMessageRegExp = "HV000122: Unsupported schema version for constraint mapping file: 1\\.2\\." ) public void shouldFailToLoadConstraintMappingWithUnsupportedVersion() { final Configuration<?> configuration = ValidatorUtil.getConfiguration(); configuration.addMapping( XmlMappingTest.class.getResourceAsStream( "my-interface-impl-mapping-unsupported-version.xml" ) ); final ValidatorFactory validatorFactory = configuration.buildValidatorFactory(); final Validator validator = validatorFactory.getValidator(); final Set<ConstraintViolation<MyInterfaceImpl>> violations = validator.validate( new MyInterfaceImpl() ); assertThat( violations ).containsOnlyViolations( violationOf( NotNull.class ) ); } @Test public void testParameterNameProviderConfiguration() { validationXmlTestHelper.runWithCustomValidationXml( "parameter-name-provider-validation.xml", new Runnable() { @Override public void run() { //given Validator validator = ValidatorUtil.getValidator(); BootstrapConfiguration bootstrapConfiguration = ValidatorUtil.getConfiguration() .getBootstrapConfiguration(); //when MethodDescriptor methodDescriptor = validator.getConstraintsForClass( CustomerService.class ) .getConstraintsForMethod( "createCustomer", Customer.class ); //then assertEquals( bootstrapConfiguration.getParameterNameProviderClassName(), CustomParameterNameProvider.class.getName() ); assertEquals( methodDescriptor.getParameterDescriptors().get( 0 ).getName(), "param0" ); } } ); } @Test @TestForIssue(jiraKey = "HV-1463") public void testScriptEvaluatorFactoryConfiguration() { validationXmlTestHelper.runWithCustomValidationXml( "script-evaluator-factory-validation.xml", () -> { //given BootstrapConfiguration bootstrapConfiguration = ValidatorUtil.getConfiguration() .getBootstrapConfiguration(); //then assertEquals( bootstrapConfiguration.getProperties().get( HibernateValidatorConfiguration.SCRIPT_EVALUATOR_FACTORY_CLASSNAME ), CustomScriptEvaluatorFactory.class.getName() ); } ); } @Test @TestForIssue(jiraKey = "HV-1493") public void testTemporalValidationToleranceConfiguration() { validationXmlTestHelper.runWithCustomValidationXml( "temporal-validation-tolerance-duration-validation.xml", () -> { //given BootstrapConfiguration bootstrapConfiguration = ValidatorUtil.getConfiguration() .getBootstrapConfiguration(); //then assertEquals( bootstrapConfiguration.getProperties().get( HibernateValidatorConfiguration.TEMPORAL_VALIDATION_TOLERANCE ), "123456" ); } ); } @Test @TestForIssue(jiraKey = "HV-707") public void shouldReturnDefaultExecutableTypesForValidationXmlWithoutTypesGiven() { validationXmlTestHelper.runWithCustomValidationXml( "bv-1.0-validation.xml", new Runnable() { @Override public void run() { //given BootstrapConfiguration bootstrapConfiguration = ValidatorUtil.getConfiguration() .getBootstrapConfiguration(); //when //then assertEquals( bootstrapConfiguration.getDefaultValidatedExecutableTypes(), asSet( ExecutableType.CONSTRUCTORS, ExecutableType.NON_GETTER_METHODS ) ); } } ); } @Test @TestForIssue(jiraKey = "HV-707") public void shouldReturnDefaultExecutableTypesIfNoValidationXmlIsGiven() { //given BootstrapConfiguration bootstrapConfiguration = ValidatorUtil.getConfiguration() .getBootstrapConfiguration(); //when //then assertEquals( bootstrapConfiguration.getDefaultValidatedExecutableTypes(), asSet( ExecutableType.CONSTRUCTORS, ExecutableType.NON_GETTER_METHODS ) ); } @Test public void testLoadingOfBv10ValidationXml() { validationXmlTestHelper.runWithCustomValidationXml( "bv-1.0-validation.xml", new Runnable() { @Override public void run() { //given BootstrapConfiguration bootstrapConfiguration = ValidatorUtil.getConfiguration() .getBootstrapConfiguration(); //when //then assertEquals( bootstrapConfiguration.getProperties().get( "com.acme.validation.safetyChecking" ), "failOnError" ); } } ); } @Test( expectedExceptions = ValidationException.class, expectedExceptionsMessageRegExp = "HV000122: Unsupported schema version for META-INF/validation.xml: 1\\.2\\." ) public void shouldFailToLoadValidationXmlWithUnsupportedVersion() { validationXmlTestHelper.runWithCustomValidationXml( "unsupported-validation.xml", new Runnable() { @Override public void run() { ValidatorUtil.getConfiguration().getBootstrapConfiguration(); } } ); } @Test( expectedExceptions = ValidationException.class, expectedExceptionsMessageRegExp = "HV000100: Unable to parse META-INF/validation.xml." ) public void shouldFailToLoad10ValidationXmlWithParameterNameProvider() { validationXmlTestHelper.runWithCustomValidationXml( "invalid-bv-1.0-validation.xml", new Runnable() { @Override public void run() { ValidatorUtil.getConfiguration().getBootstrapConfiguration(); } } ); } @Test @TestForIssue(jiraKey = "HV-836") public void testCascadedValidation() { final Configuration<?> configuration = ValidatorUtil.getConfiguration(); configuration.addMapping( XmlMappingTest.class.getResourceAsStream( "cascaded-validation-mapping.xml" ) ); final ValidatorFactory validatorFactory = configuration.buildValidatorFactory(); final Validator validator = validatorFactory.getValidator(); System system = new System(); system.addPart( new Part() ); Set<ConstraintViolation<System>> violations = validator.validate( system ); assertThat( violations ).containsOnlyViolations( violationOf( NotNull.class ) ); } @Test @TestForIssue(jiraKey = "HV-1534") public void test_constraint_is_applied_to_inherited_getter() { final Configuration<?> configuration = ValidatorUtil.getConfiguration(); configuration.addMapping( XmlMappingTest.class.getResourceAsStream( "hv-1534-mapping.xml" ) ); final ValidatorFactory validatorFactory = configuration.buildValidatorFactory(); final Validator validator = validatorFactory.getValidator(); Parent parent = new Parent( null ); Set<ConstraintViolation<Parent>> parentViolations = validator.validate( parent ); assertNoViolations( parentViolations ); Child child = new Child( null ); Set<ConstraintViolation<Child>> childViolations = validator.validate( child ); assertThat( childViolations ).containsOnlyViolations( violationOf( NotNull.class ).withProperty( "parentAttribute" ) ); } @Test @TestForIssue(jiraKey = "HV-1534") public void test_constraint_is_applied_to_type_argument_of_inherited_getter() { final Configuration<?> configuration = ValidatorUtil.getConfiguration(); configuration.addMapping( XmlMappingTest.class.getResourceAsStream( "hv-1534-mapping.xml" ) ); final ValidatorFactory validatorFactory = configuration.buildValidatorFactory(); final Validator validator = validatorFactory.getValidator(); Parent parent = new Parent( "someValue" ); parent.addToListAttribute( null ); Set<ConstraintViolation<Parent>> parentViolations = validator.validate( parent ); assertNoViolations( parentViolations ); Child child = new Child( "someValue" ); child.addToListAttribute( null ); Set<ConstraintViolation<Child>> childViolations = validator.validate( child ); assertThat( childViolations ).containsOnlyViolations( violationOf( NotNull.class ) .withPropertyPath( pathWith() .property( "parentListAttribute" ) .containerElement( "<list element>", true, null, 0, List.class, 0 ) ) ); } }
package com.neusoft.entity.vo; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import java.io.Serializable; import java.time.LocalDateTime; @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class ServiceUserAllotVo implements Serializable { private Integer id; /** * 服务类型 服务类型 */ private Integer serviceType; /** * 服务类型名称 服务类型名称 */ private String serviceTypeTitle; /** * 概要 概要 */ private String outline; /** * 客户名称 客户名称 */ private String customerName; /** * 客户编号 客户编号 */ private Integer customerId; /** * 状态(0:新创建,1:已分配,2:已处理) */ private Integer status; /** * 状态名称(0:新创建,1:已分配,2:已处理) */ private String statusTitle; /** * 服务请求 服务请求 */ private String serviceReq; /** * 创建人编号 创建人编号 */ private Integer creationId; /** * 创建人姓名 创建人姓名 */ private String creationName; /** * 创建时间 创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime creationTime; /** * 服务编号 服务编号 */ private Integer serviceId; /** * 分配用户编号 分配用户编号 */ private Integer userId; /** * 分配用户名字 分配用户名字 */ private String userIdName; /** * 创建人编号 创建人编号 */ /** * 分配时间 分配时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime allotTime; /** * 服务处理 服务处理 */ private String serviceHandle; /** * 处理人 处理人 */ private String handleName; /** * 处理时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime handleTime; /** * 处理结果 处理结果 */ private String handleResult; /** * 满意度 满意度 */ private Integer satisfaction; }
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 付费外卡模版配置 * * @author auto create * @since 1.0, 2021-08-18 17:24:35 */ public class PaidOuterCardTemplateConfDTO extends AlipayObject { private static final long serialVersionUID = 4331244366492986245L; /** * 连续售卖配置 */ @ApiField("cycle_selling_conf") private PaidOuterCardCycleSellConfDTO cycleSellingConf; /** * 生命周期管理地址 */ @ApiField("manage_url_conf") private PaidOuterCardManageUrlConfDTO manageUrlConf; /** * 售卖基础配置 */ @ApiField("open_selling_conf") private PaidOuterCardSellingConfDTO openSellingConf; public PaidOuterCardCycleSellConfDTO getCycleSellingConf() { return this.cycleSellingConf; } public void setCycleSellingConf(PaidOuterCardCycleSellConfDTO cycleSellingConf) { this.cycleSellingConf = cycleSellingConf; } public PaidOuterCardManageUrlConfDTO getManageUrlConf() { return this.manageUrlConf; } public void setManageUrlConf(PaidOuterCardManageUrlConfDTO manageUrlConf) { this.manageUrlConf = manageUrlConf; } public PaidOuterCardSellingConfDTO getOpenSellingConf() { return this.openSellingConf; } public void setOpenSellingConf(PaidOuterCardSellingConfDTO openSellingConf) { this.openSellingConf = openSellingConf; } }
package org.culpan.bris.sprites; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Rectangle; public interface NonPlayerObject { void move(); Rectangle getBoundingRectangle(); boolean isDestroyed(); void destroy(); void draw(Batch batch); }
/* * Copyright 2012-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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.autoconfigure; import java.util.Collection; import java.util.List; import java.util.Map; import javax.servlet.Servlet; import javax.sql.DataSource; import org.apache.catalina.startup.Tomcat; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.actuate.cache.CacheStatisticsProvider; import org.springframework.boot.actuate.endpoint.CachePublicMetrics; import org.springframework.boot.actuate.endpoint.DataSourcePublicMetrics; import org.springframework.boot.actuate.endpoint.MetricReaderPublicMetrics; import org.springframework.boot.actuate.endpoint.PublicMetrics; import org.springframework.boot.actuate.endpoint.RichGaugeReaderPublicMetrics; import org.springframework.boot.actuate.endpoint.SystemPublicMetrics; import org.springframework.boot.actuate.endpoint.TomcatPublicMetrics; import org.springframework.boot.actuate.metrics.integration.SpringIntegrationMetricReader; import org.springframework.boot.actuate.metrics.reader.CompositeMetricReader; import org.springframework.boot.actuate.metrics.reader.MetricReader; import org.springframework.boot.actuate.metrics.rich.RichGaugeReader; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnJava; import org.springframework.boot.autoconfigure.condition.ConditionalOnJava.JavaVersion; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.SearchStrategy; import org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvider; import org.springframework.cache.CacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.config.EnableIntegrationManagement; import org.springframework.integration.support.management.IntegrationManagementConfigurer; import org.springframework.lang.UsesJava7; /** * {@link EnableAutoConfiguration Auto-configuration} for {@link PublicMetrics}. * * @author Stephane Nicoll * @author Phillip Webb * @author Johannes Edmeier * @author Artem Bilan * @since 1.2.0 */ @Configuration @AutoConfigureBefore(EndpointAutoConfiguration.class) @AutoConfigureAfter({ DataSourceAutoConfiguration.class, CacheAutoConfiguration.class, MetricRepositoryAutoConfiguration.class, CacheStatisticsAutoConfiguration.class, IntegrationAutoConfiguration.class }) public class PublicMetricsAutoConfiguration { private final List<MetricReader> metricReaders; public PublicMetricsAutoConfiguration( @ExportMetricReader ObjectProvider<List<MetricReader>> metricReaders) { this.metricReaders = metricReaders.getIfAvailable(); } @Bean public SystemPublicMetrics systemPublicMetrics() { return new SystemPublicMetrics(); } @Bean public MetricReaderPublicMetrics metricReaderPublicMetrics() { MetricReader[] readers = (this.metricReaders != null) ? this.metricReaders.toArray(new MetricReader[this.metricReaders.size()]) : new MetricReader[0]; return new MetricReaderPublicMetrics(new CompositeMetricReader(readers)); } @Bean @ConditionalOnBean(RichGaugeReader.class) public RichGaugeReaderPublicMetrics richGaugePublicMetrics( RichGaugeReader richGaugeReader) { return new RichGaugeReaderPublicMetrics(richGaugeReader); } @Configuration @ConditionalOnClass(DataSource.class) @ConditionalOnBean(DataSource.class) static class DataSourceMetricsConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(DataSourcePoolMetadataProvider.class) public DataSourcePublicMetrics dataSourcePublicMetrics() { return new DataSourcePublicMetrics(); } } @Configuration @ConditionalOnClass({ Servlet.class, Tomcat.class }) @ConditionalOnWebApplication static class TomcatMetricsConfiguration { @Bean @ConditionalOnMissingBean public TomcatPublicMetrics tomcatPublicMetrics() { return new TomcatPublicMetrics(); } } @Configuration @ConditionalOnClass(CacheManager.class) @ConditionalOnBean(CacheManager.class) static class CacheStatisticsConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(CacheStatisticsProvider.class) public CachePublicMetrics cachePublicMetrics( Map<String, CacheManager> cacheManagers, Collection<CacheStatisticsProvider<?>> statisticsProviders) { return new CachePublicMetrics(cacheManagers, statisticsProviders); } } @Configuration @ConditionalOnClass(EnableIntegrationManagement.class) @ConditionalOnJava(JavaVersion.SEVEN) @UsesJava7 static class IntegrationMetricsConfiguration { @Bean(name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME) @ConditionalOnMissingBean(value = IntegrationManagementConfigurer.class, name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME, search = SearchStrategy.CURRENT) public IntegrationManagementConfigurer managementConfigurer() { IntegrationManagementConfigurer configurer = new IntegrationManagementConfigurer(); configurer.setDefaultCountsEnabled(true); configurer.setDefaultStatsEnabled(true); return configurer; } @Bean @ConditionalOnMissingBean(name = "springIntegrationPublicMetrics") public MetricReaderPublicMetrics springIntegrationPublicMetrics( IntegrationManagementConfigurer managementConfigurer) { return new MetricReaderPublicMetrics( new SpringIntegrationMetricReader(managementConfigurer)); } } }
package com.ppdai.das.server; import java.sql.JDBCType; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.common.collect.Lists; import com.ppdai.das.client.Hints; import com.ppdai.das.client.SqlBuilder; import com.ppdai.das.client.TableDefinition; import com.ppdai.das.client.delegate.local.ClientDasDelegate; import com.ppdai.das.client.delegate.remote.PPDaiDasProxyParser; import com.ppdai.das.core.client.DalParser; import com.ppdai.das.service.ColumnMeta; import com.ppdai.das.service.Entity; import com.ppdai.das.service.EntityMeta; public class ServerDasDelegate extends ClientDasDelegate { private String appId; private String logicDbName; public ServerDasDelegate(String appId, String logicDbName, String customerClientVersion) { super(appId, logicDbName, customerClientVersion); this.appId = appId; this.logicDbName = logicDbName; } protected <T> DalParser<T> getParser(T entity) throws SQLException { return getParser(((Entity)entity).getEntityMeta()); } protected <T> DalParser<T> getParser(EntityMeta meta) throws SQLException { return (DalParser<T>)new PPDaiDasProxyParser(getAppId(), getLogicDbName(), meta); } @Override protected <T> SqlBuilder countBySampleSqlBuilder(TableDefinition table, T sample) throws SQLException { SqlBuilder sqlBuilder = super.countBySampleSqlBuilder(table, sample); sqlBuilder.setEntityMeta(((Entity)sample).getEntityMeta()); return sqlBuilder; } @Override protected <T> SqlBuilder queryByPkSqlBuilder(TableDefinition table, T id, Hints hints) throws SQLException { SqlBuilder sb = super.queryByPkSqlBuilder(table, id, hints); sb.setEntityMeta(((Entity)id).getEntityMeta()); return sb; } @Override protected <T> SqlBuilder queryBySampleSqlBuilder(TableDefinition table, T sample) throws SQLException { SqlBuilder sb = super.queryBySampleSqlBuilder(table, sample); sb.setEntityMeta(((Entity)sample).getEntityMeta()); return sb; } @Override public <T> List<T> query(SqlBuilder builder) throws SQLException { EntityMeta meta = builder.getEntityMeta(); List list = super.query(builder); EntityMeta mapMeta = createMapEntityMeta(list, meta); builder.setEntityMeta(mapMeta); return list; } private EntityMeta createMapEntityMeta(List<Map> list, EntityMeta entityMeta) { EntityMeta meta = new EntityMeta(); if(entityMeta == null || !entityMeta.isMapType()){ return null; } if(!list.isEmpty()) { Map first = list.get(0); List<String> colNames = Lists.newArrayList(first.keySet()); meta.setColumnNames(colNames); Map<String,ColumnMeta> metaMap = new HashMap<>(); for(String name : colNames){ metaMap.put(name, new ColumnMeta().setType(JDBCType.VARCHAR.getName())); } meta.setMetaMap(metaMap); } return meta; } }
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.google.android.gms.nearby; public final class R { public static final class attr { public static final int adSize = 0x7f010027; public static final int adSizes = 0x7f010028; public static final int adUnitId = 0x7f010029; public static final int ambientEnabled = 0x7f010051; public static final int appTheme = 0x7f0100ef; public static final int buttonSize = 0x7f010067; public static final int buyButtonAppearance = 0x7f0100f6; public static final int buyButtonHeight = 0x7f0100f3; public static final int buyButtonText = 0x7f0100f5; public static final int buyButtonWidth = 0x7f0100f4; public static final int cameraBearing = 0x7f010042; public static final int cameraTargetLat = 0x7f010043; public static final int cameraTargetLng = 0x7f010044; public static final int cameraTilt = 0x7f010045; public static final int cameraZoom = 0x7f010046; public static final int circleCrop = 0x7f010040; public static final int colorScheme = 0x7f010068; public static final int environment = 0x7f0100f0; public static final int fragmentMode = 0x7f0100f2; public static final int fragmentStyle = 0x7f0100f1; public static final int imageAspectRatio = 0x7f01003f; public static final int imageAspectRatioAdjust = 0x7f01003e; public static final int liteMode = 0x7f010047; public static final int mapType = 0x7f010041; public static final int maskedWalletDetailsBackground = 0x7f0100f9; public static final int maskedWalletDetailsButtonBackground = 0x7f0100fb; public static final int maskedWalletDetailsButtonTextAppearance = 0x7f0100fa; public static final int maskedWalletDetailsHeaderTextAppearance = 0x7f0100f8; public static final int maskedWalletDetailsLogoImageType = 0x7f0100fd; public static final int maskedWalletDetailsLogoTextColor = 0x7f0100fc; public static final int maskedWalletDetailsTextAppearance = 0x7f0100f7; public static final int scopeUris = 0x7f010069; public static final int uiCompass = 0x7f010048; public static final int uiMapToolbar = 0x7f010050; public static final int uiRotateGestures = 0x7f010049; public static final int uiScrollGestures = 0x7f01004a; public static final int uiTiltGestures = 0x7f01004b; public static final int uiZoomControls = 0x7f01004c; public static final int uiZoomGestures = 0x7f01004d; public static final int useViewLifecycle = 0x7f01004e; public static final int windowTransitionStyle = 0x7f010032; public static final int zOrderOnTop = 0x7f01004f; } public static final class color { public static final int common_action_bar_splitter = 0x7f0b0015; public static final int common_google_signin_btn_text_dark = 0x7f0b0079; public static final int common_google_signin_btn_text_dark_default = 0x7f0b0016; public static final int common_google_signin_btn_text_dark_disabled = 0x7f0b0017; public static final int common_google_signin_btn_text_dark_focused = 0x7f0b0018; public static final int common_google_signin_btn_text_dark_pressed = 0x7f0b0019; public static final int common_google_signin_btn_text_light = 0x7f0b007a; public static final int common_google_signin_btn_text_light_default = 0x7f0b001a; public static final int common_google_signin_btn_text_light_disabled = 0x7f0b001b; public static final int common_google_signin_btn_text_light_focused = 0x7f0b001c; public static final int common_google_signin_btn_text_light_pressed = 0x7f0b001d; public static final int common_plus_signin_btn_text_dark = 0x7f0b007b; public static final int common_plus_signin_btn_text_dark_default = 0x7f0b001e; public static final int common_plus_signin_btn_text_dark_disabled = 0x7f0b001f; public static final int common_plus_signin_btn_text_dark_focused = 0x7f0b0020; public static final int common_plus_signin_btn_text_dark_pressed = 0x7f0b0021; public static final int common_plus_signin_btn_text_light = 0x7f0b007c; public static final int common_plus_signin_btn_text_light_default = 0x7f0b0022; public static final int common_plus_signin_btn_text_light_disabled = 0x7f0b0023; public static final int common_plus_signin_btn_text_light_focused = 0x7f0b0024; public static final int common_plus_signin_btn_text_light_pressed = 0x7f0b0025; public static final int place_autocomplete_prediction_primary_text = 0x7f0b0044; public static final int place_autocomplete_prediction_primary_text_highlight = 0x7f0b0045; public static final int place_autocomplete_prediction_secondary_text = 0x7f0b0046; public static final int place_autocomplete_search_hint = 0x7f0b0047; public static final int place_autocomplete_search_text = 0x7f0b0048; public static final int place_autocomplete_separator = 0x7f0b0049; public static final int wallet_bright_foreground_disabled_holo_light = 0x7f0b005f; public static final int wallet_bright_foreground_holo_dark = 0x7f0b0060; public static final int wallet_bright_foreground_holo_light = 0x7f0b0061; public static final int wallet_dim_foreground_disabled_holo_dark = 0x7f0b0062; public static final int wallet_dim_foreground_holo_dark = 0x7f0b0063; public static final int wallet_dim_foreground_inverse_disabled_holo_dark = 0x7f0b0064; public static final int wallet_dim_foreground_inverse_holo_dark = 0x7f0b0065; public static final int wallet_highlighted_text_holo_dark = 0x7f0b0066; public static final int wallet_highlighted_text_holo_light = 0x7f0b0067; public static final int wallet_hint_foreground_holo_dark = 0x7f0b0068; public static final int wallet_hint_foreground_holo_light = 0x7f0b0069; public static final int wallet_holo_blue_light = 0x7f0b006a; public static final int wallet_link_text_light = 0x7f0b006b; public static final int wallet_primary_text_holo_light = 0x7f0b007f; public static final int wallet_secondary_text_holo_dark = 0x7f0b0080; } public static final class dimen { public static final int place_autocomplete_button_padding = 0x7f070049; public static final int place_autocomplete_powered_by_google_height = 0x7f07004a; public static final int place_autocomplete_powered_by_google_start = 0x7f07004b; public static final int place_autocomplete_prediction_height = 0x7f07004c; public static final int place_autocomplete_prediction_horizontal_margin = 0x7f07004d; public static final int place_autocomplete_prediction_primary_text = 0x7f07004e; public static final int place_autocomplete_prediction_secondary_text = 0x7f07004f; public static final int place_autocomplete_progress_horizontal_margin = 0x7f070050; public static final int place_autocomplete_progress_size = 0x7f070051; public static final int place_autocomplete_separator_start = 0x7f070052; } public static final class drawable { public static final int cast_ic_notification_0 = 0x7f020042; public static final int cast_ic_notification_1 = 0x7f020043; public static final int cast_ic_notification_2 = 0x7f020044; public static final int cast_ic_notification_connecting = 0x7f020045; public static final int cast_ic_notification_on = 0x7f020046; public static final int common_full_open_on_phone = 0x7f02004b; public static final int common_google_signin_btn_icon_dark = 0x7f02004c; public static final int common_google_signin_btn_icon_dark_disabled = 0x7f02004d; public static final int common_google_signin_btn_icon_dark_focused = 0x7f02004e; public static final int common_google_signin_btn_icon_dark_normal = 0x7f02004f; public static final int common_google_signin_btn_icon_dark_pressed = 0x7f020050; public static final int common_google_signin_btn_icon_light = 0x7f020051; public static final int common_google_signin_btn_icon_light_disabled = 0x7f020052; public static final int common_google_signin_btn_icon_light_focused = 0x7f020053; public static final int common_google_signin_btn_icon_light_normal = 0x7f020054; public static final int common_google_signin_btn_icon_light_pressed = 0x7f020055; public static final int common_google_signin_btn_text_dark = 0x7f020056; public static final int common_google_signin_btn_text_dark_disabled = 0x7f020057; public static final int common_google_signin_btn_text_dark_focused = 0x7f020058; public static final int common_google_signin_btn_text_dark_normal = 0x7f020059; public static final int common_google_signin_btn_text_dark_pressed = 0x7f02005a; public static final int common_google_signin_btn_text_light = 0x7f02005b; public static final int common_google_signin_btn_text_light_disabled = 0x7f02005c; public static final int common_google_signin_btn_text_light_focused = 0x7f02005d; public static final int common_google_signin_btn_text_light_normal = 0x7f02005e; public static final int common_google_signin_btn_text_light_pressed = 0x7f02005f; public static final int common_ic_googleplayservices = 0x7f020060; public static final int common_plus_signin_btn_icon_dark = 0x7f020061; public static final int common_plus_signin_btn_icon_dark_disabled = 0x7f020062; public static final int common_plus_signin_btn_icon_dark_focused = 0x7f020063; public static final int common_plus_signin_btn_icon_dark_normal = 0x7f020064; public static final int common_plus_signin_btn_icon_dark_pressed = 0x7f020065; public static final int common_plus_signin_btn_icon_light = 0x7f020066; public static final int common_plus_signin_btn_icon_light_disabled = 0x7f020067; public static final int common_plus_signin_btn_icon_light_focused = 0x7f020068; public static final int common_plus_signin_btn_icon_light_normal = 0x7f020069; public static final int common_plus_signin_btn_icon_light_pressed = 0x7f02006a; public static final int common_plus_signin_btn_text_dark = 0x7f02006b; public static final int common_plus_signin_btn_text_dark_disabled = 0x7f02006c; public static final int common_plus_signin_btn_text_dark_focused = 0x7f02006d; public static final int common_plus_signin_btn_text_dark_normal = 0x7f02006e; public static final int common_plus_signin_btn_text_dark_pressed = 0x7f02006f; public static final int common_plus_signin_btn_text_light = 0x7f020070; public static final int common_plus_signin_btn_text_light_disabled = 0x7f020071; public static final int common_plus_signin_btn_text_light_focused = 0x7f020072; public static final int common_plus_signin_btn_text_light_normal = 0x7f020073; public static final int common_plus_signin_btn_text_light_pressed = 0x7f020074; public static final int ic_plusone_medium_off_client = 0x7f020090; public static final int ic_plusone_small_off_client = 0x7f020091; public static final int ic_plusone_standard_off_client = 0x7f020092; public static final int ic_plusone_tall_off_client = 0x7f020093; public static final int places_ic_clear = 0x7f0200b1; public static final int places_ic_search = 0x7f0200b2; public static final int powered_by_google_dark = 0x7f0200b3; public static final int powered_by_google_light = 0x7f0200b4; } public static final class id { public static final int adjust_height = 0x7f0c001d; public static final int adjust_width = 0x7f0c001e; public static final int android_pay = 0x7f0c0047; public static final int android_pay_dark = 0x7f0c003e; public static final int android_pay_light = 0x7f0c003f; public static final int android_pay_light_with_border = 0x7f0c0040; public static final int auto = 0x7f0c002a; public static final int book_now = 0x7f0c0037; public static final int buyButton = 0x7f0c0034; public static final int buy_now = 0x7f0c0038; public static final int buy_with = 0x7f0c0039; public static final int buy_with_google = 0x7f0c003a; public static final int cast_notification_id = 0x7f0c0004; public static final int classic = 0x7f0c0041; public static final int dark = 0x7f0c002b; public static final int donate_with = 0x7f0c003b; public static final int donate_with_google = 0x7f0c003c; public static final int google_wallet_classic = 0x7f0c0042; public static final int google_wallet_grayscale = 0x7f0c0043; public static final int google_wallet_monochrome = 0x7f0c0044; public static final int grayscale = 0x7f0c0045; public static final int holo_dark = 0x7f0c002e; public static final int holo_light = 0x7f0c002f; public static final int hybrid = 0x7f0c001f; public static final int icon_only = 0x7f0c0027; public static final int light = 0x7f0c002c; public static final int logo_only = 0x7f0c003d; public static final int match_parent = 0x7f0c0036; public static final int monochrome = 0x7f0c0046; public static final int none = 0x7f0c000f; public static final int normal = 0x7f0c000b; public static final int place_autocomplete_clear_button = 0x7f0c00fb; public static final int place_autocomplete_powered_by_google = 0x7f0c00fd; public static final int place_autocomplete_prediction_primary_text = 0x7f0c00ff; public static final int place_autocomplete_prediction_secondary_text = 0x7f0c0100; public static final int place_autocomplete_progress = 0x7f0c00fe; public static final int place_autocomplete_search_button = 0x7f0c00f9; public static final int place_autocomplete_search_input = 0x7f0c00fa; public static final int place_autocomplete_separator = 0x7f0c00fc; public static final int production = 0x7f0c0030; public static final int sandbox = 0x7f0c0031; public static final int satellite = 0x7f0c0020; public static final int selectionDetails = 0x7f0c0035; public static final int slide = 0x7f0c0019; public static final int standard = 0x7f0c0028; public static final int strict_sandbox = 0x7f0c0032; public static final int terrain = 0x7f0c0021; public static final int test = 0x7f0c0033; public static final int wide = 0x7f0c0029; public static final int wrap_content = 0x7f0c002d; } public static final class integer { public static final int google_play_services_version = 0x7f0a0004; } public static final class layout { public static final int place_autocomplete_fragment = 0x7f030042; public static final int place_autocomplete_item_powered_by_google = 0x7f030043; public static final int place_autocomplete_item_prediction = 0x7f030044; public static final int place_autocomplete_progress = 0x7f030045; } public static final class raw { public static final int gtm_analytics = 0x7f050000; } public static final class string { public static final int accept = 0x7f06003d; public static final int auth_google_play_services_client_facebook_display_name = 0x7f06003f; public static final int auth_google_play_services_client_google_display_name = 0x7f060040; public static final int cast_notification_connected_message = 0x7f060041; public static final int cast_notification_connecting_message = 0x7f060042; public static final int cast_notification_disconnect = 0x7f060043; public static final int common_google_play_services_api_unavailable_text = 0x7f060011; public static final int common_google_play_services_enable_button = 0x7f060012; public static final int common_google_play_services_enable_text = 0x7f060013; public static final int common_google_play_services_enable_title = 0x7f060014; public static final int common_google_play_services_install_button = 0x7f060015; public static final int common_google_play_services_install_text_phone = 0x7f060016; public static final int common_google_play_services_install_text_tablet = 0x7f060017; public static final int common_google_play_services_install_title = 0x7f060018; public static final int common_google_play_services_invalid_account_text = 0x7f060019; public static final int common_google_play_services_invalid_account_title = 0x7f06001a; public static final int common_google_play_services_network_error_text = 0x7f06001b; public static final int common_google_play_services_network_error_title = 0x7f06001c; public static final int common_google_play_services_notification_ticker = 0x7f06001d; public static final int common_google_play_services_restricted_profile_text = 0x7f06001e; public static final int common_google_play_services_restricted_profile_title = 0x7f06001f; public static final int common_google_play_services_sign_in_failed_text = 0x7f060020; public static final int common_google_play_services_sign_in_failed_title = 0x7f060021; public static final int common_google_play_services_unknown_issue = 0x7f060022; public static final int common_google_play_services_unsupported_text = 0x7f060023; public static final int common_google_play_services_unsupported_title = 0x7f060024; public static final int common_google_play_services_update_button = 0x7f060025; public static final int common_google_play_services_update_text = 0x7f060026; public static final int common_google_play_services_update_title = 0x7f060027; public static final int common_google_play_services_updating_text = 0x7f060028; public static final int common_google_play_services_updating_title = 0x7f060029; public static final int common_google_play_services_wear_update_text = 0x7f06002a; public static final int common_open_on_phone = 0x7f06002b; public static final int common_signin_button_text = 0x7f06002c; public static final int common_signin_button_text_long = 0x7f06002d; public static final int create_calendar_message = 0x7f060044; public static final int create_calendar_title = 0x7f060045; public static final int decline = 0x7f060046; public static final int place_autocomplete_clear_button = 0x7f060039; public static final int place_autocomplete_search_hint = 0x7f06003a; public static final int store_picture_message = 0x7f06004a; public static final int store_picture_title = 0x7f06004b; public static final int wallet_buy_button_place_holder = 0x7f06003c; } public static final class style { public static final int Theme_AppInvite_Preview = 0x7f0800e8; public static final int Theme_AppInvite_Preview_Base = 0x7f080014; public static final int Theme_IAPTheme = 0x7f0800e9; public static final int WalletFragmentDefaultButtonTextAppearance = 0x7f0800f1; public static final int WalletFragmentDefaultDetailsHeaderTextAppearance = 0x7f0800f2; public static final int WalletFragmentDefaultDetailsTextAppearance = 0x7f0800f3; public static final int WalletFragmentDefaultStyle = 0x7f0800f4; } public static final class styleable { public static final int[] AdsAttrs = { 0x7f010027, 0x7f010028, 0x7f010029 }; public static final int AdsAttrs_adSize = 0; public static final int AdsAttrs_adSizes = 1; public static final int AdsAttrs_adUnitId = 2; public static final int[] CustomWalletTheme = { 0x7f010032 }; public static final int CustomWalletTheme_windowTransitionStyle = 0; public static final int[] LoadingImageView = { 0x7f01003e, 0x7f01003f, 0x7f010040 }; public static final int LoadingImageView_circleCrop = 2; public static final int LoadingImageView_imageAspectRatio = 1; public static final int LoadingImageView_imageAspectRatioAdjust = 0; public static final int[] MapAttrs = { 0x7f010041, 0x7f010042, 0x7f010043, 0x7f010044, 0x7f010045, 0x7f010046, 0x7f010047, 0x7f010048, 0x7f010049, 0x7f01004a, 0x7f01004b, 0x7f01004c, 0x7f01004d, 0x7f01004e, 0x7f01004f, 0x7f010050, 0x7f010051 }; public static final int MapAttrs_ambientEnabled = 16; public static final int MapAttrs_cameraBearing = 1; public static final int MapAttrs_cameraTargetLat = 2; public static final int MapAttrs_cameraTargetLng = 3; public static final int MapAttrs_cameraTilt = 4; public static final int MapAttrs_cameraZoom = 5; public static final int MapAttrs_liteMode = 6; public static final int MapAttrs_mapType = 0; public static final int MapAttrs_uiCompass = 7; public static final int MapAttrs_uiMapToolbar = 15; public static final int MapAttrs_uiRotateGestures = 8; public static final int MapAttrs_uiScrollGestures = 9; public static final int MapAttrs_uiTiltGestures = 10; public static final int MapAttrs_uiZoomControls = 11; public static final int MapAttrs_uiZoomGestures = 12; public static final int MapAttrs_useViewLifecycle = 13; public static final int MapAttrs_zOrderOnTop = 14; public static final int[] SignInButton = { 0x7f010067, 0x7f010068, 0x7f010069 }; public static final int SignInButton_buttonSize = 0; public static final int SignInButton_colorScheme = 1; public static final int SignInButton_scopeUris = 2; public static final int[] WalletFragmentOptions = { 0x7f0100ef, 0x7f0100f0, 0x7f0100f1, 0x7f0100f2 }; public static final int WalletFragmentOptions_appTheme = 0; public static final int WalletFragmentOptions_environment = 1; public static final int WalletFragmentOptions_fragmentMode = 3; public static final int WalletFragmentOptions_fragmentStyle = 2; public static final int[] WalletFragmentStyle = { 0x7f0100f3, 0x7f0100f4, 0x7f0100f5, 0x7f0100f6, 0x7f0100f7, 0x7f0100f8, 0x7f0100f9, 0x7f0100fa, 0x7f0100fb, 0x7f0100fc, 0x7f0100fd }; public static final int WalletFragmentStyle_buyButtonAppearance = 3; public static final int WalletFragmentStyle_buyButtonHeight = 0; public static final int WalletFragmentStyle_buyButtonText = 2; public static final int WalletFragmentStyle_buyButtonWidth = 1; public static final int WalletFragmentStyle_maskedWalletDetailsBackground = 6; public static final int WalletFragmentStyle_maskedWalletDetailsButtonBackground = 8; public static final int WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance = 7; public static final int WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance = 5; public static final int WalletFragmentStyle_maskedWalletDetailsLogoImageType = 10; public static final int WalletFragmentStyle_maskedWalletDetailsLogoTextColor = 9; public static final int WalletFragmentStyle_maskedWalletDetailsTextAppearance = 4; } }
package com.kymjs.base.backactivity; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
package com.packtpub.mmj.mcrsrvc.domain.model; /** * @param <T> * @author Sourabh Sharma */ public abstract class BaseEntity<T> extends Entity<T> { private final boolean isModified; /** * @param id * @param name */ public BaseEntity(T id, String name) { super.id = id; super.name = name; isModified = false; } /** * * @return */ public boolean isIsModified() { return isModified; } }
package com.xyzniu.fpsgame.programs; import android.content.Context; import com.xyzniu.fpsgame.R; import static android.opengl.GLES20.*; public class EndPointShaderProgram extends ShaderProgram { private final int uModelViewProjectionLocation; private final int uLightColorLocation; private final int aPositionLocation; protected EndPointShaderProgram(Context context) { super(context, R.raw.endpoint_vertex_shader, R.raw.endpoint_fragment_shader); uModelViewProjectionLocation = glGetUniformLocation(program, U_MODEL_VIEW_PROJECTION); uLightColorLocation = glGetUniformLocation(program, U_LIGHT_COLOR); aPositionLocation = glGetAttribLocation(program, A_POSITION); } public void setUniforms(float[] modelViewProjection, float[] color) { glUniformMatrix4fv(uModelViewProjectionLocation, 1, false, modelViewProjection, 0); glUniform3fv(uLightColorLocation, 1, color, 0); } public int getPositionLocation() { return aPositionLocation; } }
/* Copyright (c) 2018 Joey <majunjiev@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 org.ovirt.sdk.go; /** * This class represents the fully qualified name of a Go function and its package */ public class GoFuncName { private String packageName; private String simpleName; public String getPackageName() { return packageName; } public void setPackageName(String newPackageName) { packageName = newPackageName; } public String getSimpleName() { return simpleName; } public void setSimpleName(String newClassName) { simpleName = newClassName; } public void setClass(Class<?> newClass) { packageName = newClass.getPackage().getName(); simpleName = newClass.getSimpleName(); } @Override public String toString() { StringBuilder buffer = new StringBuilder(); if (packageName != null && packageName.length() > 0) { buffer.append(packageName); buffer.append("/"); } buffer.append(simpleName); return buffer.toString(); } }
package net.chakramod.mod.block; import net.chakramod.mod.ChakraMod; import net.chakramod.mod.block.custom.glowstoneCrystal.GlowstoneCrystalSpecial; import net.chakramod.mod.block.custom.stoneWorkBench.StoneWorkBench; import net.chakramod.mod.item.ModItemGroup; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.block.Block; import net.minecraft.block.Material; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; public class ModBlocks extends Block{ public static final Block HEART_ORE = registerBlock("heart_ore", new Block(FabricBlockSettings.of(Material.STONE).strength(4.0f).breakByTool(FabricToolTags.PICKAXES, 4).requiresTool())); public static final Block STONE_WORK_BENCH = registerBlock("stone_work_bench", new StoneWorkBench(FabricBlockSettings.of(Material.STONE).strength(4.0f).requiresTool())); public static final Block CHAKRA_STONE = registerBlock("chakra_stone", new Block(FabricBlockSettings.of(Material.STONE).strength(4.0f).breakByTool(FabricToolTags.PICKAXES, 4).requiresTool())); public static final Block CHAKRA_GRASS = registerBlock("chakra_grass", new Block(FabricBlockSettings.of(Material.STONE).strength(4.0f).breakByTool(FabricToolTags.PICKAXES, 4).requiresTool())); public static final Block CHAKRA_GRAVEL = registerBlock("chakra_gravel", new Block(FabricBlockSettings.of(Material.STONE).strength(4.0f).breakByTool(FabricToolTags.PICKAXES, 4).requiresTool())); public static final Block GLOWSTONE_CRYSTAL = registerBlock("glowstone_crystal", new GlowstoneCrystalSpecial(FabricBlockSettings.of(Material.STONE).strength(4.0f).requiresTool().luminance((state) -> 8))); public ModBlocks(Settings settings) { super(settings); } private static Block registerBlock(String name, Block block){ registerBlockItem(name, block); return Registry.register(Registry.BLOCK, new Identifier(ChakraMod.MOD_ID, name), block); } private static Item registerBlockItem(String name, Block block){ return Registry.register(Registry.ITEM, new Identifier(ChakraMod.MOD_ID, name), new BlockItem(block, new FabricItemSettings().group(ModItemGroup.MALACHIT))); } public static void registerModBlocks(){ System.out.println("tvoje máma"); } }
/* The MIT License Copyright (c) 2004-2015 Paul R. Holser, Jr. 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 joptsimple.internal; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a> */ public final class Classes { private static final Map<Class<?>, Class<?>> WRAPPERS = new HashMap<>( 13 ); static { WRAPPERS.put( boolean.class, Boolean.class ); WRAPPERS.put( byte.class, Byte.class ); WRAPPERS.put( char.class, Character.class ); WRAPPERS.put( double.class, Double.class ); WRAPPERS.put( float.class, Float.class ); WRAPPERS.put( int.class, Integer.class ); WRAPPERS.put( long.class, Long.class ); WRAPPERS.put( short.class, Short.class ); WRAPPERS.put( void.class, Void.class ); } private Classes() { throw new UnsupportedOperationException(); } /** * Gives the "short version" of the given class name. Somewhat naive to inner classes. * * @param className class name to chew on * @return the short name of the class */ public static String shortNameOf( String className ) { return className.substring( className.lastIndexOf( '.' ) + 1 ); } /** * Gives the primitive wrapper class for the given class. If the given class is not * {@linkplain Class#isPrimitive() primitive}, returns the class itself. * * @param <T> generic class type * @param clazz the class to check * @return primitive wrapper type if {@code clazz} is primitive, otherwise {@code clazz} */ @SuppressWarnings( "unchecked" ) public static <T> Class<T> wrapperOf( Class<T> clazz ) { return clazz.isPrimitive() ? (Class<T>) WRAPPERS.get( clazz ) : clazz; } }
package info.androidhive.barcodereader; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; public class PostSender extends AppCompatActivity { private String TAG = MainActivity.class.getSimpleName(); public String barcode_id = ""; public PostSender(){ } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_post_sender); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); Bundle extras = getIntent().getExtras(); barcode_id = extras.getString("barcode_id"); new GetContacts("post-api/search?model_size_id=" + barcode_id).execute(); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(PostSender.this,MainActivity.class)); Log.e("stop", "ss"); } }); } public void shvei(View v){ EditText modelSizeQty = findViewById(R.id.modelSizeQty); new GetContacts("post-api/move?sklad_id=987&qty="+String.valueOf(modelSizeQty.getText())+"&model_size_id=" + barcode_id).execute(); Log.e("qty" , String.valueOf(modelSizeQty.getText())); } private class GetContacts extends AsyncTask<Void, Void, Void> { private Integer qty = 0; public String url; public GetContacts(String url){ this.url = url; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(this.url); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { JSONArray jsonObj = new JSONArray(jsonStr); // looping through All Contacts for (int i = 0; i < jsonObj.length(); i++) { JSONObject c = jsonObj.getJSONObject(i); this.qty = Integer.valueOf(c.getString("qty")); } } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show(); } }); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if (this.qty > 0){ findViewById(R.id.modelSizeQty).setVisibility( View.VISIBLE ); //TextView text1 = findViewById(R.id.modelSizeTitle); //text1.setVisibility( View.VISIBLE ); //text1.setText(this.qty); findViewById(R.id.shvei1).setVisibility( View.VISIBLE ); } else { findViewById(R.id.modelSizeQty).setVisibility( View.INVISIBLE ); //TextView text1 = findViewById(R.id.modelSizeTitle); //text1.setVisibility( View.VISIBLE ); //text1.setText(this.qty); findViewById(R.id.shvei1).setVisibility( View.INVISIBLE ); } } } }
/** * Copyright © 2016-2021 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thingsboard.server.service.security.permission; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.service.security.model.SecurityUser; @Component(value="sysAdminPermissions") public class SysAdminPermissions extends AbstractPermissions { public SysAdminPermissions() { super(); put(Resource.ADMIN_SETTINGS, PermissionChecker.allowAllPermissionChecker); put(Resource.DASHBOARD, new PermissionChecker.GenericPermissionChecker(Operation.READ)); put(Resource.TENANT, PermissionChecker.allowAllPermissionChecker); put(Resource.RULE_CHAIN, systemEntityPermissionChecker); put(Resource.USER, userPermissionChecker); put(Resource.WIDGETS_BUNDLE, systemEntityPermissionChecker); put(Resource.WIDGET_TYPE, systemEntityPermissionChecker); put(Resource.OAUTH2_CONFIGURATION_INFO, PermissionChecker.allowAllPermissionChecker); put(Resource.OAUTH2_CONFIGURATION_TEMPLATE, PermissionChecker.allowAllPermissionChecker); put(Resource.TENANT_PROFILE, PermissionChecker.allowAllPermissionChecker); put(Resource.TB_RESOURCE, systemEntityPermissionChecker); } private static final PermissionChecker systemEntityPermissionChecker = new PermissionChecker() { @Override public boolean hasPermission(SecurityUser user, Operation operation, EntityId entityId, HasTenantId entity) { if (entity.getTenantId() != null && !entity.getTenantId().isNullUid()) { return false; } return true; } }; private static final PermissionChecker userPermissionChecker = new PermissionChecker<UserId, User>() { @Override public boolean hasPermission(SecurityUser user, Operation operation, UserId userId, User userEntity) { if (Authority.CUSTOMER_USER.equals(userEntity.getAuthority())) { return false; } return true; } }; }
package org.protege.editor.owl.model.selection; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.protege.editor.core.util.HandlerRegistration; import org.semanticweb.owlapi.model.OWLObject; import java.awt.*; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.util.Optional; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; /** * Matthew Horridge * Stanford Center for Biomedical Informatics Research * 8 Aug 16 */ @RunWith(MockitoJUnitRunner.class) public class SelectionPlaneImpl_TestCase { private SelectionPlaneImpl selectionPlane; @Mock private OWLSelectionModel selectionModel; @Mock private SelectionDriver selectionDriverA, selectionDriverB; @Mock private Component componentA, componentB; @Mock private OWLObject selectionA, selectionB; @Before public void setUp() { selectionPlane = new SelectionPlaneImpl(selectionModel); when(selectionDriverA.getSelection()).thenReturn(Optional.of(selectionA)); when(selectionDriverA.asComponent()).thenReturn(componentA); when(selectionDriverB.getSelection()).thenReturn(Optional.of(selectionB)); when(selectionDriverB.asComponent()).thenReturn(componentB); } /** * Tests that a hierarchy listener is added when a driver is registered. */ @Test public void shouldAddHierarchyListenerDuringRegistration() { selectionPlane.registerSelectionDriver(selectionDriverA); verify(componentA, times(1)).addHierarchyListener(any()); } /** * Tests that drivers that are registered multiple times are in fact only registered once. * * The expected result is that a hierarchy listener is only added to the component once. */ @Test public void shouldIgnoreRegistrationsOfAlreadyRegisterdDrivers() { selectionPlane.registerSelectionDriver(selectionDriverA); selectionPlane.registerSelectionDriver(selectionDriverA); verify(componentA, times(1)).addHierarchyListener(any()); } /** * Tests that hierarchy listeners are removed when a driver is unregistered */ @Test public void shouldRemoveHierarchyListenerOnRemoveRegistration() { HandlerRegistration registration = selectionPlane.registerSelectionDriver(selectionDriverA); ArgumentCaptor<HierarchyListener> listener = ArgumentCaptor.forClass(HierarchyListener.class); verify(componentA, times(1)).addHierarchyListener(listener.capture()); registration.removeHandler(); verify(componentA, times(1)).removeHierarchyListener(listener.getValue()); } @Test public void shouldTransmitSelectionIfShowing() { when(componentA.isShowing()).thenReturn(true); selectionPlane.registerSelectionDriver(selectionDriverA); triggerHierarchyChangeEvent(componentA); verify(selectionModel, times(1)).setSelectedObject(selectionA); } @Test public void shouldNotTransmitSelectionIfNotShowing() { when(componentA.isShowing()).thenReturn(false); selectionPlane.registerSelectionDriver(selectionDriverA); triggerHierarchyChangeEvent(componentA); verify(selectionModel, never()).setSelectedObject(any()); } /** * Tests the case where no prior selection has been made (i.e. {@code SelectionDriver#transmitSelection} has never * been called) and where multiple drivers are showing. * * The expected result is that the first registered driver gets its selection transmitted. Any other drivers * do not have their selection transmitted. */ @Test public void shouldTransmitSelectionOfFirstRegisteredDriverIfShowingButNoPriorSelection() { selectionPlane.registerSelectionDriver(selectionDriverA); selectionPlane.registerSelectionDriver(selectionDriverB); when(componentA.isShowing()).thenReturn(true); when(componentB.isShowing()).thenReturn(true); triggerHierarchyChangeEvent(componentA); verify(selectionModel, times(1)).setSelectedObject(selectionA); verify(selectionModel, never()).setSelectedObject(selectionB); } /** * Tests the case where a prior selection has been made (i.e. {@code SelectionDriver#transmitSelection} has * been called) and where multiple drivers are showing. * * The expected result is that the driver to transmit the selection gets its selection transmitted again. Any * other drivers do not have their selection transmitted. */ @Test public void shouldTransmitSelectionOfLastDriverIfShowingWithPriorSelection() { selectionPlane.registerSelectionDriver(selectionDriverA); selectionPlane.registerSelectionDriver(selectionDriverB); when(componentA.isShowing()).thenReturn(true); when(componentB.isShowing()).thenReturn(true); selectionPlane.transmitSelection(selectionDriverB, selectionB); reset(selectionModel); triggerHierarchyChangeEvent(componentA); verify(selectionModel, never()).setSelectedObject(selectionA); verify(selectionModel, times(1)).setSelectedObject(selectionB); } /** * Tests the case when multiple hierarchy change events occur. If the hierarchy events are fired from * multiple drivers but each firing results in the same state of driver visibility and selection state * then only one selection transmition should take place. */ @Test public void shouldNotTransmitMultipleSelections() { selectionPlane.registerSelectionDriver(selectionDriverA); selectionPlane.registerSelectionDriver(selectionDriverB); when(componentA.isShowing()).thenReturn(true); triggerHierarchyChangeEvent(componentA); triggerHierarchyChangeEvent(componentB); verify(selectionModel, times(1)).setSelectedObject(anyObject()); } private static void triggerHierarchyChangeEvent(Component component) { // Capture the listener that is added ArgumentCaptor<HierarchyListener> listener = ArgumentCaptor.forClass(HierarchyListener.class); verify(component, times(1)).addHierarchyListener(listener.capture()); // Now trigger the hierarchy event listener.getValue().hierarchyChanged(mock(HierarchyEvent.class)); } }
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.master; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.ConfigurerStrategy; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.support.component.PropertyConfigurerSupport; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class MasterEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("namespace", java.lang.String.class); map.put("delegateUri", java.lang.String.class); map.put("bridgeErrorHandler", boolean.class); map.put("exceptionHandler", org.apache.camel.spi.ExceptionHandler.class); map.put("exchangePattern", org.apache.camel.ExchangePattern.class); map.put("basicPropertyBinding", boolean.class); map.put("synchronous", boolean.class); ALL_OPTIONS = map; ConfigurerStrategy.addConfigurerClearer(MasterEndpointConfigurer::clearConfigurers); } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { MasterEndpoint target = (MasterEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "basicpropertybinding": case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } public static void clearBootstrapConfigurers() { } public static void clearConfigurers() { ALL_OPTIONS.clear(); } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { MasterEndpoint target = (MasterEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "basicpropertybinding": case "basicPropertyBinding": return target.isBasicPropertyBinding(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "synchronous": return target.isSynchronous(); default: return null; } } }
/* * Copyright 2015 Karl Dahlgren * * 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.castlemock.web.mock.rest.web.view.controller; import com.castlemock.web.mock.rest.web.AbstractControllerTest; /** * @author Karl Dahlgren * @since 1.0 */ public abstract class AbstractRestControllerTest extends AbstractControllerTest { protected static final String SERVICE_URL = "/web/rest/"; protected static final String REST_MOCK_RESPONSE = "restMockResponse"; protected static final String REST_MOCK_RESPONSE_STRATEGIES = "restMockResponseStrategies"; protected static final String RESPONSE = "response"; protected static final String REST_PROJECT = "restProject"; protected static final String METHOD = "method"; protected static final String RESOURCE = "resource"; protected static final String REST_PROJECT_ID = "restProjectId"; protected static final String REST_RESOURCE_ID = "restResourceId"; protected static final String REST_METHOD_ID = "restMethodId"; protected static final String REST_RESOURCE = "restResource"; protected static final String REST_METHOD = "restMethod"; protected static final String APPLICATION = "application"; protected static final String REST_APPLICATION = "restApplication"; protected static final String REST_APPLICATION_ID = "restApplicationId"; protected static final String EVENT = "event"; protected static final Integer GLOBAL_VIEW_MODEL_COUNT = 8; }
/** * @PartnerAction.java * @com.lingnet.vocs.action.partner * @Description: * * @author zy * @copyright 2017 * @version V * @since 2017年6月2日 */ package com.lingnet.vocs.action.partner; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.hibernate.criterion.Restrictions; import com.alibaba.fastjson.JSONObject; import com.lingnet.common.action.BaseAction; import com.lingnet.common.action.BaseAction.Status; import com.lingnet.qxgl.entity.QxUsers; import com.lingnet.qxgl.service.AdminService; import com.lingnet.qxgl.service.BackendRoleService; import com.lingnet.util.Constants; import com.lingnet.util.JsonUtil; import com.lingnet.util.LingUtil; import com.lingnet.vocs.entity.Contacts; import com.lingnet.vocs.entity.Demand; import com.lingnet.vocs.entity.Joint; import com.lingnet.vocs.entity.Partner; import com.lingnet.vocs.entity.SewageBusiness; import com.lingnet.vocs.service.baseinfo.AreaService; import com.lingnet.vocs.service.partner.ContactsService; import com.lingnet.vocs.service.partner.PartnerService; /** * 合作商 * * @ClassName: PartnerAction * @Description: TODO * @author zy * @date 2017年6月2日 下午3:28:30 * */ @ParentPackage("partner") @Namespace("/partner") public class PartnerAction extends BaseAction { private static final long serialVersionUID = 3468554186829112057L; @Resource(name = "partnerService") private PartnerService partnerService; @Resource(name = "areaService") private AreaService areaService; @Resource(name = "contactsService") private ContactsService contactsService; @Resource(name = "adminService") private AdminService adminService; @Resource(name = "backendRoleService") private BackendRoleService backendRoleService; private Partner partner; private String provinceId;// 省份id private String cityId;// 城市id private String formdata;// 表单数据 private String griddata;// 联系人列表 private String areaId;// 区域id private Joint joint;//对接人表 private String partnerId;//合作商id private String bhyj; public String threadId; private SewageBusiness business; /** * 列表页 * * @Title: list * @return String * @author zy * @since 2017年6月2日 V 1.0 */ public String list() { return LIST; } /** * 列表页:我的合作商 * * @Title: hsjlist * @return * @author zy * @since 2017年7月4日 V 1.0 */ public String myList() { return "mylist"; } /** * 合作商拥有设备 * * @Title: ownedequipment * @return String * @author zy * @since 2017年6月5日 V 1.0 */ public String ownedequipment() { return "ownedequipment"; } /** * 合作商地图(废弃) * * @Title: map * @return String * @author zy * @since 2017年6月20日 V 1.0 */ public String map() { return "map"; } /** * 设备地图(废弃) * * @Title: equipmentmap * @return String * @author zy * @since 2017年6月20日 V 1.0 */ public String equipmentmap() { return "equipment_map"; } /** * 定向跳转 到 未被占用的设备页面 * * @Title: equipmentlist * @return String * @author zy * @since 2017年6月5日 V 1.0 */ @Action(value = "equipmentlist", results = { @Result(name = "equipmentlist", location = "/equipmentlist.jsp") }) public String equipmentlist() { return "equipmentlist"; } /** * 添加页 * * @Title: add * @return String * @author zy * @since 2017年6月2日 V 1.0 */ public String add() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");// 单号由开头+年月日时分秒合成 threadId =simpleDateFormat.format(new Date());// 编码 return ADD; } /** * 编辑页 * * @Title: edit * @return String * @author zy * @since 2017年6月2日 V 1.0 */ public String edit() { partner = partnerService.get(Partner.class, id); if (null == partner) { partner = new Partner(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");// 单号由开头+年月日时分秒合成 threadId =simpleDateFormat.format(new Date());// 编码 }else{ if(StringUtils.isEmpty(partner.getThreadId())){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");// 单号由开头+年月日时分秒合成 threadId =simpleDateFormat.format(new Date());// 编码 }else{ threadId = partner.getThreadId(); } } // 手动设置 管辖区域 的中文名称 /* * String[] arr = partner.getJurisdictionArea().split(","); String * sJurisdictionCn = ""; for (int i = 0; i < arr.length; ++i) { * sJurisdictionCn += areaService.get(Area.class, arr[i]).getName()+ * ","; } sJurisdictionCn = sJurisdictionCn.substring(0, * sJurisdictionCn.length() - 1); * partner.setJurisdictionCn(sJurisdictionCn); */ // 上级、归属 String higherAgentName = partnerService.get(Partner.class, partner.getHigherAgent()).getName(); partner.setHigherAgentName(higherAgentName); business = partnerService.getBusinessBySewageId(id); return ADD; } /** * 查看页 * * @Title: look * @return String * @author zy * @since 2017年6月3日 V 1.0 */ public String look() { getRequest().setAttribute("flag", "false"); partner = partnerService.get(Partner.class, id); if (null == partner) { partner = new Partner(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");// 单号由开头+年月日时分秒合成 threadId =simpleDateFormat.format(new Date());// 编码 }else{ threadId = partner.getThreadId(); } // 上级、归属 String higherAgentName = partnerService.get(Partner.class, partner.getHigherAgent()).getName(); partner.setHigherAgentName(higherAgentName); business = partnerService.getBusinessBySewageId(id); return ADD; } /** * 添加页:我的合作商 * * @Title: hsjAdd * @return * @author zy * @since 2017年7月4日 V 1.0 */ public String myAdd() { partner = new Partner(); QxUsers currentUser = (QxUsers) partnerService.get(QxUsers.class, Restrictions.eq("username", LingUtil.userName())); partner.setHigherAgent(currentUser.getPartnerId()); Partner p = partnerService.get(Partner.class, Restrictions.eq("id", currentUser.getPartnerId())); partner.setHigherAgentName(p == null ? "" : p.getName()); return "myadd"; } /** * 编辑页:合作商信息管理 * * @Title: myEdit * @return * @author zy * @since 2017年7月4日 V 1.0 */ public String myEdit() { partner = partnerService.get(Partner.class, id); if (null == partner) { partner = new Partner(); } // 上级、归属 String higherAgentName = partnerService.get(Partner.class, partner.getHigherAgent()).getName(); partner.setHigherAgentName(higherAgentName); return "myadd"; } /** * 查看页:合作商信息管理 * * @Title: myLook * @return * @author zy * @since 2017年7月10日 V 1.0 */ public String myLook() { getRequest().setAttribute("flag", "false"); partner = partnerService.get(Partner.class, id); if (null == partner) { partner = new Partner(); } // 上级、归属 String higherAgentName = partnerService.get(Partner.class, partner.getHigherAgent()).getName(); partner.setHigherAgentName(higherAgentName); return "myadd"; } /** * 删除 * * @Title: remove * @return String * @author zy * @since 2017年6月3日 V 1.0 */ public String remove() { try { partnerService.remove(ids[0]); return ajax(Status.success, "success"); } catch (Exception e) { return ajax(Status.success, e.getMessage()); } } /** * 删除 我的合作商 * * @Title: remove * @return String * @author zy * @since 2017年7月26日 V 1.0 */ public String myRemove() { try { partnerService.remove(ids[0]); return ajax(Status.success, "success"); } catch (Exception e) { return ajax(Status.success, "删除失败"); } } /** * 获取列表数据 * * @Title: getMyListData * @return String * @author zy * @since 2017年6月3日 V 1.0 */ @SuppressWarnings("rawtypes") public String getMyListData() { HashMap result = partnerService.getMyPartnerListData(pager, Constants.PARTNER, areaId); String json = JsonUtil.Encode(result); return ajax(Status.success, json); } /** * 跳转审核页面 * @Title: check * @return * String * @author lizk * @since 2018年2月26日 V 1.0 */ public String check(){ partner = this.getBeanById(Partner.class, id); return "check"; } public String sh() { try { partner=getBeanById(Partner.class, id); partner.setStatus("2"); partnerService.update(partner); backendRoleService.createRoleAuto(partner.getId(), partner.getPartnerOrCustomer(),partner.getName(),partner.getCode()); return ajax(Status.success, "success"); } catch (Exception e) { return ajax(Status.success, "审核失败"); } } public String shno() { try { partner=getBeanById(Partner.class, id); partner.setStatus("3"); partner.setBhyj(bhyj); partnerService.update(partner); return ajax(Status.success, "success"); } catch (Exception e) { return ajax(Status.success, "审核失败"); } } public String jf() { try { partner=getBeanById(Partner.class, id); partner.setJfstatus("0"); partnerService.update(partner); return ajax(Status.success, "success"); } catch (Exception e) { return ajax(Status.success, "提交失败"); } } public String tj() { try { partner=getBeanById(Partner.class, id); partner.setStatus("1"); partner.setTjsj(new Date()); partner.setBhyj(""); partnerService.update(partner); return ajax(Status.success, "success"); } catch (Exception e) { return ajax(Status.success, "提交失败"); } } public String ntj() { try { partner=getBeanById(Partner.class, id); partner.setBhyj(bhyj);; partner.setStatus("4"); partnerService.update(partner); return ajax(Status.success, "success"); } catch (Exception e) { return ajax(Status.success, "重新提交失败"); } } /** * @Title: getListData * @return * @author zy * @since 2017年7月4日 V 1.0 */ @SuppressWarnings("rawtypes") public String getListData() { if (partner == null) { partner = new Partner(); } HashMap result = partnerService.getPartnerListData(pager, partner.getId(), areaId); String json = JsonUtil.Encode(result); return ajax(Status.success, json); } /** * 联系人列表 * * @Title: getContactListData * @return String * @author zy * @since 2017年6月5日 V 1.0 */ public String getContactListData() { String partnerId = getRequest().getParameter("partnerId"); if (StringUtils.isNotEmpty(partnerId)) { String json = JsonUtil.Encode(partnerService .getContactListData(partnerId)); return ajax(Status.success, json); } else { return ajax(Status.success, NONE); } } /** * 根据客户获取联系人 * * @Title: getContactByPartnertData * @return String * @author 薛硕 * @since 2017年7月5日 V 1.0 */ public String getContactByPartnertData() { if (partner == null) { partner = new Partner(); } String partnerId = partner.getId(); if (StringUtils.isNotEmpty(partnerId)) { String json = JsonUtil.Encode(partnerService .getContactListData(partnerId)); return ajax(Status.success, json); } else { return ajax(Status.success, NONE); } } /** * 合作商拥有设备列表 * * @Title: getPartnerEquipmentlist * @return String * @author zy * @since 2017年6月6日 V 1.0 */ @SuppressWarnings({ "rawtypes" }) public String getPartnerEquipmentlist() { pager.setSearchData(searchData); if (id == null) { id = this.getSession("partnerId").toString(); } HashMap mapResult = partnerService.getPartnerEquipList(pager, id); String json = JsonUtil.Encode(mapResult); return ajax(Status.success, json); } /** * 未被占用的设备的列表 * * @Title: getAvailableEquipmentlist * @return String * @author zy * @since 2017年6月6日 V 1.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public String getAvailableEquipmentlist() { HashMap map = new HashMap(); map.put("id", "EQ0005"); map.put("equipmentCode", "EQ0005"); map.put("equipmentName", "蜂窝活性炭吸附回收"); map.put("equipmentPosition", "山东青岛"); map.put("equipmentOwner", "华世洁"); HashMap map2 = new HashMap(); map2.put("id", "EQ0006"); map2.put("equipmentCode", "EQ0006"); map2.put("equipmentName", "活性炭颗粒吸附回收"); map2.put("equipmentPosition", "山东青岛"); map2.put("equipmentOwner", "华世洁"); ArrayList arrlist = new ArrayList(); arrlist.add(map); arrlist.add(map2); HashMap mapResult = new HashMap(); mapResult.put("data", arrlist); mapResult.put("total", 1); String json = JsonUtil.Encode(mapResult); return ajax(Status.success, json); } /** * 保存或更新 * * @Title: saveOrUpdate * @return String * @author zy * @since 2017年6月3日 V 1.0 */ public String saveOrUpdate() { try { partner = JSONObject.parseObject(formdata, Partner.class); String business = getRequest().getParameter("formdataBusiness"); //partnerService.saveOrUpdate(partner, griddata); partnerService.saveOrUpdate(partner, griddata,business); return ajax(Status.success, "success"); } catch (Exception e) { return ajax(e.toString().substring(e.toString().indexOf(":") + 1), "text/html;charset=UTF-8"); } } /** * 区域三级联动:获取全部省份 * * @Title: getProvinceData * @return String * @author zy * @since 2017年6月20日 V 1.0 */ public String getProvinceData() { ArrayList<HashMap<String, String>> arrList = areaService .getChildrenArea("0"); String json = JsonUtil.Encode(arrList); return ajax(Status.success, json); } /** * 区域三级联动:根据省份id获取全部城市 * * @Title: getCityData * @return String * @author zy * @since 2017年6月20日 V 1.0 */ public String getCityData() { ArrayList<HashMap<String, String>> arrList = areaService .getChildrenArea(provinceId); String json = JsonUtil.Encode(arrList); return ajax(Status.success, json); } /** * 区域三级联动:根据城市id获取全部市区 * * @Title: getDistrictData * @return String * @author zy * @since 2017年6月20日 V 1.0 */ public String getDistrictData() { ArrayList<HashMap<String, String>> arrList = areaService .getChildrenArea(cityId); String json = JsonUtil.Encode(arrList); return ajax(Status.success, json); } /** * 输入名字时验证唯一性 * * @Title: validateName * @return * @author zy * @since 2017年6月21日 V 1.0 */ public String validateName() { try { String name = URLDecoder.decode(getRequest().getParameter("name"), "utf-8"); String s = partnerService.validateName(name); return ajax(Status.success, s); } catch (Exception e) { return ajax(e.toString().substring(e.toString().indexOf(":") + 1), "text/html;charset=UTF-8"); } } /** * 删除联系人 * * @Title: removeContact * @return * @author zy * @since 2017年6月23日 V 1.0 */ public String removeContact() { try { Contacts contacts = contactsService.get(Contacts.class, id); if (null != contacts) { contactsService.delete(id); } return ajax(Status.success, "success"); } catch (Exception e) { e.printStackTrace(); return ajax(Status.error, "删除失败"); } } /** * 合作商选择 * * @Title: chosing * @return * @author zy * @since 2017年6月22日 V 1.0 */ public String chosing() { if (partner == null) { partner = new Partner(); } return "chosing"; } /** * 获取合作商表的数据 * * @Title: partnerData * @return String * @author duanjj * @since 2017年6月23日 V 1.0 */ public String partnerData() { List<HashMap<String, String>> result = partnerService .partnerData(searchData); String json = JsonUtil.Encode(result); return ajax(Status.success, json); } /** * 获取全部合作商、客户 * * @Title: getAllPartnerAndCustomer * @return * @author zy * @since 2017年6月28日 V 1.0 */ @SuppressWarnings("rawtypes") public String getAllPartnerAndCustomer() { String partnerId = (String) (getRequest().getSession() .getAttribute("partnerId")); // 没有选合作商类型,应该key=undifined,但如果打开页面过快,key可能会是空串"",可能是miniui还未加载到合作商/客户的DOM /* * if (StringUtils.isBlank(key)) { key = "undefined"; } */ HashMap m = partnerService.getPandC4FirstParty(pager, partnerId, key); String s = JsonUtil.Encode(m); return ajax(Status.success, s); } /** * 设备归属转移选择公司 * * @Title: getAllCustomer * @return String * @author wanl * @since 2017年7月17日 V 1.0 */ @SuppressWarnings("rawtypes") public String getAllCustomer() { String partnerId = (String) (getRequest().getSession() .getAttribute("partnerId")); HashMap m = partnerService.getPandC4FirstParty(pager, partnerId, key); String s = JsonUtil.Encode(m); return ajax(Status.success, s); } /** * 根据id 获取 客户 或者合作商 * * @Title: getById * @return String * @author 薛硕 * @since 2017年7月3日 V 1.0 */ public String getById() { partner = partnerService.get(Partner.class, id); return ajax(Status.success, JsonUtil.Encode(partner)); } /** * 跳转设备使用者选择页 * * @Title: equipUser * @return * @author zy * @since 2017年7月14日 V 1.0 */ public String equipUser() { return "equip_user"; } /** * 设备使用者 列表 * * @Title: getEquipUserList * @return * @author zy * @since 2017年7月14日 V 1.0 */ @SuppressWarnings("rawtypes") public String getEquipUserList() { HashMap m = partnerService.getEquipUserList(pager); String s = JsonUtil.Encode(m); return ajax(Status.success, s); } /** * 能进行合作商上级归属编辑的只有华世杰 进入此函数也只能在编辑页面 递归验证所选合作商是否是当前合作商的子、孙单位 * * @Title: validateHigherAgent * @return * @author zy * @since 2017年7月24日 V 1.0 */ public String validateHigherAgent() { String chosenId = getRequest().getParameter("chosenId"); String s = partnerService.validateHigherAgent(id, chosenId); return ajax(Status.success, s); } /** * 跳转对接人列表 * @Title: joint * @return * String * @author lizk * @since 2018年2月2日 V 1.0 */ public String joint(){ return "joint_list"; } public String jointAdd(){ return "joint_add"; } public String jointEdit(){ joint = this.getBeanById(Joint.class, id); return "joint_add"; } public String jointLook(){ joint = this.getBeanById(Joint.class, id); getRequest().setAttribute("flag", "false"); return "joint_add"; } /** * 对接人展示列表 * @Title: getJointData * @return * String * @author lizk * @since 2018年2月2日 V 1.0 */ public String getJointData(){ String json = partnerService.getJointData(pager); return ajax(Status.success, json); } /** * 保存编辑对接人 * @Title: saveJoint * @return * String * @author lizk * @since 2018年2月2日 V 1.0 */ public String saveJoint(){ try { String json = partnerService.saveJoint(formdata); return ajax(Status.success,json); } catch (Exception e) { return ajax(Status.error,e.getMessage()); } } /** * 删除对接人 * @Title: deleteJoint * @return * String * @author lizk * @since 2018年2月2日 V 1.0 */ public String deleteJoint(){ try { Joint j = this.getBeanByCriteria(Joint.class, Restrictions.eq("id", id)); QxUsers user = adminService.load(QxUsers.class,j.getUserId()); user.setIsDeleted("1"); adminService.update(user); this.deleteByCriteria(Joint.class, Restrictions.eq("id", id)); return ajax(Status.success, "success"); } catch (Exception e) { e.printStackTrace(); return ajax(Status.error, "删除失败"); } } /** * 跳转指定对接人页面 * @Title: zddjr * @return * String * @author lizk * @since 2018年2月3日 V 1.0 */ public String zddjr(){ return "zddjr"; } /** * 合作商保存对接人 * @Title: saveDjr * @return * String * @author lizk * @since 2018年2月3日 V 1.0 */ public String saveDjr(){ try { Partner partner = this.getBeanByCriteria(Partner.class, Restrictions.eq("id", partnerId)); partner.setDjr(id); partnerService.update(partner); return ajax(Status.success,"success"); } catch (Exception e) { return ajax(Status.error,"指定失败"); } } /** * 跳转对接人负责的合作商 * @Title: hzs * @return * String * @author lizk * @since 2018年2月3日 V 1.0 */ public String hzs(){ return "hzs"; } public String getHzcData(){ String json = partnerService.getHzcData(pager,id); return ajax(Status.success, json); } /////////////////////////////////////////////////////////////////////// /** * @return the provinceId */ public String getProvinceId() { return provinceId; } /** * @param provinceId * the provinceId to set */ public void setProvinceId(String provinceId) { this.provinceId = provinceId; } /** * @return the cityId */ public String getCityId() { return cityId; } /** * @param cityId * the cityId to set */ public void setCityId(String cityId) { this.cityId = cityId; } /** * @return the partner */ public Partner getPartner() { return partner; } /** * @param partner * the partner to set */ public void setPartner(Partner partner) { this.partner = partner; } /** * @return the formdata */ public String getFormdata() { return formdata; } /** * @param formdata * the formdata to set */ public void setFormdata(String formdata) { this.formdata = formdata; } /** * @return the griddata */ public String getGriddata() { return griddata; } /** * @param griddata * the griddata to set */ public void setGriddata(String griddata) { this.griddata = griddata; } public String getAreaId() { return areaId; } public void setAreaId(String areaId) { this.areaId = areaId; } public Joint getJoint() { return joint; } public void setJoint(Joint joint) { this.joint = joint; } public String getPartnerId() { return partnerId; } public void setPartnerId(String partnerId) { this.partnerId = partnerId; } public String getBhyj() { return bhyj; } public void setBhyj(String bhyj) { this.bhyj = bhyj; } public String getThreadId() { return threadId; } public void setThreadId(String threadId) { this.threadId = threadId; } public SewageBusiness getBusiness() { return business; } public void setBusiness(SewageBusiness business) { this.business = business; } }
package com.goat.chapter200.base; /** * 媒体播放器 接口,其实现类有 box播放器,cd播放器 * */ public interface MediaPlayer { void insert(); }
package ru.taximaxim.codekeeper.apgdiff.utils; import java.io.Serializable; /** * Objects of this class are unmodifiable. * Use {@link ModPair} and {@link #copyMod()} to get modifiable Pairs. */ public class Pair<K, V> implements Serializable { private static final long serialVersionUID = 3151284706296455602L; protected K first; protected V second; public Pair(K first, V second) { this.first = first; this.second = second; } public K getFirst() { return first; } public V getSecond(){ return second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((first == null) ? 0 : first.hashCode()); result = prime * result + ((second == null) ? 0 : second.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Pair<?, ?> other = (Pair<?, ?>) obj; if (first == null) { if (other.first != null) { return false; } } else if (!first.equals(other.first)) { return false; } if (second == null) { if (other.second != null) { return false; } } else if (!second.equals(other.second)) { return false; } return true; } @Override public String toString() { return "(" + first + " - " + second + ")"; } public Pair<K, V> copy() { return new Pair<>(first, second); } public ModPair<K, V> copyMod() { return new ModPair<>(first, second); } }
package org.kunze.diansh.controller.vo; import lombok.Data; import org.kunze.diansh.salesTicket.SalesTicket; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Random; /*** * 相似商品 */ @Data public class BeSimilarSpuVo implements Serializable { /**spuId*/ private String spuId; /**商品名称*/ private String spuTitle; /**缩略图*/ private String image; /**商品现在价格*/ private String spuNewPrice; /**商品原价格*/ private String spuPrice; /**SkuId*/ private String skuId; //sku规格 private String skuSpec; }
package br.com.command.activities; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.Toast; import android.widget.ToggleButton; import br.com.command.comandos.ControleRemoto; import br.com.command.comandos.GaragemAbrirCommand; import br.com.command.comandos.GaragemFecharCommand; import br.com.command.comandos.PersianaSalaEstarAbrirCommand; import br.com.command.comandos.PersianaSalaEstarFecharCommand; import br.com.command.comandos.PersianaSuiteAbrirCommand; import br.com.command.comandos.PersianaSuiteFecharCommand; import br.com.command.comandos.PortaPrincipalAbrirCommand; import br.com.command.comandos.PortaPrincipalFecharCommand; import br.com.command.comandos.PortaoAbrirCommand; import br.com.command.comandos.PortaoFecharCommand; import br.com.command.interfaces.Command; import br.com.command.modelos.Garagem; import br.com.command.modelos.PersianaSalaEstar; import br.com.command.modelos.PersianaSuite; import br.com.command.modelos.Porta; import br.com.command.modelos.Portao; import br.com.command.modelos.StatusController; import br.com.command.util.OnStatusChangeListener; public class PersianasActivity extends AppCompatActivity { private ToggleButton togglePersianaSalaEstar; private ToggleButton togglePersianaSuite; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_persianas); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); StatusController statusController = StatusController.getInstance(); togglePersianaSalaEstar = (ToggleButton) findViewById(R.id.tgbPersianaSalaDeEstar); togglePersianaSuite = (ToggleButton) findViewById(R.id.tgbPersianaSuite); PersianaSuite persianaSuite = new PersianaSuite(); persianaSuite.setOnStatusChangeListener(new OnStatusChangeListener() { @Override public void onChange(boolean newStatus) { if (togglePersianaSuite.isChecked() != newStatus){ Toast.makeText(getApplicationContext(), getString(R.string.notificao_se_erro_servidor), Toast.LENGTH_LONG).show(); } togglePersianaSuite.setChecked(newStatus); } }); PersianaSalaEstar persianaSalaEstar = new PersianaSalaEstar(); persianaSalaEstar.setOnStatusChangeListener(new OnStatusChangeListener() { @Override public void onChange(boolean newStatus) { if (togglePersianaSalaEstar.isChecked() != newStatus){ Toast.makeText(getApplicationContext(), getString(R.string.notificao_se_erro_servidor), Toast.LENGTH_LONG).show(); } togglePersianaSalaEstar.setChecked(newStatus); } }); Command persianaSalaEstarAbrirCommand = new PersianaSalaEstarAbrirCommand(persianaSalaEstar); Command persianaSalaEstarFecharCommand = new PersianaSalaEstarFecharCommand(persianaSalaEstar); Command persianaSuiteAbrirCommand = new PersianaSuiteAbrirCommand(persianaSuite); Command persianaSuiteFecharCommand = new PersianaSuiteFecharCommand(persianaSuite); ControleRemoto controleRemoto = new ControleRemoto(); controleRemoto.setCommand(PersianaSalaEstar.ID, persianaSalaEstarAbrirCommand, persianaSalaEstarFecharCommand); controleRemoto.setCommand(PersianaSuite.ID, persianaSuiteAbrirCommand, persianaSuiteFecharCommand); togglePersianaSalaEstar.setChecked(statusController.isPersianaSalaEstarAberta()); togglePersianaSuite.setChecked(statusController.isPersianaSuiteAberta()); togglePersianaSalaEstar.setOnClickListener(new CommandOnClick(PersianaSalaEstar.ID, controleRemoto)); togglePersianaSuite.setOnClickListener(new CommandOnClick(PersianaSuite.ID, controleRemoto)); } }
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2011 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.soap.admin.message; import javax.xml.bind.annotation.XmlRootElement; import com.zimbra.common.soap.BackupConstants; @XmlRootElement(name=BackupConstants.E_MOVE_MAILBOX_RESPONSE) public class MoveMailboxResponse { }
[ buildVersion=51.0, instances=( ConnectApi.OrchestrationInstance [ buildVersion=51.0, id=0jE9A000000000VUAQ, pausedInterviewId=0Fo9A0000002HdcSAE, stageInstances=( ConnectApi.OrchestrationStageInstance[ buildVersion=51.0, id=0jF9A000000000VUAQ, label=Submit Content, name=Submit_Content, position=0, stageStepInstances=( ConnectApi.OrchestrationStepInstance[ buildVersion=51.0, id=0jL9A000000000VUAQ, label=Submit Content for Approval, name=Submit_Content_for_Approval, status=InProgress, type=Task, workAssignments=( ConnectApi.OrchestrationWorkAssignment[ buildVersion=51.0, assigneeId=null, contextRecordId=0019A00000Gg58lQAB, description=null, id=0jf9A0000000006QAA, label=Submit Content, screenFlowId=3009A0000000JxIQAU, screenFlowInputParameters={"recordId":["0019A00000Gg58lQAB"],"appProcessStepInstanceId":["0jL9A000000000V"],"appProcessInstanceId":["0jE9A000000000V"]}, status=NotStarted ] ) ] ), status=InProgress ] ), status=InProgress ] ) ] 20:34:44.2 (28141890)|STATEMENT_EXECUTE|[36]
/* * Copyright (C) 2004 - 2014 Brian McCallister * * 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.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcConnectionPool; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.sqlobject.mixins.CloseMe; import org.skife.jdbi.v2.tweak.HandleCallback; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; public class TestGetGeneratedKeysPostgres { private JdbcConnectionPool ds; private DBI dbi; @Before public void setUp() throws Exception { dbi = new DBI("jdbc:postgresql:test", "postgres", "postgres"); dbi.withHandle(new HandleCallback<Object>() { @Override public Object withHandle(Handle handle) throws Exception { handle.execute("create sequence id_sequence INCREMENT 1 START WITH 100"); handle.execute("create table if not exists something (name text, id int DEFAULT nextval('id_sequence'), CONSTRAINT something_id PRIMARY KEY ( id ));"); return null; } }); } @After public void tearDown() throws Exception { dbi.withHandle(new HandleCallback<Object>() { @Override public Object withHandle(Handle handle) throws Exception { handle.execute("drop table something"); handle.execute("drop sequence id_sequence"); return null; } }); } public static interface DAO extends CloseMe { @SqlUpdate("insert into something (name, id) values (:name, nextval('id_sequence'))") @GetGeneratedKeys(columnName = "id") public long insert(@Bind("name") String name); @SqlQuery("select name from something where id = :it") public String findNameById(@Bind long id); } @Ignore @Test public void testFoo() throws Exception { DAO dao = dbi.open(DAO.class); Long brian_id = dao.insert("Brian"); long keith_id = dao.insert("Keith"); assertThat(dao.findNameById(brian_id), equalTo("Brian")); assertThat(dao.findNameById(keith_id), equalTo("Keith")); dao.close(); } }
package com.leviathanstudio.test.pack.animation; import javax.vecmath.Quat4f; import com.leviathanstudio.craftstudio.client.model.CSModelRenderer; import com.leviathanstudio.craftstudio.client.util.MathHelper; import com.leviathanstudio.craftstudio.common.animation.CustomChannel; import com.leviathanstudio.craftstudio.common.animation.IAnimated; import net.minecraft.entity.EntityLiving; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class AnimationLootAt extends CustomChannel { private String headPart; public AnimationLootAt(String headPartIn) { super("lookat"); this.headPart = headPartIn; } @Override @SideOnly(Side.CLIENT) public void update(CSModelRenderer parts, IAnimated animated) { if (animated instanceof EntityLiving) if (parts.boxName.equals(this.headPart)) { EntityLiving entityL = (EntityLiving) animated; float diff = entityL.getRotationYawHead() - entityL.renderYawOffset; Quat4f quat = MathHelper.quatFromEuler(entityL.rotationPitch, 0.0F, diff); Quat4f quat2 = new Quat4f(parts.getDefaultRotationAsQuaternion()); quat.mul(quat2); parts.getRotationMatrix().set(quat); parts.getRotationMatrix().transpose(); } } }
/* * NullYAGetCharFieldTest2.java * Copyright 2008, 2009, 2010, 2011, 2012, 2013 Fiji Systems Inc. * This file is part of the FIJI VM Software licensed under the FIJI PUBLIC * LICENSE Version 3 or any later version. A copy of the FIJI PUBLIC LICENSE is * available at fivm/LEGAL and can also be found at * http://www.fiji-systems.com/FPL3.txt * * By installing, reproducing, distributing, and/or using the FIJI VM Software * you agree to the terms of the FIJI PUBLIC LICENSE. You may exercise the * rights granted under the FIJI PUBLIC LICENSE subject to the conditions and * restrictions stated therein. Among other conditions and restrictions, the * FIJI PUBLIC LICENSE states that: * * a. You may only make non-commercial use of the FIJI VM Software. * * b. Any adaptation you make must be licensed under the same terms * of the FIJI PUBLIC LICENSE. * * c. You must include a copy of the FIJI PUBLIC LICENSE in every copy of any * file, adaptation or output code that you distribute and cause the output code * to provide a notice of the FIJI PUBLIC LICENSE. * * d. You must not impose any additional conditions. * * e. You must not assert or imply any connection, sponsorship or endorsement by * the author of the FIJI VM Software * * f. You must take no derogatory action in relation to the FIJI VM Software * which would be prejudicial to the FIJI VM Software author's honor or * reputation. * * * The FIJI VM Software is provided as-is. FIJI SYSTEMS INC does not make any * representation and provides no warranty of any kind concerning the software. * * The FIJI PUBLIC LICENSE and any rights granted therein terminate * automatically upon any breach by you of the terms of the FIJI PUBLIC LICENSE. */ package com.fiji.fivm.test; public class NullYAGetCharFieldTest2 { public static void main(String[] v) { YetAnotherClass o=null; System.out.println("result = "+o.icnumber2); } }