text
stringlengths
7
1.01M
package org.apache.commons.jcs.utils.discovery; /* * 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. */ import java.util.HashMap; import java.util.Map; import org.apache.commons.jcs.engine.behavior.ICompositeCacheManager; import org.apache.commons.jcs.engine.behavior.IProvideScheduler; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This manages UDPDiscovery Services. We should end up with one service per Lateral Cache Manager * Instance. One service works for multiple regions. We don't want a connection for each region. * <p> * @author Aaron Smuts */ public class UDPDiscoveryManager { /** The logger */ private static final Log log = LogFactory.getLog( UDPDiscoveryManager.class ); /** Singleton instance */ private static UDPDiscoveryManager INSTANCE = new UDPDiscoveryManager(); /** Known services */ private final Map<String, UDPDiscoveryService> services = new HashMap<String, UDPDiscoveryService>(); /** private for singleton */ private UDPDiscoveryManager() { // noopt } /** * Singleton * <p> * @return UDPDiscoveryManager */ public static UDPDiscoveryManager getInstance() { return INSTANCE; } /** * Creates a service for the address and port if one doesn't exist already. * <p> * We need to key this using the listener port too. TODO think of making one discovery service * work for multiple types of clients. * <p> * @param discoveryAddress * @param discoveryPort * @param servicePort * @param cacheMgr * @return UDPDiscoveryService */ public synchronized UDPDiscoveryService getService( String discoveryAddress, int discoveryPort, int servicePort, ICompositeCacheManager cacheMgr ) { String key = discoveryAddress + ":" + discoveryPort + ":" + servicePort; UDPDiscoveryService service = services.get( key ); if ( service == null ) { if ( log.isInfoEnabled() ) { log.info( "Creating service for address:port:servicePort [" + key + "]" ); } UDPDiscoveryAttributes attributes = new UDPDiscoveryAttributes(); attributes.setUdpDiscoveryAddr( discoveryAddress ); attributes.setUdpDiscoveryPort( discoveryPort ); attributes.setServicePort( servicePort ); service = new UDPDiscoveryService( attributes ); // register for shutdown notification cacheMgr.registerShutdownObserver( service ); // inject scheduler if ( cacheMgr instanceof IProvideScheduler) { service.setScheduledExecutorService(((IProvideScheduler)cacheMgr).getScheduledExecutorService()); } service.startup(); services.put( key, service ); } if ( log.isDebugEnabled() ) { log.debug( "Returning service [" + service + "] for key [" + key + "]" ); } return service; } }
package com.jsoft.framework.ssm.model.sys.user; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * User 数据传输对象 * * @author jim * @date 2018/04/26 */ @Getter @Setter @ToString public class UserDTO extends UserDO { }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.04.22 at 12:42:32 PM SAST // package za.co.enigma.turing.mda.jee.xsd.javaee; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * * If WS-Addressing is enabled, this type determines if an endpoint * requires the use of only anonymous responses, or only non-anonymous * responses, or all. * * * * <p>Java class for addressing-responsesType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="addressing-responsesType"> * &lt;simpleContent> * &lt;restriction base="&lt;http://xmlns.jcp.org/xml/ns/javaee>string"> * &lt;/restriction> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "addressing-responsesType") public class AddressingResponsesType extends String { }
package com.com.robert.image.demonew; /** * Created by michael on 13-12-18. */ public class Config { public static final String QRCODE_CONTENT = "http://dajie.me/2vc294"; public static final int QRCODE_DEFAULT_SIZE = 500; public static final String KEY_QRCODE_CONTENT = "content"; public static final String KEY_RES_ID = "res"; }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.workspacesweb.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/workspaces-web-2020-07-08/ListUserSettings" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListUserSettingsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The pagination token used to retrieve the next page of results for this operation. * </p> */ private String nextToken; /** * <p> * The user settings. * </p> */ private java.util.List<UserSettingsSummary> userSettings; /** * <p> * The pagination token used to retrieve the next page of results for this operation. * </p> * * @param nextToken * The pagination token used to retrieve the next page of results for this operation. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The pagination token used to retrieve the next page of results for this operation. * </p> * * @return The pagination token used to retrieve the next page of results for this operation. */ public String getNextToken() { return this.nextToken; } /** * <p> * The pagination token used to retrieve the next page of results for this operation. * </p> * * @param nextToken * The pagination token used to retrieve the next page of results for this operation. * @return Returns a reference to this object so that method calls can be chained together. */ public ListUserSettingsResult withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * <p> * The user settings. * </p> * * @return The user settings. */ public java.util.List<UserSettingsSummary> getUserSettings() { return userSettings; } /** * <p> * The user settings. * </p> * * @param userSettings * The user settings. */ public void setUserSettings(java.util.Collection<UserSettingsSummary> userSettings) { if (userSettings == null) { this.userSettings = null; return; } this.userSettings = new java.util.ArrayList<UserSettingsSummary>(userSettings); } /** * <p> * The user settings. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setUserSettings(java.util.Collection)} or {@link #withUserSettings(java.util.Collection)} if you want to * override the existing values. * </p> * * @param userSettings * The user settings. * @return Returns a reference to this object so that method calls can be chained together. */ public ListUserSettingsResult withUserSettings(UserSettingsSummary... userSettings) { if (this.userSettings == null) { setUserSettings(new java.util.ArrayList<UserSettingsSummary>(userSettings.length)); } for (UserSettingsSummary ele : userSettings) { this.userSettings.add(ele); } return this; } /** * <p> * The user settings. * </p> * * @param userSettings * The user settings. * @return Returns a reference to this object so that method calls can be chained together. */ public ListUserSettingsResult withUserSettings(java.util.Collection<UserSettingsSummary> userSettings) { setUserSettings(userSettings); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()).append(","); if (getUserSettings() != null) sb.append("UserSettings: ").append(getUserSettings()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListUserSettingsResult == false) return false; ListUserSettingsResult other = (ListUserSettingsResult) obj; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; if (other.getUserSettings() == null ^ this.getUserSettings() == null) return false; if (other.getUserSettings() != null && other.getUserSettings().equals(this.getUserSettings()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); hashCode = prime * hashCode + ((getUserSettings() == null) ? 0 : getUserSettings().hashCode()); return hashCode; } @Override public ListUserSettingsResult clone() { try { return (ListUserSettingsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
package com.yjh.web.blog.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.yjh.web.blog.domain.Comment; /** * @author yujunhong * @date 2021/4/20 14:34 */ public interface CommentMapper extends BaseMapper<Comment> { }
package eu.rsulkowski.jdoocsoup.processor.descriptor; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.sun.tools.javac.code.Attribute; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.MirroredTypeException; import javax.lang.model.type.NoType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Types; import eu.rsulkowski.jdoocsoup.annotation.DataClassBuilder; import eu.rsulkowski.jdoocsoup.processor.utils.ElementsUtils; import lombok.Getter; /** * Created by rsulkowski on 10/2/17. */ /** * Contains the description of the DataClassBuilder such as: package name, element kind etc. */ @Getter public class DataClassBuilderDescriptor { private final static String BUILDER_NAME_POSTFIX = "Builder"; private final DataClassBuilder annotation; private final String dataClassBuilderName; private final String packageName; private final String setterPrefix; private final ProcessingEnvironment processingEnvironment; private final TypeElement typeElement; private final ElementKind elementKind; private final TypeSpec.Builder typeSpecBuilder; private final List<ExecutableElement> methods = new ArrayList<>(); private final List<VariableElement> fields = new ArrayList<>(); private TypeElement buildMethodReturnType; public DataClassBuilderDescriptor(ProcessingEnvironment env, TypeElement element) { annotation = element.getAnnotation(DataClassBuilder.class); try { annotation.buildMethodReturnType(); } catch (MirroredTypeException mte) { buildMethodReturnType = (TypeElement) env.getTypeUtils().asElement(mte.getTypeMirror()); } this.dataClassBuilderName = annotation.name().isEmpty() ? element.getSimpleName() + BUILDER_NAME_POSTFIX : annotation.name(); this.setterPrefix = annotation.setterPrefix(); this.packageName = ElementsUtils.parsePackageName(env, element); this.processingEnvironment = env; this.typeElement = element; this.elementKind = element.getKind(); this.typeSpecBuilder = TypeSpec.classBuilder(dataClassBuilderName); parseImplementInterfaces(); typeSpecBuilder.addModifiers(Modifier.PUBLIC); parseAll(); } private void parseImplementInterfaces() { AnnotationMirror annotationMirror = getAnnotationMirror(this.typeElement, DataClassBuilder.class.getName()); AnnotationValue inflationArgsValue = getAnnotationValue(annotationMirror, "implementInterfaces"); if (inflationArgsValue != null) { List<Attribute.Class> list = (List<Attribute.Class>) inflationArgsValue.getValue(); for (Attribute.Class superInterface : list) { TypeName superI = ClassName.bestGuess(superInterface.getValue().toString()); typeSpecBuilder.addSuperinterface(superI); } } } private static AnnotationMirror getAnnotationMirror(TypeElement typeElement, String className) { for (AnnotationMirror m : typeElement.getAnnotationMirrors()) { if (m.getAnnotationType().toString().equals(className)) { return m; } } return null; } private static AnnotationValue getAnnotationValue(AnnotationMirror annotationMirror, String key) { if (annotationMirror == null){ return null; } if (annotationMirror.getElementValues() == null){ return null; } for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) { if (entry.getKey().getSimpleName().toString().equals(key)) { return entry.getValue(); } } return null; } private TypeElement asTypeElement(TypeMirror typeMirror) { Types TypeUtils = this.processingEnvironment.getTypeUtils(); return (TypeElement) TypeUtils.asElement(typeMirror); } private void parseAll() { typeSpecBuilder.addJavadoc(annotation.jdocs() + "\n"); checkElementForMembers(typeElement); TypeMirror superElement = typeElement.getSuperclass(); while (superElement!=null){ Element superClassElement = processingEnvironment.getTypeUtils().asElement(superElement); if (superClassElement!=null) { checkElementForMembers(superClassElement); superElement = processingEnvironment.getElementUtils().getTypeElement(superClassElement.asType().toString()).getSuperclass(); }else{ superElement = null; } } } private void checkElementForMembers(Element rootElement) { for (Element element : rootElement.getEnclosedElements()) { if (element.getKind() == ElementKind.METHOD) { methods.add((ExecutableElement) element); } else if (element.getKind() == ElementKind.FIELD) { fields.add((VariableElement) element); } } } }
/* * 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.github.ipaas.ifw.server.ice; import java.net.InetAddress; import java.net.Socket; import java.nio.channels.SocketChannel; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import Ice.ConnectionI; import Ice.Current; import Ice.LocalObjectHolder; import Ice.LocalObjectImpl; import Ice.Object; import Ice.ServantLocator; import Ice.UserException; import IceInternal.Transceiver; import com.github.ipaas.ifw.core.exception.FwRuntimeException; /** * rpc代理中自定义servant定位器 * * @author Chenql * @memo: */ @SuppressWarnings({ "deprecation", "unused" }) public class ComponentServantLocator extends LocalObjectImpl implements ServantLocator { public static Logger logger = LoggerFactory.getLogger(ComponentServantLocator.class); /** * 全局静态变量,线程安全 */ private static AtomicLong requestCountTotal = new AtomicLong(0L); /** * 配置信息 */ private Map<String, String> config = null; /** * 是否需要访问控制标记 */ private boolean accessControl = false; /** * 允许访问的ip集合,如果启动了访问控制才生效 */ private Map<InetAddress, Boolean> permission = new ConcurrentHashMap<InetAddress, Boolean>(); ComponentServantLocator(Map<String, String> config) { this.config = config; String ac = config.get("server.access_control"); String as = config.get("server.access_servers"); accessControl = ("true".equals(ac) && null != as && !"".equals(as)); if (null != as && !"".equals(as)) { String[] items = as.trim().split(";"); for (String item : items) { try { String[] host = item.split(":"); InetAddress h = InetAddress.getByName(host[0]); Boolean flag = Boolean.valueOf(host[1]); permission.put(h, flag); } catch (Exception ex) { logger.error("无法解析访问控制项:{}", item); } } } } public void deactivate(String arg) { } public void finished(Current current, Object servant, java.lang.Object cookie) throws UserException { } /** * 定位ice服务(servant对象) */ public Object locate(Current current, LocalObjectHolder holder) throws UserException { // 计算ICE SERVER的请求数 requestCountTotal.addAndGet(1L); ConnectionI conn = (ConnectionI) current.con; // 获取当前访问的信息: 远程IP地址, 本地IP地址 Transceiver trans = conn.getTransceiver(); SocketChannel sc = (SocketChannel) trans.fd(); Socket socket = sc.socket(); InetAddress clientAddress = socket.getInetAddress(); InetAddress localAddress = socket.getLocalAddress(); if (logger.isDebugEnabled()) { logger.debug("Transceiver:" + trans); logger.debug("SocketChannel:" + sc); logger.debug("Socket:" + socket); logger.debug("localAddress:" + localAddress); logger.debug("clientAddress:" + clientAddress); } if (!checkPermission(clientAddress, localAddress)) { // 权限校验失败 throw new FwRuntimeException("组件服务器进行IP访问校验失败, 客户端[" + clientAddress + "]无权访问服务器[" + localAddress + "]"); } if (null != current.id.name) { Object target = ComponentServantProvider.getServantBean(current.id.name); return target; } return null; } /** * 访问权限校验 * * @param clientAddress * -- 客户端IP * @param localAddress * -- 本地接受连接的IP * @return -- true, 如果允许访问(权限校验通过) */ private boolean checkPermission(InetAddress clientAddress, InetAddress localAddress) { if (accessControl) { Boolean flag = permission.get(clientAddress); // 如果不存在配置项,返回true, 如果存在配置项,返回配置项的值 return (null == flag) ? true : flag.booleanValue(); } return true; } /** * * @return 返回ICE SERVER 的请求数 */ public static long getRequestCountTotal() { return requestCountTotal.get(); } }
/** * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * 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.taobao.weex.ui.component; import com.taobao.weappplus_sdk.BuildConfig; import com.taobao.weex.WXSDKInstanceTest; import com.taobao.weex.common.Constants; import com.taobao.weex.dom.TestDomObject; import com.taobao.weex.ui.SimpleComponentHolder; import com.taobao.weex.ui.view.WXEditText; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.lang.reflect.InvocationTargetException; import static com.taobao.weex.common.Constants.Name.*; import static com.taobao.weex.common.Constants.Value.*; /** * Created by sospartan on 8/3/16. */ @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = 19) @PowerMockIgnore( {"org.mockito.*", "org.robolectric.*", "android.*"}) @PrepareForTest public class EditComponentTest { static final String[] PROPS = { TEXT_ALIGN, FONT_SIZE, COLOR, TYPE, VALUE, PLACE_HOLDER, PLACEHOLDER_COLOR, AUTOFOCUS, LINES, SINGLELINE, MAX_LENGTH, ROWS}; static final Object[][] TEST_VALUES = { {null,CENTER, Constants.Name.LEFT, Constants.Name.RIGHT,"kdkdkdk"}, {null,12,Integer.MAX_VALUE,0,-2}, {"red","#000","#ffffff","rgb(12,23,45)"}, {"DKDK", TEXT, PASSWORD, TEL, EMAIL, URL, DATE, TIME, DATETIME}, {null,123,"dkdkdkdk"}, {null,123,"dkdkdkdk"}, {"red","#000","#ffffff","rgb(12,23,45)"}, {null,true,"true","false",false,"test"}, {null,34,Integer.MAX_VALUE,-1,"test"}, {null,true,"true","false",false,"test"}, {null,34,Integer.MAX_VALUE,-1,"test"}, {null,34,Integer.MAX_VALUE,-1,"test"}, }; AbstractEditComponent component; public static WXInput create() throws IllegalAccessException, InstantiationException, InvocationTargetException { return (WXInput) new SimpleComponentHolder(WXInput.class).createInstance(WXSDKInstanceTest.createInstance(), new TestDomObject(), WXDivTest.create()); } public static Textarea createTextarea() throws IllegalAccessException, InstantiationException, InvocationTargetException { return (Textarea) new SimpleComponentHolder(Textarea.class).createInstance(WXSDKInstanceTest.createInstance(), new TestDomObject(), WXDivTest.create()); } @Before public void setUp() throws Exception { component = create(); ComponentTest.create(component); } @After public void tearDown() throws Exception { ComponentTest.destory(component); } @Test public void testEvent() throws Exception { WXEditText view = component.getHostView(); view.performClick(); view.setText(""); view.requestFocus(); view.setText("hello"); view.clearFocus(); view.setText(null); } @Test public void testSetProperty() throws Exception { ComponentTest.setProperty(component,PROPS,TEST_VALUES); } @Test public void testFocus() throws Exception { component.getParent().mHost = component.getParent().initComponentHostView(component.getContext()); component.getParent().interceptFocus(); component.getHostView().clearFocus(); component.focus(); Assert.assertEquals(component.getHostView().hasFocus(), true); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.mahout.cf.taste.hadoop.item; import java.io.IOException; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.cli2.Option; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.ToolRunner; import org.apache.mahout.cf.taste.hadoop.EntityPrefWritable; import org.apache.mahout.cf.taste.hadoop.RecommendedItemsWritable; import org.apache.mahout.cf.taste.hadoop.ToItemPrefsMapper; import org.apache.mahout.common.AbstractJob; import org.apache.mahout.common.commandline.DefaultOptionCreator; import org.apache.mahout.math.VarIntWritable; import org.apache.mahout.math.VarLongWritable; import org.apache.mahout.math.VectorWritable; /** * <p>Runs a completely distributed recommender job as a series of mapreduces.</p> * * <p>Command line arguments specific to this class are:</p> * * <ol> * <li>-Dmapred.input.dir=(path): Directory containing a text file containing user IDs * for which recommendations should be computed, one per line</li> * <li>-Dmapred.output.dir=(path): output path where recommender output should go</li> * <li>--usersFile (path): file containing user IDs to recommend for (optional)</li> * <li>--numRecommendations (integer): Number of recommendations to compute per user (optional; default 10)</li> * <li>--booleanData (boolean): Treat input data as having to pref values (false)</li> * <li>--maxPrefsPerUserConsidered (integer): Maximum number of preferences considered per user in * final recommendation phase (10)</li> * <li>--maxCooccurrencesPerItemConsidered: Maximum number of cooccurrences considered per item * in count phase (100)</li> * </ol> * * <p>General command line options are documented in {@link AbstractJob}.</p> * * <p>Note that because of how Hadoop parses arguments, all "-D" arguments must appear before all other * arguments.</p> */ public final class RecommenderJob extends AbstractJob { public static final String BOOLEAN_DATA = "booleanData"; @Override public int run(String[] args) throws IOException, ClassNotFoundException, InterruptedException { addOption("numRecommendations", "n", "Number of recommendations per user", String.valueOf(AggregateAndRecommendReducer.DEFAULT_NUM_RECOMMENDATIONS)); addOption("usersFile", "u", "File of users to recommend for", null); addOption("booleanData", "b", "Treat input as without pref values", Boolean.FALSE.toString()); addOption("maxPrefsPerUserConsidered", null, "Maximum number of preferences considered per user in final recommendation phase", String.valueOf(UserVectorSplitterMapper.DEFAULT_MAX_PREFS_PER_USER_CONSIDERED)); addOption("maxCooccurrencesPerItemConsidered", null, "Maximum number of cooccurrences considered per item in count phase", String.valueOf(UserVectorToCooccurrenceMapper.DEFAULT_MAX_COOCCURRENCES_PER_ITEM_CONSIDERED)); Map<String,String> parsedArgs = parseArguments(args); if (parsedArgs == null) { return -1; } Configuration originalConf = getConf(); Path inputPath = new Path(originalConf.get("mapred.input.dir")); Path outputPath = new Path(originalConf.get("mapred.output.dir")); Path tempDirPath = new Path(parsedArgs.get("--tempDir")); int numRecommendations = Integer.parseInt(parsedArgs.get("--numRecommendations")); String usersFile = parsedArgs.get("--usersFile"); boolean booleanData = Boolean.valueOf(parsedArgs.get("--booleanData")); int maxPrefsPerUserConsidered = Integer.parseInt(parsedArgs.get("--maxPrefsPerUserConsidered")); int maxCooccurrencesPerItemConsidered = Integer.parseInt(parsedArgs.get("--maxCooccurrencesPerItemConsidered")); Path userVectorPath = new Path(tempDirPath, "userVectors"); Path itemIDIndexPath = new Path(tempDirPath, "itemIDIndex"); Path cooccurrencePath = new Path(tempDirPath, "cooccurrence"); Path prePartialMultiplyPath1 = new Path(tempDirPath, "prePartialMultiply1"); Path prePartialMultiplyPath2 = new Path(tempDirPath, "prePartialMultiply2"); Path partialMultiplyPath = new Path(tempDirPath, "partialMultiply"); AtomicInteger currentPhase = new AtomicInteger(); if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job itemIDIndex = prepareJob( inputPath, itemIDIndexPath, TextInputFormat.class, ItemIDIndexMapper.class, VarIntWritable.class, VarLongWritable.class, ItemIDIndexReducer.class, VarIntWritable.class, VarLongWritable.class, SequenceFileOutputFormat.class); itemIDIndex.setCombinerClass(ItemIDIndexReducer.class); itemIDIndex.waitForCompletion(true); } if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job toUserVector = prepareJob( inputPath, userVectorPath, TextInputFormat.class, ToItemPrefsMapper.class, VarLongWritable.class, booleanData ? VarLongWritable.class : EntityPrefWritable.class, ToUserVectorReducer.class, VarLongWritable.class, VectorWritable.class, SequenceFileOutputFormat.class); toUserVector.getConfiguration().setBoolean(BOOLEAN_DATA, booleanData); toUserVector.waitForCompletion(true); } if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job toCooccurrence = prepareJob( userVectorPath, cooccurrencePath, SequenceFileInputFormat.class, UserVectorToCooccurrenceMapper.class, VarIntWritable.class, VarIntWritable.class, UserVectorToCooccurrenceReducer.class, VarIntWritable.class, VectorWritable.class, SequenceFileOutputFormat.class); setIOSort(toCooccurrence); toCooccurrence.getConfiguration().setInt(UserVectorToCooccurrenceMapper.MAX_COOCCURRENCES_PER_ITEM_CONSIDERED, maxCooccurrencesPerItemConsidered); toCooccurrence.waitForCompletion(true); } if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job prePartialMultiply1 = prepareJob( cooccurrencePath, prePartialMultiplyPath1, SequenceFileInputFormat.class, CooccurrenceColumnWrapperMapper.class, VarIntWritable.class, VectorOrPrefWritable.class, Reducer.class, VarIntWritable.class, VectorOrPrefWritable.class, SequenceFileOutputFormat.class); prePartialMultiply1.waitForCompletion(true); Job prePartialMultiply2 = prepareJob( userVectorPath, prePartialMultiplyPath2, SequenceFileInputFormat.class, UserVectorSplitterMapper.class, VarIntWritable.class, VectorOrPrefWritable.class, Reducer.class, VarIntWritable.class, VectorOrPrefWritable.class, SequenceFileOutputFormat.class); if (usersFile != null) { prePartialMultiply2.getConfiguration().set(UserVectorSplitterMapper.USERS_FILE, usersFile); } prePartialMultiply2.getConfiguration().setInt(UserVectorSplitterMapper.MAX_PREFS_PER_USER_CONSIDERED, maxPrefsPerUserConsidered); prePartialMultiply2.waitForCompletion(true); Job partialMultiply = prepareJob( new Path(prePartialMultiplyPath1 + "," + prePartialMultiplyPath2), partialMultiplyPath, SequenceFileInputFormat.class, Mapper.class, VarIntWritable.class, VectorOrPrefWritable.class, ToVectorAndPrefReducer.class, VarIntWritable.class, VectorAndPrefsWritable.class, SequenceFileOutputFormat.class); partialMultiply.waitForCompletion(true); } if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job aggregateAndRecommend = prepareJob( partialMultiplyPath, outputPath, SequenceFileInputFormat.class, PartialMultiplyMapper.class, VarLongWritable.class, VectorWritable.class, AggregateAndRecommendReducer.class, VarLongWritable.class, RecommendedItemsWritable.class, TextOutputFormat.class); Configuration jobConf = aggregateAndRecommend.getConfiguration(); setIOSort(aggregateAndRecommend); aggregateAndRecommend.setCombinerClass(AggregateCombiner.class); jobConf.set(AggregateAndRecommendReducer.ITEMID_INDEX_PATH, itemIDIndexPath.toString()); jobConf.setInt(AggregateAndRecommendReducer.NUM_RECOMMENDATIONS, numRecommendations); aggregateAndRecommend.waitForCompletion(true); } return 0; } private static void setIOSort(JobContext job) { Configuration conf = job.getConfiguration(); conf.setInt("io.sort.factor", 100); int assumedHeapSize = 512; String javaOpts = conf.get("mapred.child.java.opts"); if (javaOpts != null) { Matcher m = Pattern.compile("-Xmx([0-9]+)([mMgG])").matcher(javaOpts); if (m.find()) { assumedHeapSize = Integer.parseInt(m.group(1)); String megabyteOrGigabyte = m.group(2); if ("g".equalsIgnoreCase(megabyteOrGigabyte)) { assumedHeapSize *= 1024; } } } conf.setInt("io.sort.mb", assumedHeapSize / 2); // For some reason the Merger doesn't report status for a long time; increase // timeout when running these jobs conf.setInt("mapred.task.timeout", 60 * 60 * 1000); } public static void main(String[] args) throws Exception { ToolRunner.run(new Configuration(), new RecommenderJob(), args); } }
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.jboss.cdi.tck.tests.context.dependent.ejb; import java.io.Serializable; import jakarta.annotation.PreDestroy; public class Horse implements Serializable { /** * */ private static final long serialVersionUID = 1417245695143239294L; public static boolean destroyed; @PreDestroy public void preDestroy() { destroyed = true; } }
package tw.edu.au.csie.ucan.beebit.seco; public class User { private String uid; public User(String uid) { this.uid = uid; } public String getUid() { return uid;} }
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*; /** * @author LEO D PEN * @date 2021/2/12 * @desc */ @DisplayName("IgnoreGetSetTest") class IgnoreGetSetTest { private static IgnoreGetSet igs; private static Set<Method> methods; @BeforeAll public static void init() { igs = new IgnoreGetSet("牛", 1, new Student(), new ArrayList<Boolean>()); methods = Arrays.stream(igs.getClass().getMethods()) .collect(Collectors.toSet()); } @Test public void 大_test_ignore_get() { int cnt = 0; for (Method m : methods) { if (m.getName().equals("大")) { assertEquals(igs.getClass(), m.getReturnType()); cnt++; } } assertEquals(1, cnt); } @Test public void 牛_test_ignore_set() { int cnt = 0; for (Method m : methods) { if (m.getName().equals("牛")) { assertEquals(String.class, m.getReturnType()); cnt++; } } assertEquals(1, cnt); } @Test public void 年_test_ignore() { int cnt = 0; for (Method m : methods) { if (m.getName().equals("年")) { cnt++; } } assertEquals(0, cnt); } }
/* * Copyright (C) 2008 FoxLabs * * 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.foxlabs.etk.function.base; import java.text.SimpleDateFormat; import org.foxlabs.etk.Environment; import org.foxlabs.etk.annotation.FxNames; import org.foxlabs.etk.function.Function; @FxNames("DATEFORMAT") public class DateFormat extends Function { public DateFormat(String name, String namespace) { super(name, namespace, java.util.Date.class, String.class); } public boolean isDetermined() { return true; } public Object evaluate(Environment context, Object... arguments) throws Exception { java.util.Date date = safeArgumentOf(arguments, 0); String format = safeArgumentOf(arguments, 1); return (new SimpleDateFormat(format)).format(date); } }
package com.planet_ink.coffee_mud.Abilities.Skills; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2003-2021 Bo Zimmerman 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. */ public class Skill_Cage extends StdSkill { @Override public String ID() { return "Skill_Cage"; } private final static String localizedName = CMLib.lang().L("Cage"); @Override public String name() { return localizedName; } @Override public String displayText() { return ""; } @Override protected int canAffectCode() { return 0; } @Override protected int canTargetCode() { return CAN_MOBS; } @Override public int abstractQuality() { return Ability.QUALITY_MALICIOUS; } private static final String[] triggerStrings =I(new String[] {"CAGE"}); @Override public String[] triggerStrings() { return triggerStrings; } @Override public int classificationCode() { return Ability.ACODE_SKILL|Ability.DOMAIN_ANIMALAFFINITY; } @Override public int usageType() { return USAGE_MOVEMENT|USAGE_MANA; } @Override public int castingQuality(final MOB mob, final Physical target) { if((mob!=null)&&(target!=null)&&(mob.isInCombat())) return Ability.QUALITY_INDIFFERENT; return super.castingQuality(mob,target); } @Override public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel) { Item cage=null; if(mob.location()!=null) { for(int i=0;i<mob.location().numItems();i++) { final Item I=mob.location().getItem(i); if((I!=null) &&(I instanceof Container) &&((((Container)I).containTypes()&Container.CONTAIN_CAGED)==Container.CONTAIN_CAGED)) { cage=I; break; } } if(commands.size()>0) { final String last=commands.get(commands.size()-1); final Item I=mob.location().findItem(null,last); if((I!=null) &&(I instanceof Container) &&((((Container)I).containTypes()&Container.CONTAIN_CAGED)==Container.CONTAIN_CAGED)) { cage=I; commands.remove(last); } } } final MOB target=getTarget(mob,commands,givenTarget); if(target==null) return false; if((!auto)&&(!(CMSecurity.isAllowed(mob,mob.location(),CMSecurity.SecFlag.ORDER)||target.willFollowOrdersOf(mob)))) { boolean ok=false; if((target.isMonster()) &&(CMLib.flags().isAnimalIntelligence(target))) { if(CMLib.flags().isSleeping(target) ||(!CMLib.flags().canMove(target)) ||((target.amFollowing()==mob)) ||(CMLib.flags().isBoundOrHeld(target))) ok=true; } if(!ok) { mob.tell(L("@x1 won't seem to let you.",target.name(mob))); return false; } if(cage==null) { mob.tell(L("Cage @x1 where?",target.name(mob))); return false; } if((mob.isInCombat())&&(mob.getVictim()!=target)) { mob.tell(L("Not while you are fighting!")); return false; } } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); final CagedAnimal caged=(CagedAnimal)CMClass.getItem("GenCaged"); if((success)&&(caged.cageMe(target))) { final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_JUSTICE,null); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); if((cage!=null)&&(cage.owner()!=null)) { if(cage.owner() instanceof MOB) ((MOB)cage.owner()).addItem(caged); else if(cage.owner() instanceof Room) ((Room)cage.owner()).addItem(caged); } else mob.addItem(caged); final CMMsg putMsg=CMClass.getMsg(mob,cage,caged,CMMsg.MSG_PUT,L("<S-NAME> cage(s) <O-NAME> in <T-NAME>.")); if(mob.location().okMessage(mob,putMsg)) { mob.location().send(mob,putMsg); target.killMeDead(false); } else ((Item)caged).destroy(); mob.location().recoverRoomStats(); } } else return maliciousFizzle(mob,target,L("<S-NAME> attempt(s) to cage <T-NAME> and fail(s).")); // return whether it worked return success; } }
package com.communote.server.web.fe.portal.user.profile.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import com.communote.common.util.ParameterHelper; import com.communote.server.api.ServiceLocator; import com.communote.server.api.core.common.NotFoundException; import com.communote.server.api.core.security.AuthorizationException; import com.communote.server.core.messaging.NotificationDefinition; import com.communote.server.core.messaging.NotificationManagement; import com.communote.server.core.messaging.NotificationManagementConstants; import com.communote.server.core.messaging.NotificationScheduleTypes; import com.communote.server.core.messaging.NotificationService; import com.communote.server.core.messaging.vo.MessagerConnectorConfigTO; import com.communote.server.core.security.SecurityHelper; import com.communote.server.core.user.UserProfileManagement; import com.communote.server.core.user.UserProfileManagementException; import com.communote.server.model.messaging.MessagerConnectorType; import com.communote.server.web.commons.FormAction; import com.communote.server.web.commons.MessageHelper; import com.communote.server.web.commons.controller.BaseFormController; import com.communote.server.web.commons.helper.ControllerHelper; import com.communote.server.web.fe.portal.user.profile.forms.UserProfileNotificationsForm; /** * Controller for modifying the notification configuration of a user. * * @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a> */ public class UserProfileNotificationsController extends BaseFormController { private static final String NOTIFICATION_SCHEDULE_PREFIX = "notificationSchedule_"; /** Logger. */ private static final Logger LOGGER = LoggerFactory .getLogger(UserProfileNotificationsController.class); /** * * @param userId * the ID of the user */ private void doRequestFriendShip(Long userId) { ServiceLocator.findService(NotificationManagement.class) .enableUser(userId, MessagerConnectorType.XMPP.toString()); } /** * * @param request * the servlet request * @param response * the servlet response * @param form * the form object * @param errors * object to bind errors */ private void doUpdateNotifications(HttpServletRequest request, HttpServletResponse response, UserProfileNotificationsForm form, BindException errors) { if (form.isXmppFail()) { // force an XMPP connector if the XMPP fail is set form.setXmpp(true); } Map<MessagerConnectorType, MessagerConnectorConfigTO> connectorConfigs; connectorConfigs = new HashMap<MessagerConnectorType, MessagerConnectorConfigTO>(); if (form.isXmpp()) { MessagerConnectorConfigTO configTO = new MessagerConnectorConfigTO( MessagerConnectorType.XMPP, NotificationManagementConstants.XMPP_PRIORITY); configTO.getProperties().put(NotificationManagementConstants.FALLBACK_ON_FAIL_LITERAL, String.valueOf(form.isXmppFail())); connectorConfigs.put(MessagerConnectorType.XMPP, configTO); } if (form.isMail()) { MessagerConnectorConfigTO configTO = new MessagerConnectorConfigTO( MessagerConnectorType.MAIL, NotificationManagementConstants.MAIL_PRIORITY); connectorConfigs.put(MessagerConnectorType.MAIL, configTO); } try { ServiceLocator.findService(UserProfileManagement.class).updateNotificationConfig( connectorConfigs); } catch (UserProfileManagementException e) { LOGGER.error("Error changing notification config: " + e.getMessage(), e); errors.reject("user.profile.notification.change.failed"); ControllerHelper.setApplicationFailure(response); } } /** * {@inheritDoc} */ @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { Map<NotificationDefinition, NotificationScheduleTypes> schedules = ServiceLocator .findService(NotificationService.class) .getUserNotificationSchedules(SecurityHelper.getCurrentUserId()); request.setAttribute("userNotificationSchedules", schedules); UserProfileNotificationsForm form = new UserProfileNotificationsForm(); initNotification(request, form); return form; } /** * {@inheritDoc} */ @Override protected ModelAndView handleOnSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { UserProfileNotificationsForm form = (UserProfileNotificationsForm) command; Long userId = SecurityHelper.getCurrentUserId(); if (userId != null) { if (form.getAction().equals(FormAction.UPDATE_USER_PROFILE)) { doUpdateNotifications(request, response, form, errors); } else if (form.getAction().equals(FormAction.XMPP_REQUEST_FRIENDSHIP)) { doRequestFriendShip(userId); } saveNotificationSchedules(userId, request); } if (errors.hasErrors()) { return showForm(request, errors, getFormView()); } else { MessageHelper.saveMessageFromKey(request, "user.profile.notification.save.success"); return new ModelAndView(getSuccessView(), getCommandName(), command); } } /** * Initializes the notification. * * @param request * The HttpServletRequest object * @param form * The form object */ private void initNotification(HttpServletRequest request, UserProfileNotificationsForm form) { List<MessagerConnectorConfigTO> connectorConfigs = ServiceLocator.findService( UserProfileManagement.class).getMessagerConnectorConfigs(); if (connectorConfigs != null) { for (MessagerConnectorConfigTO config : connectorConfigs) { if (config.getType().equals(MessagerConnectorType.MAIL)) { form.setMail(true); } else if (config.getType().equals(MessagerConnectorType.XMPP)) { form.setXmpp(true); String fallback = config.getProperties().get( NotificationManagementConstants.FALLBACK_ON_FAIL_LITERAL); if ("true".equals(fallback)) { form.setXmppFail(true); } } } } } /** * {@inheritDoc} */ @Override protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { if (errors.hasErrors()) { ControllerHelper.setApplicationFailure(response); } return super.processFormSubmission(request, response, command, errors); } /** * Method to save users settings for notification definitions. * * @param userId * The users id. * @param request * The request. */ private void saveNotificationSchedules(Long userId, HttpServletRequest request) { NotificationService notificationDefinitionService = ServiceLocator .findService(NotificationService.class); Map<String, String[]> parameters = request.getParameterMap(); Map<NotificationDefinition, NotificationScheduleTypes> mappings = new HashMap<NotificationDefinition, NotificationScheduleTypes>(); for (NotificationDefinition definition : notificationDefinitionService .getRegisteredDefinitions()) { boolean definitionEnabled = ParameterHelper.getParameterAsBoolean(parameters, NOTIFICATION_SCHEDULE_PREFIX + definition.getId(), false); mappings.put(definition, definitionEnabled ? NotificationScheduleTypes.IMMEDIATE : NotificationScheduleTypes.NEVER); } try { notificationDefinitionService.saveUserNotificationSchedules(userId, mappings); Map<NotificationDefinition, NotificationScheduleTypes> schedules = ServiceLocator .findService(NotificationService.class) .getUserNotificationSchedules(SecurityHelper.getCurrentUserId()); request.setAttribute("userNotificationSchedules", schedules); } catch (NotFoundException e) { // Should never occur. MessageHelper .saveErrorMessageFromKey(request, "error.message.code.unknown.description"); LOGGER.error("Error updating notification definitions", e); } catch (AuthorizationException e) { // Should never occur. MessageHelper .saveErrorMessageFromKey(request, "error.message.code.unknown.description"); LOGGER.error("Error updating notification definitions", e); } } }
package com.ke.css.cimp.fwb.fwb11; /* ----------------------------------------------------------------------------- * Rule_Hid_AWB_Column_Identifier_C.java * ----------------------------------------------------------------------------- * * Producer : com.parse2.aparse.Parser 2.5 * Produced : Tue Mar 06 10:36:50 KST 2018 * * ----------------------------------------------------------------------------- */ import java.util.ArrayList; final public class Rule_Hid_AWB_Column_Identifier_C extends Rule { public Rule_Hid_AWB_Column_Identifier_C(String spelling, ArrayList<Rule> rules) { super(spelling, rules); } public Object accept(Visitor visitor) { return visitor.visit(this); } public static Rule_Hid_AWB_Column_Identifier_C parse(ParserContext context) { context.push("Hid_AWB_Column_Identifier_C"); boolean parsed = true; int s0 = context.index; ParserAlternative a0 = new ParserAlternative(s0); ArrayList<ParserAlternative> as1 = new ArrayList<ParserAlternative>(); parsed = false; { int s1 = context.index; ParserAlternative a1 = new ParserAlternative(s1); parsed = true; if (parsed) { boolean f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { Rule rule = Terminal_StringValue.parse(context, "C"); if ((f1 = rule != null)) { a1.add(rule, context.index); c1++; } } parsed = c1 == 1; } if (parsed) { as1.add(a1); } context.index = s1; } ParserAlternative b = ParserAlternative.getBest(as1); parsed = b != null; if (parsed) { a0.add(b.rules, b.end); context.index = b.end; } Rule rule = null; if (parsed) { rule = new Rule_Hid_AWB_Column_Identifier_C(context.text.substring(a0.start, a0.end), a0.rules); } else { context.index = s0; } context.pop("Hid_AWB_Column_Identifier_C", parsed); return (Rule_Hid_AWB_Column_Identifier_C)rule; } } /* ----------------------------------------------------------------------------- * eof * ----------------------------------------------------------------------------- */
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.fontbox.cff; /** * This is specialized CFFEncoding. It's used if the EncodingId of a font is set to 0. * * @author Villu Ruusmann */ public final class CFFStandardEncoding extends CFFEncoding { private static final int CHAR_CODE = 0; private static final int CHAR_SID = 1; /** * Table of character codes and their corresponding sid. */ private static final int[][] CFF_STANDARD_ENCODING_TABLE = { {0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}, {7, 0}, {8, 0}, {9, 0}, {10, 0}, {11, 0}, {12, 0}, {13, 0}, {14, 0}, {15, 0}, {16, 0}, {17, 0}, {18, 0}, {19, 0}, {20, 0}, {21, 0}, {22, 0}, {23, 0}, {24, 0}, {25, 0}, {26, 0}, {27, 0}, {28, 0}, {29, 0}, {30, 0}, {31, 0}, {32, 1}, {33, 2}, {34, 3}, {35, 4}, {36, 5}, {37, 6}, {38, 7}, {39, 8}, {40, 9}, {41, 10}, {42, 11}, {43, 12}, {44, 13}, {45, 14}, {46, 15}, {47, 16}, {48, 17}, {49, 18}, {50, 19}, {51, 20}, {52, 21}, {53, 22}, {54, 23}, {55, 24}, {56, 25}, {57, 26}, {58, 27}, {59, 28}, {60, 29}, {61, 30}, {62, 31}, {63, 32}, {64, 33}, {65, 34}, {66, 35}, {67, 36}, {68, 37}, {69, 38}, {70, 39}, {71, 40}, {72, 41}, {73, 42}, {74, 43}, {75, 44}, {76, 45}, {77, 46}, {78, 47}, {79, 48}, {80, 49}, {81, 50}, {82, 51}, {83, 52}, {84, 53}, {85, 54}, {86, 55}, {87, 56}, {88, 57}, {89, 58}, {90, 59}, {91, 60}, {92, 61}, {93, 62}, {94, 63}, {95, 64}, {96, 65}, {97, 66}, {98, 67}, {99, 68}, {100, 69}, {101, 70}, {102, 71}, {103, 72}, {104, 73}, {105, 74}, {106, 75}, {107, 76}, {108, 77}, {109, 78}, {110, 79}, {111, 80}, {112, 81}, {113, 82}, {114, 83}, {115, 84}, {116, 85}, {117, 86}, {118, 87}, {119, 88}, {120, 89}, {121, 90}, {122, 91}, {123, 92}, {124, 93}, {125, 94}, {126, 95}, {127, 0}, {128, 0}, {129, 0}, {130, 0}, {131, 0}, {132, 0}, {133, 0}, {134, 0}, {135, 0}, {136, 0}, {137, 0}, {138, 0}, {139, 0}, {140, 0}, {141, 0}, {142, 0}, {143, 0}, {144, 0}, {145, 0}, {146, 0}, {147, 0}, {148, 0}, {149, 0}, {150, 0}, {151, 0}, {152, 0}, {153, 0}, {154, 0}, {155, 0}, {156, 0}, {157, 0}, {158, 0}, {159, 0}, {160, 0}, {161, 96}, {162, 97}, {163, 98}, {164, 99}, {165, 100}, {166, 101}, {167, 102}, {168, 103}, {169, 104}, {170, 105}, {171, 106}, {172, 107}, {173, 108}, {174, 109}, {175, 110}, {176, 0}, {177, 111}, {178, 112}, {179, 113}, {180, 114}, {181, 0}, {182, 115}, {183, 116}, {184, 117}, {185, 118}, {186, 119}, {187, 120}, {188, 121}, {189, 122}, {190, 0}, {191, 123}, {192, 0}, {193, 124}, {194, 125}, {195, 126}, {196, 127}, {197, 128}, {198, 129}, {199, 130}, {200, 131}, {201, 0}, {202, 132}, {203, 133}, {204, 0}, {205, 134}, {206, 135}, {207, 136}, {208, 137}, {209, 0}, {210, 0}, {211, 0}, {212, 0}, {213, 0}, {214, 0}, {215, 0}, {216, 0}, {217, 0}, {218, 0}, {219, 0}, {220, 0}, {221, 0}, {222, 0}, {223, 0}, {224, 0}, {225, 138}, {226, 0}, {227, 139}, {228, 0}, {229, 0}, {230, 0}, {231, 0}, {232, 140}, {233, 141}, {234, 142}, {235, 143}, {236, 0}, {237, 0}, {238, 0}, {239, 0}, {240, 0}, {241, 144}, {242, 0}, {243, 0}, {244, 0}, {245, 145}, {246, 0}, {247, 0}, {248, 146}, {249, 147}, {250, 148}, {251, 149}, {252, 0}, {253, 0}, {254, 0}, {255, 0} }; private CFFStandardEncoding() { for (int[] encodingEntry : CFF_STANDARD_ENCODING_TABLE) { add(encodingEntry[CHAR_CODE], encodingEntry[CHAR_SID]); } } /** * Returns an instance of the CFFStandardEncoding class. * @return an instance of CFFStandardEncoding */ public static CFFStandardEncoding getInstance() { return CFFStandardEncoding.INSTANCE; } private static final CFFStandardEncoding INSTANCE = new CFFStandardEncoding(); }
package estruturas; /* REGISTRO HASH EXTENSIVEL Esta interface apresenta os métodos que os objetos a serem incluídos na tabela hash extensível devem conter. Implementado pelo Prof. Marcos Kutova v1.1 - 2021 */ import java.io.IOException; public interface RegistroHashExtensivel<T> { public int hashCode(); // chave numérica para ser usada no diretório public short size(); // tamanho FIXO do registro public byte[] toByteArray() throws IOException; // representação do elemento em um vetor de bytes public void fromByteArray(byte[] ba) throws IOException; // vetor de bytes a ser usado na construção do elemento }
package com.almasb.fxglgames.spaceinvaders.level; import com.almasb.fxgl.app.FXGL; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.entity.GameWorld; import com.almasb.fxgl.entity.SpawnData; import com.almasb.fxgl.entity.component.Component; import com.almasb.fxgl.extra.entity.components.CircularMovementComponent; import com.almasb.fxgl.time.LocalTimer; import com.almasb.fxglgames.spaceinvaders.Config; import javafx.util.Duration; import static com.almasb.fxgl.app.DSLKt.play; import static com.almasb.fxgl.app.DSLKt.runOnce; /** * @author Almas Baimagambetov (almaslvl@gmail.com) */ public class BossLevel1 extends BossLevel { private Entity boss; @Override public void playInCutscene(Runnable onFinished) { boss = spawnBoss(Config.WIDTH * 2 / 3, Config.HEIGHT / 3, 50, "boss1.png"); showStoryPane(); updateAlienStoryText("I will end you!"); runOnce(() -> { hideStoryPane(); onFinished.run(); }, Duration.seconds(4)); } @Override public void init() { boss.addComponent(new CircularMovementComponent(2, 200)); boss.addComponent(new Level1BossComponent()); } private static class Level1BossComponent extends Component { private LocalTimer attackTimer = FXGL.newLocalTimer(); private Duration nextAttack = Duration.seconds(1); @Override public void onUpdate(double tpf) { if (attackTimer.elapsed(nextAttack)) { shoot(); nextAttack = Duration.seconds(1); attackTimer.capture(); } } private void shoot() { for (int i = 0; i < 6; i++) { GameWorld world = getEntity().getWorld(); Entity bullet = world.spawn("Bullet", new SpawnData(0, 0).put("owner", getEntity())); bullet.translateX(20 * (i-3)); } play("shoot" + (int)(Math.random() * 4 + 1) + ".wav"); } } }
package com.airbnb.lottie.parser; import android.graphics.PointF; import android.util.JsonReader; import android.util.JsonToken; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatablePathValue; import com.airbnb.lottie.model.animatable.AnimatableScaleValue; import com.airbnb.lottie.model.animatable.AnimatableSplitDimensionPathValue; import com.airbnb.lottie.model.animatable.AnimatableTransform; import com.airbnb.lottie.model.animatable.AnimatableValue; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; public class AnimatableTransformParser { private AnimatableTransformParser() { } public static AnimatableTransform parse( JsonReader reader, LottieComposition composition) throws IOException { AnimatablePathValue anchorPoint = null; AnimatableValue<PointF, PointF> position = null; AnimatableScaleValue scale = null; AnimatableFloatValue rotation = null; AnimatableIntegerValue opacity = null; AnimatableFloatValue startOpacity = null; AnimatableFloatValue endOpacity = null; AnimatableFloatValue skew = null; AnimatableFloatValue skewAngle = null; boolean isObject = reader.peek() == JsonToken.BEGIN_OBJECT; if (isObject) { reader.beginObject(); } while (reader.hasNext()) { switch (reader.nextName()) { case "a": reader.beginObject(); while (reader.hasNext()) { if (reader.nextName().equals("k")) { anchorPoint = AnimatablePathValueParser.parse(reader, composition); } else { reader.skipValue(); } } reader.endObject(); break; case "p": position = AnimatablePathValueParser.parseSplitPath(reader, composition); break; case "s": scale = AnimatableValueParser.parseScale(reader, composition); break; case "rz": composition.addWarning("Lottie doesn't support 3D layers."); case "r": /** * Sometimes split path rotation gets exported like: * "rz": { * "a": 1, * "k": [ * {} * ] * }, * which doesn't parse to a real keyframe. */ rotation = AnimatableValueParser.parseFloat(reader, composition, false); if (rotation.getKeyframes().isEmpty()) { rotation.getKeyframes().add(new Keyframe(composition, 0f, 0f, null, 0f, composition.getEndFrame())); } else if (rotation.getKeyframes().get(0).startValue == null) { rotation.getKeyframes().set(0, new Keyframe(composition, 0f, 0f, null, 0f, composition.getEndFrame())); } break; case "o": opacity = AnimatableValueParser.parseInteger(reader, composition); break; case "so": startOpacity = AnimatableValueParser.parseFloat(reader, composition, false); break; case "eo": endOpacity = AnimatableValueParser.parseFloat(reader, composition, false); break; case "sk": skew = AnimatableValueParser.parseFloat(reader, composition, false); break; case "sa": skewAngle = AnimatableValueParser.parseFloat(reader, composition, false); break; default: reader.skipValue(); } } if (isObject) { reader.endObject(); } if (isAnchorPointIdentity(anchorPoint)) { anchorPoint = null; } if (isPositionIdentity(position)) { position = null; } if (isRotationIdentity(rotation)) { rotation = null; } if (isScaleIdentity(scale)) { scale = null; } if (isSkewIdentity(skew)) { skew = null; } if (isSkewAngleIdentity(skewAngle)) { skewAngle = null; } return new AnimatableTransform(anchorPoint, position, scale, rotation, opacity, startOpacity, endOpacity, skew, skewAngle); } private static boolean isAnchorPointIdentity(AnimatablePathValue anchorPoint) { return anchorPoint == null || (anchorPoint.isStatic() && anchorPoint.getKeyframes().get(0).startValue.equals(0f, 0f)); } private static boolean isPositionIdentity(AnimatableValue<PointF, PointF> position) { return position == null || ( !(position instanceof AnimatableSplitDimensionPathValue) && position.isStatic() && position.getKeyframes().get(0).startValue.equals(0f, 0f)); } private static boolean isRotationIdentity(AnimatableFloatValue rotation) { return rotation == null || (rotation.isStatic() && rotation.getKeyframes().get(0).startValue == 0f); } private static boolean isScaleIdentity(AnimatableScaleValue scale) { return scale == null || (scale.isStatic() && scale.getKeyframes().get(0).startValue.equals(1f, 1f)); } private static boolean isSkewIdentity(AnimatableFloatValue skew) { return skew == null || (skew.isStatic() && skew.getKeyframes().get(0).startValue == 0f); } private static boolean isSkewAngleIdentity(AnimatableFloatValue skewAngle) { return skewAngle == null || (skewAngle.isStatic() && skewAngle.getKeyframes().get(0).startValue == 0f); } }
/* * Copyright (c) 2020 ProDev+ (Pascal Gerner). * * 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.simplelib; import android.content.Context; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; import android.os.Handler; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import com.simplelib.interfaces.InitializeAdapter; import com.simplelib.interfaces.OnEvent; import com.simplelib.interfaces.UpdateAdapter; import com.simplelib.interfaces.VisibilityAdapter; import java.util.concurrent.atomic.AtomicBoolean; public abstract class SimpleFragment extends Fragment implements OnEvent, InitializeAdapter, UpdateAdapter, VisibilityAdapter { // States private AtomicBoolean stateInitialized; private AtomicBoolean stateNeedsUpdate; private AtomicBoolean stateVisibility; // General private int id; private View contentView; protected boolean overrideActivityDefaults; private String title, subtitle; private boolean backButton; private int menuId; private Menu menu; public boolean willResumeOnlyCurrentFragment = true; private AtomicBoolean resumed; public SimpleFragment(int id) { this.id = id; resetToolbar(); setInitialized(false); setNeedsUpdate(true); setDefVisibility(false); } @NonNull public final AtomicBoolean getInitializedState() { if (stateInitialized == null) stateInitialized = new AtomicBoolean(false); return stateInitialized; } @NonNull public final AtomicBoolean getNeedsUpdateState() { if (stateNeedsUpdate == null) stateNeedsUpdate = new AtomicBoolean(false); return stateNeedsUpdate; } @NonNull public final AtomicBoolean getVisibleState() { if (stateVisibility == null) stateVisibility = new AtomicBoolean(false); return stateVisibility; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!willResumeOnlyCurrentFragment) setInitialized(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(id, container, false); this.contentView = view; onRestoreInstanceState(savedInstanceState); if (overrideActivityDefaults || getActivity() == null) resetToolbar(); create(view, savedInstanceState); if (!willResumeOnlyCurrentFragment) { setInitialized(true); update(false); } return view; } public void onRestoreInstanceState(@Nullable Bundle savedInstanceState) { if (savedInstanceState == null) return; overrideActivityDefaults = savedInstanceState.getBoolean("overrideActivityDefaults", overrideActivityDefaults); title = savedInstanceState.getString("title", title); subtitle = savedInstanceState.getString("subtitle", subtitle); backButton = savedInstanceState.getBoolean("backButton", backButton); menuId = savedInstanceState.getInt("menuId", menuId); willResumeOnlyCurrentFragment = savedInstanceState.getBoolean("willResumeOnlyCurrentFragment", willResumeOnlyCurrentFragment); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); if (outState == null) return; outState.putBoolean("overrideActivityDefaults", overrideActivityDefaults); outState.putString("title", title); outState.putString("subtitle", subtitle); outState.putBoolean("backButton", backButton); outState.putInt("menuId", menuId); outState.putBoolean("willResumeOnlyCurrentFragment", willResumeOnlyCurrentFragment); } public View getContentView() { return contentView; } @SuppressWarnings("unchecked") public <T extends View> T findViewById(int id) { try { return (T) getContentView().findViewById(id); } catch (Exception e) { } return null; } public abstract void create(View view, Bundle savedInstanceState); @Override public void onUpdate() { updateVisibility(); } @Override public void onVisibilitySet(boolean visible) { try { if (visible && overrideActivityDefaults) { if (menuId < 0) disableOptionsMenu(); else enableOptionsMenu(menuId); if (title != null) setTitle(title); if (subtitle != null) setSubtitle(subtitle); setBackButtonEnabled(backButton); } } catch (Exception e) { } } @Override public void onVisibilityChanged(boolean visible) { } public void setToolbar(int toolbarId) { try { View view = findViewById(toolbarId); if (view instanceof Toolbar) setToolbar((Toolbar) view); } catch (Exception e) { } } public void setToolbar(Toolbar toolbar) { try { if (getActivity() instanceof SimpleActivity) { SimpleActivity activity = (SimpleActivity) getActivity(); activity.setSupportActionBar(toolbar); } } catch (Exception e) { } } public ActionBar getToolbar() { try { if (getActivity() instanceof SimpleActivity) { SimpleActivity activity = (SimpleActivity) getActivity(); return activity.getSupportActionBar(); } } catch (Exception e) { } return null; } public String getDefaultName() { return SimpleActivity.getApplicationName(getActivity()); } public void resetToolbar() { setBackButtonEnabled(false); disableOptionsMenu(); resetTitle(); resetSubtitle(); } public void resetTitle() { String title = getDefaultName(); setTitle(title); } public void resetSubtitle() { String subtitle = ""; setSubtitle(subtitle); } public String getTitle() { if (title == null) resetTitle(); return title; } public void setTitle(String title) { try { if (title == null) title = ""; this.title = title; if (getVisibility() && getActivity() instanceof SimpleActivity) { SimpleActivity activity = (SimpleActivity) getActivity(); activity.setTitle(title); } } catch (Exception e) { } } public String getSubtitle() { if (subtitle == null) resetSubtitle(); return subtitle; } public void setSubtitle(String subtitle) { try { if (subtitle == null) subtitle = ""; this.subtitle = subtitle; if (getVisibility() && getActivity() instanceof SimpleActivity) { SimpleActivity activity = (SimpleActivity) getActivity(); activity.setSubtitle(subtitle); } } catch (Exception e) { } } public boolean isBackButtonEnabled() { return backButton; } public void setBackButtonEnabled(boolean enabled) { try { this.backButton = enabled; if (getVisibility() && getActivity() instanceof SimpleActivity) { SimpleActivity activity = (SimpleActivity) getActivity(); activity.setBackButtonEnabled(enabled); } } catch (Exception e) { } } public void callActivity(int code, Object... args) { if (args == null) args = new Object[0]; try { if (getActivity() instanceof SimpleActivity) { SimpleActivity activity = (SimpleActivity) getActivity(); activity.onReceiveCall(code, args); } } catch (Exception e) { } } @SuppressWarnings("deprecation") @Deprecated @Override public boolean getUserVisibleHint() { return super.getUserVisibleHint(); } @SuppressWarnings("deprecation") @Deprecated @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); setVisibility(isVisibleToUser, false); } @Override public void onStart() { super.onStart(); if (willResumeOnlyCurrentFragment) { if (this.resumed != null) { this.resumed.set(true); this.resumed = null; } final AtomicBoolean resumed = new AtomicBoolean(false); this.resumed = resumed; new Handler().post(new Runnable() { @Override public void run() { if (resumed.get()) return; setVisibility(false, false); setInitialized(true); update(false); } }); } } @Override public void onResume() { super.onResume(); if (willResumeOnlyCurrentFragment) { if (this.resumed != null) { this.resumed.set(true); this.resumed = null; } setVisibility(true, false); setInitialized(true); update(false); } } public void enableOptionsMenu(int menu) { if (getVisibility() && getActivity() != null) this.setHasOptionsMenu(true); this.menuId = menu; } public void disableOptionsMenu() { if (getVisibility() && getActivity() != null) this.setHasOptionsMenu(false); this.menuId = -1; } public Menu getMenu() { return menu; } @Override public void onPrepareOptionsMenu(Menu menu) { this.menu = menu; super.onPrepareOptionsMenu(menu); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { try { if (menuId >= 0) inflater.inflate(menuId, menu); } catch (Exception e) { } this.menu = menu; super.onCreateOptionsMenu(menu, inflater); } @Override public void onStop() { super.onStop(); hideKeyboard(); } public void hideKeyboard() { try { InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), 0); } catch (Exception e) { } } }
/* * Copyright (C) 2014 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.example.android.sunshine.app.data; import android.annotation.TargetApi; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import java.sql.SQLClientInfoException; public class WeatherProvider extends ContentProvider { // The URI Matcher used by this content provider. private static final UriMatcher sUriMatcher = buildUriMatcher(); private WeatherDbHelper mOpenHelper; static final int WEATHER = 100; static final int WEATHER_WITH_LOCATION = 101; static final int WEATHER_WITH_LOCATION_AND_DATE = 102; static final int LOCATION = 300; private static final SQLiteQueryBuilder sWeatherByLocationSettingQueryBuilder; static{ sWeatherByLocationSettingQueryBuilder = new SQLiteQueryBuilder(); //This is an inner join which looks like //weather INNER JOIN location ON weather.location_id = location._id sWeatherByLocationSettingQueryBuilder.setTables( WeatherContract.WeatherEntry.TABLE_NAME + " INNER JOIN " + WeatherContract.LocationEntry.TABLE_NAME + " ON " + WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry.COLUMN_LOC_KEY + " = " + WeatherContract.LocationEntry.TABLE_NAME + "." + WeatherContract.LocationEntry._ID); } //location.location_setting = ? private static final String sLocationSettingSelection = WeatherContract.LocationEntry.TABLE_NAME+ "." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? "; //location.location_setting = ? AND date >= ? private static final String sLocationSettingWithStartDateSelection = WeatherContract.LocationEntry.TABLE_NAME+ "." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " + WeatherContract.WeatherEntry.COLUMN_DATE + " >= ? "; //location.location_setting = ? AND date = ? private static final String sLocationSettingAndDaySelection = WeatherContract.LocationEntry.TABLE_NAME + "." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " + WeatherContract.WeatherEntry.COLUMN_DATE + " = ? "; private Cursor getWeatherByLocationSetting(Uri uri, String[] projection, String sortOrder) { String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri); long startDate = WeatherContract.WeatherEntry.getStartDateFromUri(uri); String[] selectionArgs; String selection; if (startDate == 0) { selection = sLocationSettingSelection; selectionArgs = new String[]{locationSetting}; } else { selectionArgs = new String[]{locationSetting, Long.toString(startDate)}; selection = sLocationSettingWithStartDateSelection; } return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(), projection, selection, selectionArgs, null, null, sortOrder ); } private Cursor getWeatherByLocationSettingAndDate( Uri uri, String[] projection, String sortOrder) { String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri); long date = WeatherContract.WeatherEntry.getDateFromUri(uri); return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(), projection, sLocationSettingAndDaySelection, new String[]{locationSetting, Long.toString(date)}, null, null, sortOrder ); } /* Students: Here is where you need to create the UriMatcher. This UriMatcher will match each URI to the WEATHER, WEATHER_WITH_LOCATION, WEATHER_WITH_LOCATION_AND_DATE, and LOCATION integer constants defined above. You can test this by uncommenting the testUriMatcher test within TestUriMatcher. */ static UriMatcher buildUriMatcher() { // 1) The code passed into the constructor represents the code to return for the root // URI. It's common to use NO_MATCH as the code for this case. Add the constructor below. UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); // 2) Use the addURI function to match each of the types. Use the constants from // WeatherContract to help define the types to the UriMatcher. matcher.addURI(WeatherContract.CONTENT_AUTHORITY,WeatherContract.PATH_WEATHER,WEATHER); matcher.addURI(WeatherContract.CONTENT_AUTHORITY,WeatherContract.PATH_WEATHER+"/*",WEATHER_WITH_LOCATION); matcher.addURI(WeatherContract.CONTENT_AUTHORITY,WeatherContract.PATH_WEATHER+"/*/#",WEATHER_WITH_LOCATION_AND_DATE); matcher.addURI(WeatherContract.CONTENT_AUTHORITY,WeatherContract.PATH_LOCATION,LOCATION); // 3) Return the new matcher! return matcher; } /* Students: We've coded this for you. We just create a new WeatherDbHelper for later use here. */ @Override public boolean onCreate() { mOpenHelper = new WeatherDbHelper(getContext()); return true; } /* Students: Here's where you'll code the getType function that uses the UriMatcher. You can test this by uncommenting testGetType in TestProvider. */ @Override public String getType(Uri uri) { // Use the Uri Matcher to determine what kind of URI this is. final int match = sUriMatcher.match(uri); switch (match) { // Student: Uncomment and fill out these two cases case WEATHER_WITH_LOCATION_AND_DATE: return WeatherContract.WeatherEntry.CONTENT_ITEM_TYPE; case WEATHER_WITH_LOCATION: return WeatherContract.WeatherEntry.CONTENT_TYPE; case WEATHER: return WeatherContract.WeatherEntry.CONTENT_TYPE; case LOCATION: return WeatherContract.LocationEntry.CONTENT_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Here's the switch statement that, given a URI, will determine what kind of request it is, // and query the database accordingly. Cursor retCursor; switch (sUriMatcher.match(uri)) { // "weather/*/*" case WEATHER_WITH_LOCATION_AND_DATE: { retCursor = getWeatherByLocationSettingAndDate(uri, projection, sortOrder); break; } // "weather/*" case WEATHER_WITH_LOCATION: { retCursor = getWeatherByLocationSetting(uri, projection, sortOrder); break; } // "weather" case WEATHER: { retCursor = mOpenHelper.getReadableDatabase().query(WeatherContract.WeatherEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); break; } // "location" case LOCATION: { retCursor = mOpenHelper.getReadableDatabase().query(WeatherContract.LocationEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } retCursor.setNotificationUri(getContext().getContentResolver(), uri); return retCursor; } /* Student: Add the ability to insert Locations to the implementation of this function. */ @Override public Uri insert(Uri uri, ContentValues values) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); Uri returnUri; switch (match) { case WEATHER: { normalizeDate(values); long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, values); if ( _id > 0 ) returnUri = WeatherContract.WeatherEntry.buildWeatherUri(_id); else throw new android.database.SQLException("Failed to insert row into " + uri); break; } case LOCATION: { long _id = db.insert(WeatherContract.LocationEntry.TABLE_NAME,null,values); if(_id > 0 ) returnUri = WeatherContract.LocationEntry.buildLocationUri(_id); else throw new android.database.SQLException("Failed to insert row into " + uri); break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return returnUri; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { // Student: Start by getting a writable database final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); // Student: Use the uriMatcher to match the WEATHER and LOCATION URI's we are going to // handle. If it doesn't match these, throw an UnsupportedOperationException. final int match = sUriMatcher.match(uri); int rowsDeleted; if(selection == null) selection = "1"; switch(match){ case WEATHER: { rowsDeleted = db.delete(WeatherContract.WeatherEntry.TABLE_NAME, selection, selectionArgs); break; } case LOCATION: { rowsDeleted = db.delete(WeatherContract.LocationEntry.TABLE_NAME, selection, selectionArgs); break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } // Student: A null value deletes all rows. In my implementation of this, I only notified // the uri listeners (using the content resolver) if the rowsDeleted != 0 or the selection // is null. // Oh, and you should notify the listeners here. if(rowsDeleted!=0){ getContext().getContentResolver().notifyChange(uri,null); } // Student: return the actual rows deleted return rowsDeleted; } private void normalizeDate(ContentValues values) { // normalize the date value if (values.containsKey(WeatherContract.WeatherEntry.COLUMN_DATE)) { long dateValue = values.getAsLong(WeatherContract.WeatherEntry.COLUMN_DATE); values.put(WeatherContract.WeatherEntry.COLUMN_DATE, WeatherContract.normalizeDate(dateValue)); } } @Override public int update( Uri uri, ContentValues values, String selection, String[] selectionArgs) { // Student: Start by getting a writable database final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); // Student: Use the uriMatcher to match the WEATHER and LOCATION URI's we are going to // handle. If it doesn't match these, throw an UnsupportedOperationException. final int match = sUriMatcher.match(uri); int rowsUpdated; switch(match){ case WEATHER: { rowsUpdated = db.update(WeatherContract.WeatherEntry.TABLE_NAME, values, selection, selectionArgs); break; } case LOCATION: { rowsUpdated = db.update(WeatherContract.LocationEntry.TABLE_NAME, values, selection, selectionArgs); break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } // Student: A null value deletes all rows. In my implementation of this, I only notified // the uri listeners (using the content resolver) if the rowsDeleted != 0 or the selection // is null. // Oh, and you should notify the listeners here. if(rowsUpdated!=0 || selection == null){ getContext().getContentResolver().notifyChange(uri,null); } // Student: return the actual rows deleted return rowsUpdated; } @Override public int bulkInsert(Uri uri, ContentValues[] values) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { case WEATHER: db.beginTransaction(); int returnCount = 0; try { for (ContentValues value : values) { normalizeDate(value); long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value); if (_id != -1) { returnCount++; } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } getContext().getContentResolver().notifyChange(uri, null); return returnCount; default: return super.bulkInsert(uri, values); } } // You do not need to call this method. This is a method specifically to assist the testing // framework in running smoothly. You can read more at: // http://developer.android.com/reference/android/content/ContentProvider.html#shutdown() @Override @TargetApi(11) public void shutdown() { mOpenHelper.close(); super.shutdown(); } }
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.adblock; import android.text.TextUtils; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class AdBlockDecoder { public static List<AdBlock> decode(String text, boolean comment) { return decode(new Scanner(text), comment); } public static List<AdBlock> decode(Scanner scanner, boolean comment) { List<AdBlock> adBlocks = new ArrayList<>(); while (scanner.hasNext()) { String line = scanner.nextLine().trim(); if (!TextUtils.isEmpty(line)) { if (comment && (line.charAt(0) == '#' || line.startsWith("//"))) continue; if (line.startsWith("127.0.0.1")) line = line.replace("127.0.0.1", "h"); else if (line.startsWith("0.0.0.0")) line = line.replace("0.0.0.0", "h"); adBlocks.add(new AdBlock(line)); } } return adBlocks; } }
package com.baeldung.jackson.test; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import java.io.IOException; import org.junit.Test; import com.baeldung.jackson.jsonview.Item; import com.baeldung.jackson.jsonview.MyBeanSerializerModifier; import com.baeldung.jackson.jsonview.User; import com.baeldung.jackson.jsonview.Views; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ser.BeanSerializerFactory; import com.fasterxml.jackson.databind.ser.SerializerFactory; public class JacksonJsonViewUnitTest { @Test public void whenUseJsonViewToSerialize_thenCorrect() throws JsonProcessingException { final User user = new User(1, "John"); final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); final String result = mapper.writerWithView(Views.Public.class) .writeValueAsString(user); assertThat(result, containsString("John")); assertThat(result, not(containsString("1"))); } @Test public void whenUsePublicView_thenOnlyPublicSerialized() throws JsonProcessingException { final Item item = new Item(2, "book", "John"); final ObjectMapper mapper = new ObjectMapper(); final String result = mapper.writerWithView(Views.Public.class) .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("2")); assertThat(result, not(containsString("John"))); } @Test public void whenUseInternalView_thenAllSerialized() throws JsonProcessingException { final Item item = new Item(2, "book", "John"); final ObjectMapper mapper = new ObjectMapper(); final String result = mapper.writerWithView(Views.Internal.class) .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("2")); assertThat(result, containsString("John")); } @Test public void whenUseJsonViewToDeserialize_thenCorrect() throws IOException { final String json = "{\"id\":1,\"name\":\"John\"}"; final ObjectMapper mapper = new ObjectMapper(); final User user = mapper.readerWithView(Views.Public.class) .forType(User.class) .readValue(json); assertEquals(1, user.getId()); assertEquals("John", user.getName()); } @Test public void whenUseCustomJsonViewToSerialize_thenCorrect() throws JsonProcessingException { final User user = new User(1, "John"); final SerializerFactory serializerFactory = BeanSerializerFactory.instance.withSerializerModifier(new MyBeanSerializerModifier()); final ObjectMapper mapper = new ObjectMapper(); mapper.setSerializerFactory(serializerFactory); final String result = mapper.writerWithView(Views.Public.class) .writeValueAsString(user); assertThat(result, containsString("JOHN")); assertThat(result, containsString("1")); } }
package kr.co.basicspring.test01; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; 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.ModelAndView; /* * 스프링 프레임워크 특징 * - 환경설정이 복잡하다 * - 어노테이션 방식으로 구성할 수 있다. * */ @Controller //해당 클래스는 컨트롤러 기능이다. //스프링컨테이너(서버)에서 자동으로 객체 생성된다. public class CalcController { public CalcController() { System.out.println("---------CalcController() 객체 생성됨"); } //결과확인 //http://localhost:8090/basicspring/add.do?no1=5&no2=8 //@RequestMapping //->요청 명령어 등록 //->요청 명령어 등록 후 실행의 주체는 메소드(함수)로 한다. //1) @RequestMapping(value="요청명령어",method=GET|POST) @RequestMapping(value = "/add.do" , method=RequestMethod.GET) public ModelAndView add(HttpServletRequest req) { //사용자가 요청한 값 가져오기 int no1=Integer.parseInt(req.getParameter("no1")); int no2=Integer.parseInt(req.getParameter("no2")); System.out.println(no1); System.out.println(no2); int result=no1+no2; //view단으로 이동하기 위한 클래스 //두 클래스 중 아무거나 사용 가능 //->Model //->ModelAndView ModelAndView mav=new ModelAndView(); //View페이지로 이동 //servlet-context.xml -> prefix(접두사) : /WEB-INF/views/ // -> suffix(접미사) : .jsp //접두사와 접미사는 변경가능 // /WEB-INF/views/(prefix)calcResult.jsp(suffix) -> 이런식으로 구성 mav.setViewName("calcResult"); //공유장소 req영역에 값 올리기 req.setAttribute("msg", "<h1>두수의 합</h1>"); req.setAttribute("img","<img src='resources/images/add.png'>" ); req.setAttribute("no1", no1); req.setAttribute("no2",no2 ); req.setAttribute("result",result ); return mav; }//add //결과확인 //http://localhost:8090/basicspring/sub.do?no1=5&no2=8 @RequestMapping(value = "/sub.do",method =RequestMethod.GET) public ModelAndView sub(HttpServletRequest req) { int no1=Integer.parseInt(req.getParameter("no1")); int no2=Integer.parseInt(req.getParameter("no2")); System.out.println(no1); System.out.println(no2); int result=no1-no2; ModelAndView mav=new ModelAndView(); mav.setViewName("calcResult"); //공유공간 request영역에 값 올리기 //req.setAttribute 대신 mav.addObject써도 됨 mav.addObject("msg", "<h1>두수의 합</h1>"); mav.addObject("img","<img src='resources/images/sub.png'>" ); mav.addObject("no1", no1); mav.addObject("no2",no2 ); mav.addObject("result",result ); return mav; }//sub //결과확인 //http://localhost:8090/basicspring/mul.do?no1=5&no2=8 @RequestMapping(value = "/mul.do",method =RequestMethod.GET) public ModelAndView mul(HttpServletRequest req) { int no1=Integer.parseInt(req.getParameter("no1")); int no2=Integer.parseInt(req.getParameter("no2")); System.out.println(no1); System.out.println(no2); int result=no1*no2; ModelAndView mav=new ModelAndView(); mav.setViewName("calcResult"); //공유공간 request영역에 값 올리기 //req.setAttribute 대신 mav.addObject써도 됨 mav.addObject("msg", "<h1>두수의 합</h1>"); mav.addObject("img","<img src='resources/images/mul.png'>" ); mav.addObject("no1", no1); mav.addObject("no2",no2 ); mav.addObject("result",result ); return mav; }//mul //결과확인 //http://localhost:8090/basicspring/div.do?no1=5&no2=8 @RequestMapping(value = "/div.do",method =RequestMethod.GET) public ModelAndView div(HttpServletRequest req) { int no1=Integer.parseInt(req.getParameter("no1")); int no2=Integer.parseInt(req.getParameter("no2")); System.out.println(no1); System.out.println(no2); double result=(double)no1/(double)no2; ModelAndView mav=new ModelAndView(); mav.setViewName("calcResult"); mav.addObject("msg", "<h1>두수의 합</h1>"); mav.addObject("img","<img src='resources/images/div.png'>" ); mav.addObject("no1", no1); mav.addObject("no2",no2 ); mav.addObject("result",result ); return mav; }//div //2)요청명령어를 처리하는 메소드 매개변수의 유연성 //@RequestParam("요청명령어") 자료형 변수명 //->사용자가 요청한 값을 직접 변수에 저장 가능하다. @RequestMapping("diff.do") //<-GET|POST 둘 다 허용 public ModelAndView diff(@RequestParam("no1") int a, @RequestParam("no2") int b) { //두 수 사이의 차이 int result=Math.abs(a-b); ModelAndView mav=new ModelAndView(); mav.setViewName("calcResult"); mav.addObject("msg", "<h1>두수의 차이</h1>"); mav.addObject("no1", a); mav.addObject("no2",b ); mav.addObject("result",result ); return mav; }//diff //-------------------------------------------------------------------------- //3)사용자가 요청한 값을 매개변수로 직접 지정 //->요청변수명과 매개변수명이 동일해야 한다. @RequestMapping("max.do") public ModelAndView max(int no1, int no2) { //두 수 중 큰수 int result=Math.max(no1, no2); ModelAndView mav=new ModelAndView(); mav.setViewName("calcResult"); mav.addObject("msg", "<h1>두 수 중 큰수</h1>"); mav.addObject("no1", no1); mav.addObject("no2",no2 ); mav.addObject("result",result ); return mav; }//max }//
package net.n2oapp.framework.engine.util; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; import java.util.Set; /** * Модель для тестирования маппинга */ @Data public class TestEntity { private String valueStr; private Integer valueInt; private InnerEntity innerObj; private List<InnerEntity> innerObjList; @Data public static class InnerEntity { private String valueStr; private Integer valueInt; private Set<InnerInnerEntity> innerInnerObjSet; @Data @NoArgsConstructor @AllArgsConstructor public static class InnerInnerEntity { private String innerName; } } }
/* * Copyright 2017-2020 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.micronaut.liquibase.endpoint; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import liquibase.changelog.RanChangeSet; import java.io.IOException; import java.time.Instant; /** * Jackson serializer for {@link RanChangeSet}. * * @author Iván López * @since 1.0.0 * @deprecated Unused, replaced by wrapper type. */ @Deprecated public class RanChangeSetSerializer extends JsonSerializer<RanChangeSet> { @Override public void serialize(RanChangeSet value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeStartObject(); gen.writeStringField("author", value.getAuthor()); gen.writeStringField("changeLog", value.getChangeLog()); gen.writeStringField("comments", value.getComments()); gen.writeArrayFieldStart("contexts"); for (String c : value.getContextExpression().getContexts()) { gen.writeString(c); } gen.writeEndArray(); gen.writeStringField("dateExecuted", Instant.ofEpochMilli(value.getDateExecuted().getTime()).toString()); gen.writeStringField("deploymentId", value.getDeploymentId()); gen.writeStringField("description", value.getDescription()); gen.writeStringField("execType", value.getExecType().toString()); gen.writeStringField("id", value.getId()); gen.writeArrayFieldStart("labels"); for (String c : value.getLabels().getLabels()) { gen.writeString(c); } gen.writeEndArray(); gen.writeStringField("checksum", ((value.getLastCheckSum() != null) ? value.getLastCheckSum().toString() : null)); gen.writeNumberField("orderExecuted", value.getOrderExecuted()); gen.writeStringField("tag", value.getTag()); gen.writeEndObject(); } }
package com.atguigu.gmall.ums.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 积分变化历史记录 * * @author 上白书妖 * @email shangbaishuyao@163.com * @date 2020-06-06 12:11:32 */ @ApiModel @Data @TableName("ums_integration_change_history") public class IntegrationChangeHistoryEntity implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId @ApiModelProperty(name = "id",value = "id") private Long id; /** * member_id */ @ApiModelProperty(name = "memberId",value = "member_id") private Long memberId; /** * create_time */ @ApiModelProperty(name = "createTime",value = "create_time") private Date createTime; /** * 变化的值 */ @ApiModelProperty(name = "changeCount",value = "变化的值") private Integer changeCount; /** * 备注 */ @ApiModelProperty(name = "note",value = "备注") private String note; /** * 来源[0->购物;1->管理员修改;2->活动] */ @ApiModelProperty(name = "sourceTyoe",value = "来源[0->购物;1->管理员修改;2->活动]") private Integer sourceTyoe; }
package com.silicornio.googlyeyes.dband; import com.silicornio.googlyeyes.dband.general.GECryptLib; import java.util.ArrayList; import java.util.List; import java.util.Map; public class GEResponse { /** Num of object of the response **/ public int numResults; /** Result **/ public Map<String, Object> result; /** List of results when they are more than one **/ public List<Map<String, Object>> results = new ArrayList<>(); /** Info of a problem **/ public String info; /** Error message of the database **/ public String errorDB; public static GEResponse generateInfo(String info){ GEResponse response = new GEResponse(); response.info = info; return response; } public static GEResponse generateErrorDB(String errorDB){ GEResponse response = new GEResponse(); response.errorDB = errorDB; return response; } @Override public String toString() { return "DBResponse{" + "numResults=" + numResults + ", result=" + result + ", results=" + results + ", info='" + info + '\'' + ", errorDB='" + errorDB + '\'' + '}'; } //----- ADDITIONAL ----- public void clean(){ if(results.size()==1){ result = results.get(0); results.clear(); } } /** * Apply decryption to all fields of this response * @param objects GEModelObject[] array of model objects * @param request GERequest to get model information * @param cryptLib GECryptLib to use for encrypting */ public void applyDecryption(GEModelObject[] objects, GERequest request, GECryptLib cryptLib){ //get the model GEModelObject mObject = GEModelFactory.findObject(request.modelObject, objects); if(mObject==null){ return; } //for each operator, check if the attribute has to be encrypted for(Map<String, Object> result : results){ for(GEModelObjectAttribute moa : mObject.attributes){ if(moa.encrypt!=null && result.get(moa.name)!=null && result.get(moa.name) instanceof String){ if(moa.encrypt.equalsIgnoreCase(GEModelObjectAttribute.ENCRYPT_DEFAULT)){ result.put(moa.name, cryptLib.decrypt((String)result.get(moa.name))); } } } } } }
package com.github.zxh.classpy.classfile.datatype; /** * Unsigned two-byte quantity. */ public class U2 extends UInt { public U2() { super(READ_U2, TO_STRING); } }
package ph.codeia.shiv.demo.login; import java.util.Random; import java.util.concurrent.Executor; import java.util.regex.Pattern; import javax.inject.Inject; /* * This file is a part of the Shiv project. */ public class FakeLoginService implements Login.Service { private final Executor io; private final Pattern emailPattern; private final Random rng; @Inject public FakeLoginService(Executor io, Pattern emailPattern, Random rng) { this.io = io; this.emailPattern = emailPattern; this.rng = rng; } @Override public Login.ValidationErrors validate(String username, String password) { return new Login.ValidationErrors( username == null || username.length() == 0 ? "required" : !emailPattern.matcher(username).matches() ? "bad email" : null, password == null || password.length() == 0 ? "required" : password.length() < 5 ? "too simple" : null ); } @Override public void login(String username, String password, Completion block) { io.execute(() -> { try { Thread.sleep(2000); switch (rng.nextInt(10)) { case 0: block.denied(); break; case 1: block.unavailable(); break; case 2: if (rng.nextInt(10) == 0) { throw new IllegalStateException("random error"); } // conditional fallthrough default: block.ok("congrats"); break; } } catch (Exception e) { block.failed(e); } }); } }
package com.github.mikesafonov.smpp.core.sender; import com.cloudhopper.commons.util.windowing.WindowFuture; import com.cloudhopper.smpp.SmppConstants; import com.cloudhopper.smpp.SmppSession; import com.cloudhopper.smpp.SmppSessionConfiguration; import com.cloudhopper.smpp.impl.DefaultSmppClient; import com.cloudhopper.smpp.pdu.*; import com.cloudhopper.smpp.type.*; import com.github.mikesafonov.smpp.core.dto.*; import com.github.mikesafonov.smpp.core.exceptions.IllegalAddressException; import com.github.mikesafonov.smpp.core.exceptions.SenderClientBindException; import com.github.mikesafonov.smpp.core.exceptions.SmppException; import com.github.mikesafonov.smpp.core.exceptions.SmppSessionException; import lombok.extern.slf4j.Slf4j; import javax.validation.constraints.NotNull; import static java.lang.String.format; import static java.util.Objects.requireNonNull; /** * Default implementation of {@link SenderClient}, build on top of {@link DefaultSmppClient} and * {@link SmppSession} * * @author Mike Safonov */ @Slf4j public class StandardSenderClient implements SenderClient { private static final int INVALID_PARAM = 101; private static final int INVALID_SENDING_ERROR = 102; private static final String SENDER_SUCCESS_BINDED_MESSAGE = "SENDER SUCCESSFUL BINDED"; /** * SMPP client. */ private final DefaultSmppClient client; /** * SMPP sender configuration */ private final TransmitterConfiguration sessionConfig; /** * Number of attempts to reconnect if smpp session closed */ private final int maxTryCount; /** * Request timeout in millis */ private final long timeoutMillis; /** * Message builder */ private final MessageBuilder messageBuilder; private final boolean ucs2Only; private boolean inited = false; /** * SMPP session. */ private SmppSession session; public StandardSenderClient(@NotNull TransmitterConfiguration configuration, @NotNull DefaultSmppClient client, int maxTryCount, boolean ucs2Only, long timeoutMillis, @NotNull MessageBuilder messageBuilder) { this.sessionConfig = requireNonNull(configuration); this.messageBuilder = requireNonNull(messageBuilder); this.client = requireNonNull(client); this.maxTryCount = maxTryCount; this.ucs2Only = ucs2Only; this.timeoutMillis = timeoutMillis; } @Override public @NotNull String getId() { return sessionConfig.getName(); } /** * Setup connection to SMSC. * * @throws SenderClientBindException if connection fails * @see #checkSession() */ public void setup(){ if (!inited) { try { checkSession(); } catch (SmppSessionException e) { log.error(e.getErrorMessage(), e); throw new SenderClientBindException(format("Unable to bind with configuration: %s ", sessionConfig.configInformation())); } inited = true; } } /** * Sending message via smpp protocol * * @param message incoming message * @return message response */ @NotNull @Override public MessageResponse send(@NotNull Message message) { requireNonNull(message); if (isNullOrEmpty(message.getText())) { return MessageResponse.error(message, getId(), new MessageErrorInformation(0, "Empty message text")); } try { SubmitSm submitSm = messageBuilder.createSubmitSm(message, ucs2Only); SubmitSmResp send = send(submitSm); return analyzeResponse(message, send); } catch (IllegalAddressException e) { log.error(e.getMessage(), e); return MessageResponse.error(message, getId(), new MessageErrorInformation(INVALID_PARAM, e.getMessage())); } catch (SmppException e) { return MessageResponse.error(message, getId(), new MessageErrorInformation(e.getErrorCode(), e.getErrorMessage())); } } /** * Cancel smsc message * * @param cancelMessage message to cancel * @return cancel response */ @Override public @NotNull CancelMessageResponse cancel(@NotNull CancelMessage cancelMessage) { requireNonNull(cancelMessage); if (isNullOrEmpty(cancelMessage.getMessageId())) { return CancelMessageResponse.error(cancelMessage, getId(), new MessageErrorInformation(0, "Empty message id")); } try { checkSession(); CancelSm cancelSm = messageBuilder.createCancelSm(cancelMessage); WindowFuture<Integer, PduRequest, PduResponse> futureResponse = session.sendRequestPdu(cancelSm, timeoutMillis, true); if (futureResponse.await() && futureResponse.isDone() && futureResponse.isSuccess()) { return createCancelMessageResponse(cancelMessage, futureResponse); } return CancelMessageResponse.error(cancelMessage, getId(), new MessageErrorInformation(INVALID_PARAM, "Unable to get response")); } catch (RecoverablePduException | UnrecoverablePduException | SmppTimeoutException | SmppChannelException | InterruptedException e) { log.error(e.getMessage(), e); return CancelMessageResponse.error(cancelMessage, getId(), new MessageErrorInformation(INVALID_PARAM, e.getMessage())); } catch (Exception e) { log.error(e.getMessage(), e); return CancelMessageResponse.error(cancelMessage, getId(), new MessageErrorInformation(INVALID_SENDING_ERROR, "Unexpected exception")); } } @NotNull private CancelMessageResponse createCancelMessageResponse(@NotNull CancelMessage cancelMessage, WindowFuture<Integer, PduRequest, PduResponse> futureResponse) { CancelSmResp cancelSmResp = (CancelSmResp) futureResponse.getResponse(); if (cancelSmResp.getCommandStatus() == SmppConstants.STATUS_OK) { return CancelMessageResponse.success(cancelMessage, getId()); } else { return CancelMessageResponse.error(cancelMessage, getId(), new MessageErrorInformation(INVALID_PARAM, cancelSmResp.getResultMessage())); } } private boolean isNullOrEmpty(String value) { return value == null || value.trim().isEmpty(); } /** * Sending {@link SubmitSm} command via smpp. First of all checking session state, if session is * connected then perform SubmitSm request. * * @param sm request * @return request response * @throws SmppException if some exception occurs * @see #checkSession() */ private SubmitSmResp send(SubmitSm sm){ checkSession(); try { return session.submit(sm, timeoutMillis); } catch (SmppInvalidArgumentException ex) { log.error(ex.getMessage(), ex); throw new SmppException(INVALID_PARAM, "Invalid param"); } catch (Exception ex) { log.error(ex.getMessage(), ex); throw new SmppException(INVALID_SENDING_ERROR, "Cant send message"); } } private MessageResponse analyzeResponse(Message message, SubmitSmResp submitSmResp) { if (submitSmResp.getCommandStatus() == SmppConstants.STATUS_OK) return MessageResponse.success(message, getId(), submitSmResp.getMessageId()); else return MessageResponse.error(message, getId(), new MessageErrorInformation(INVALID_PARAM, submitSmResp.getResultMessage())); } /** * Checking smpp session state. If session is null - creating new session using method {@link #bind()}. * Otherwise checking bound session state by method {@link #checkBoundState()}. * * @throws SmppSessionException if session not connected */ private void checkSession() { boolean connectionAlive = false; int tryCount = 0; while (!connectionAlive && tryCount <= maxTryCount) { if (session == null) { connectionAlive = bind(); } else { logSessionConnection(connectionAlive, tryCount); connectionAlive = checkBoundState(); } tryCount++; } if (!connectionAlive) { throw new SmppSessionException(); } } /** * Check is {@link #session} in bound state. <br> * <p> * If <b>true</b>, then sending ping command. If ping fails then trying to reconnect.<br> * If <b>false</b>, check is smpp session in binding state then method return false, otherwise try to reconnect session. * <p> * Метод для проверки состояния сессии Bound * * @return true if session in bound state and ping/reconnection success. * @see #pingOrReconnect() * @see #isBindingOrReconnect() */ private boolean checkBoundState() { if (session.isBound()) { return pingOrReconnect(); } else { return isBindingOrReconnect(); } } /** * Check is smpp session in `binding` state. Reconnect session if session not in `binding` state * * @return is {@link #session} in binding state - return false, otherwise returns result of {@link #reconnect()} method */ private boolean isBindingOrReconnect() { if (session.isBinding()) { sleep(50); return false; } else { return reconnect(); } } /** * Send ping command. If ping return false - then try to reconnect. * * @return if ping or reconnection was successfully * @see #pingConnection() * @see #reconnect() */ private boolean pingOrReconnect() { return pingConnection() || reconnect(); } private void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException ignore) { // ignore } } /** * Debug session connection results * * @param connectionResult connection result * @param connectionTryNumber numbers of try */ private void logSessionConnection(boolean connectionResult, int connectionTryNumber) { log.debug("RESULT = " + connectionResult + " count = " + connectionTryNumber); log.debug("BOUND = " + session.isBound()); log.debug(session.getStateName()); } /** * Sending test request {@link EnquireLink}. * * @return if request was successfully */ private boolean pingConnection() { try { session.enquireLink(new EnquireLink(), 1000); return true; } catch (Exception ex) { log.debug(ex.getMessage(), ex); } return false; } /** * Binding new smpp session * * @return true - if binding was successfully, false - otherwise * @see DefaultSmppClient#bind(SmppSessionConfiguration) */ private boolean bind() { try { session = client.bind(sessionConfig); log.debug(SENDER_SUCCESS_BINDED_MESSAGE); return true; } catch (Exception ex) { log.error(ex.getMessage(), ex); } return false; } /** * Close and destroy smpp session */ private void closeSession() { if (session != null) { session.close(); session.destroy(); session = null; } } /** * Closing existing smpp session and create new connection. * * @return true if reconnection success, false - otherwise * @see #closeSession() * @see #bind() */ private boolean reconnect() { closeSession(); return bind(); } }
package edu.bu.met.cs665.beverages; import edu.bu.met.cs665.store.Menu; import java.util.Arrays; import java.util.HashMap; /** * The purpose of this class is to extend the Beverage class and provide the * additional functionality of adding a condiment to this hot beverage such as * milk or sugar (or any other). * * @author Michael Kramer * * <p>CS665 Spring 2, 2022 Software Design Patterns</p> */ public class HotBeverage extends Beverage { private HashMap<String, Integer> condiments = new HashMap<String, Integer>(); private int condimentCount = 0; // cannot be > 6 private int waterTemperature; // 195-205 private int brewTime; // in seconds round up private String type; // getters public int getWaterTemperature() { return waterTemperature; } public int getBrewTime() { return brewTime; } // setters public void setWaterTemperature(int waterTemperature) { this.waterTemperature = waterTemperature; } public void setBrewTime(int brewTime) { this.brewTime = brewTime; } /** * The purpose of this method is to add a condiment to a hot beverage. * <p>Precondition: an object extending HotBeverage has been instantiated</p> * <p>Postcondition: the condiment along with appropriate units has been added</p> * @param condiment a String, flexible but examples: "milk", "sugar" * @param condimentUnits int between 1 and 3 */ public void addCondiment(String condiment, int condimentUnits) throws CondimentException { if (condimentUnits > 3 || condimentUnits < 1) { throw new CondimentException("Error: " + condiment + " units must be between 1 and 3"); } if (condimentCount == 6) { throw new CondimentException("Error: cannot add " + condiment + ". Max condiments in Beverage reached."); } Menu menu = new Menu(); boolean goodCondiment = Arrays.stream(menu.getCondiments()).anyMatch(condiment::equals) || Arrays.stream(menu.getSweeteners()).anyMatch(condiment::equals); if (goodCondiment && condimentCount < 6) { this.condiments.put(condiment, condimentUnits); condimentCount += condimentUnits; // track condimentUnits in beverage } } public HashMap<String, Integer> getCondiments() { return (HashMap<String, Integer>) condiments.clone(); } @Override public String getType() { return type; } @Override public void setType(String type) { this.type = type; } }
package org.rcsb.cif.api.builder; import org.rcsb.cif.model.Builder; import org.rcsb.cif.model.Category; import org.rcsb.cif.model.ModelFactory; import org.rcsb.cif.api.BaseBlock; import org.rcsb.cif.api.CifBlock; import org.rcsb.cif.api.CifFile; /** * Builds a block in a {@link org.rcsb.cif.api.CifFile}, in most cases there is 1 block which contains all categories * of the file. */ public class BlockBuilder extends Builder.BlockBuilder { protected final CifBuilder parent; public BlockBuilder(String blockName, CifBuilder parent) { super(blockName); this.parent = parent; } /** * Process all stored information and release a {@link CifBlock} instance. Use {@link BlockBuilder#leaveBlock()} if you * want to create a {@link CifFile} instance. Otherwise the block is aware of this parent (and vice versa). * @return the created Block */ public CifBlock build() { return new BaseBlock(categories, "unknown"); } /** * Dive into a category captured by this builder. This will create a generic category, for categories in the CIF * schema use the named enter functions. * @param categoryName the name of this category * @return the CategoryBuilder */ public CategoryBuilder enterCategory(String categoryName) { return new CategoryBuilder(categoryName, this); } /** * Package-private function to process the information of children. * @param categoryBuilder the child builder to incorporate * @return this BlockBuilder instance */ BlockBuilder digest(CategoryBuilder categoryBuilder) { Category category = ModelFactory.createCategoryText(categoryBuilder.getCategoryName(), categoryBuilder.getColumns()); categories.put(categoryBuilder.getCategoryName(), category); return this; } /** * Process all stored information and return to the initial CifBuilder instance. * @return the parent builder */ public CifBuilder leaveBlock() { if (parent == null) { throw new IllegalStateException("cannot leave block with undefined parent file"); } return parent.digest(this); } // generated builder functions public CategoryBuilder.AtomSiteBuilder enterAtomSite() { return new CategoryBuilder.AtomSiteBuilder(this); } public CategoryBuilder.AtomSiteAnisotropBuilder enterAtomSiteAnisotrop() { return new CategoryBuilder.AtomSiteAnisotropBuilder(this); } public CategoryBuilder.AtomSitesBuilder enterAtomSites() { return new CategoryBuilder.AtomSitesBuilder(this); } public CategoryBuilder.AtomSitesAltBuilder enterAtomSitesAlt() { return new CategoryBuilder.AtomSitesAltBuilder(this); } public CategoryBuilder.AtomSitesAltEnsBuilder enterAtomSitesAltEns() { return new CategoryBuilder.AtomSitesAltEnsBuilder(this); } public CategoryBuilder.AtomSitesAltGenBuilder enterAtomSitesAltGen() { return new CategoryBuilder.AtomSitesAltGenBuilder(this); } public CategoryBuilder.AtomSitesFootnoteBuilder enterAtomSitesFootnote() { return new CategoryBuilder.AtomSitesFootnoteBuilder(this); } public CategoryBuilder.AtomTypeBuilder enterAtomType() { return new CategoryBuilder.AtomTypeBuilder(this); } public CategoryBuilder.AuditBuilder enterAudit() { return new CategoryBuilder.AuditBuilder(this); } public CategoryBuilder.AuditAuthorBuilder enterAuditAuthor() { return new CategoryBuilder.AuditAuthorBuilder(this); } public CategoryBuilder.AuditConformBuilder enterAuditConform() { return new CategoryBuilder.AuditConformBuilder(this); } public CategoryBuilder.AuditContactAuthorBuilder enterAuditContactAuthor() { return new CategoryBuilder.AuditContactAuthorBuilder(this); } public CategoryBuilder.CellBuilder enterCell() { return new CategoryBuilder.CellBuilder(this); } public CategoryBuilder.CellMeasurementBuilder enterCellMeasurement() { return new CategoryBuilder.CellMeasurementBuilder(this); } public CategoryBuilder.CellMeasurementReflnBuilder enterCellMeasurementRefln() { return new CategoryBuilder.CellMeasurementReflnBuilder(this); } public CategoryBuilder.ChemCompBuilder enterChemComp() { return new CategoryBuilder.ChemCompBuilder(this); } public CategoryBuilder.ChemCompAngleBuilder enterChemCompAngle() { return new CategoryBuilder.ChemCompAngleBuilder(this); } public CategoryBuilder.ChemCompAtomBuilder enterChemCompAtom() { return new CategoryBuilder.ChemCompAtomBuilder(this); } public CategoryBuilder.ChemCompBondBuilder enterChemCompBond() { return new CategoryBuilder.ChemCompBondBuilder(this); } public CategoryBuilder.ChemCompChirBuilder enterChemCompChir() { return new CategoryBuilder.ChemCompChirBuilder(this); } public CategoryBuilder.ChemCompChirAtomBuilder enterChemCompChirAtom() { return new CategoryBuilder.ChemCompChirAtomBuilder(this); } public CategoryBuilder.ChemCompLinkBuilder enterChemCompLink() { return new CategoryBuilder.ChemCompLinkBuilder(this); } public CategoryBuilder.ChemCompPlaneBuilder enterChemCompPlane() { return new CategoryBuilder.ChemCompPlaneBuilder(this); } public CategoryBuilder.ChemCompPlaneAtomBuilder enterChemCompPlaneAtom() { return new CategoryBuilder.ChemCompPlaneAtomBuilder(this); } public CategoryBuilder.ChemCompTorBuilder enterChemCompTor() { return new CategoryBuilder.ChemCompTorBuilder(this); } public CategoryBuilder.ChemCompTorValueBuilder enterChemCompTorValue() { return new CategoryBuilder.ChemCompTorValueBuilder(this); } public CategoryBuilder.ChemLinkBuilder enterChemLink() { return new CategoryBuilder.ChemLinkBuilder(this); } public CategoryBuilder.ChemLinkAngleBuilder enterChemLinkAngle() { return new CategoryBuilder.ChemLinkAngleBuilder(this); } public CategoryBuilder.ChemLinkBondBuilder enterChemLinkBond() { return new CategoryBuilder.ChemLinkBondBuilder(this); } public CategoryBuilder.ChemLinkChirBuilder enterChemLinkChir() { return new CategoryBuilder.ChemLinkChirBuilder(this); } public CategoryBuilder.ChemLinkChirAtomBuilder enterChemLinkChirAtom() { return new CategoryBuilder.ChemLinkChirAtomBuilder(this); } public CategoryBuilder.ChemLinkPlaneBuilder enterChemLinkPlane() { return new CategoryBuilder.ChemLinkPlaneBuilder(this); } public CategoryBuilder.ChemLinkPlaneAtomBuilder enterChemLinkPlaneAtom() { return new CategoryBuilder.ChemLinkPlaneAtomBuilder(this); } public CategoryBuilder.ChemLinkTorBuilder enterChemLinkTor() { return new CategoryBuilder.ChemLinkTorBuilder(this); } public CategoryBuilder.ChemLinkTorValueBuilder enterChemLinkTorValue() { return new CategoryBuilder.ChemLinkTorValueBuilder(this); } public CategoryBuilder.ChemicalBuilder enterChemical() { return new CategoryBuilder.ChemicalBuilder(this); } public CategoryBuilder.ChemicalConnAtomBuilder enterChemicalConnAtom() { return new CategoryBuilder.ChemicalConnAtomBuilder(this); } public CategoryBuilder.ChemicalConnBondBuilder enterChemicalConnBond() { return new CategoryBuilder.ChemicalConnBondBuilder(this); } public CategoryBuilder.ChemicalFormulaBuilder enterChemicalFormula() { return new CategoryBuilder.ChemicalFormulaBuilder(this); } public CategoryBuilder.CitationBuilder enterCitation() { return new CategoryBuilder.CitationBuilder(this); } public CategoryBuilder.CitationAuthorBuilder enterCitationAuthor() { return new CategoryBuilder.CitationAuthorBuilder(this); } public CategoryBuilder.CitationEditorBuilder enterCitationEditor() { return new CategoryBuilder.CitationEditorBuilder(this); } public CategoryBuilder.ComputingBuilder enterComputing() { return new CategoryBuilder.ComputingBuilder(this); } public CategoryBuilder.DatabaseBuilder enterDatabase() { return new CategoryBuilder.DatabaseBuilder(this); } public CategoryBuilder.Database2Builder enterDatabase2() { return new CategoryBuilder.Database2Builder(this); } public CategoryBuilder.DatabasePDBCaveatBuilder enterDatabasePDBCaveat() { return new CategoryBuilder.DatabasePDBCaveatBuilder(this); } public CategoryBuilder.DatabasePDBMatrixBuilder enterDatabasePDBMatrix() { return new CategoryBuilder.DatabasePDBMatrixBuilder(this); } public CategoryBuilder.DatabasePDBRemarkBuilder enterDatabasePDBRemark() { return new CategoryBuilder.DatabasePDBRemarkBuilder(this); } public CategoryBuilder.DatabasePDBRevBuilder enterDatabasePDBRev() { return new CategoryBuilder.DatabasePDBRevBuilder(this); } public CategoryBuilder.DatabasePDBRevRecordBuilder enterDatabasePDBRevRecord() { return new CategoryBuilder.DatabasePDBRevRecordBuilder(this); } public CategoryBuilder.DatabasePDBTvectBuilder enterDatabasePDBTvect() { return new CategoryBuilder.DatabasePDBTvectBuilder(this); } public CategoryBuilder.DiffrnBuilder enterDiffrn() { return new CategoryBuilder.DiffrnBuilder(this); } public CategoryBuilder.DiffrnAttenuatorBuilder enterDiffrnAttenuator() { return new CategoryBuilder.DiffrnAttenuatorBuilder(this); } public CategoryBuilder.DiffrnDetectorBuilder enterDiffrnDetector() { return new CategoryBuilder.DiffrnDetectorBuilder(this); } public CategoryBuilder.DiffrnMeasurementBuilder enterDiffrnMeasurement() { return new CategoryBuilder.DiffrnMeasurementBuilder(this); } public CategoryBuilder.DiffrnOrientMatrixBuilder enterDiffrnOrientMatrix() { return new CategoryBuilder.DiffrnOrientMatrixBuilder(this); } public CategoryBuilder.DiffrnOrientReflnBuilder enterDiffrnOrientRefln() { return new CategoryBuilder.DiffrnOrientReflnBuilder(this); } public CategoryBuilder.DiffrnRadiationBuilder enterDiffrnRadiation() { return new CategoryBuilder.DiffrnRadiationBuilder(this); } public CategoryBuilder.DiffrnRadiationWavelengthBuilder enterDiffrnRadiationWavelength() { return new CategoryBuilder.DiffrnRadiationWavelengthBuilder(this); } public CategoryBuilder.DiffrnReflnBuilder enterDiffrnRefln() { return new CategoryBuilder.DiffrnReflnBuilder(this); } public CategoryBuilder.DiffrnReflnsBuilder enterDiffrnReflns() { return new CategoryBuilder.DiffrnReflnsBuilder(this); } public CategoryBuilder.DiffrnScaleGroupBuilder enterDiffrnScaleGroup() { return new CategoryBuilder.DiffrnScaleGroupBuilder(this); } public CategoryBuilder.DiffrnSourceBuilder enterDiffrnSource() { return new CategoryBuilder.DiffrnSourceBuilder(this); } public CategoryBuilder.DiffrnStandardReflnBuilder enterDiffrnStandardRefln() { return new CategoryBuilder.DiffrnStandardReflnBuilder(this); } public CategoryBuilder.DiffrnStandardsBuilder enterDiffrnStandards() { return new CategoryBuilder.DiffrnStandardsBuilder(this); } public CategoryBuilder.EntityBuilder enterEntity() { return new CategoryBuilder.EntityBuilder(this); } public CategoryBuilder.EntityKeywordsBuilder enterEntityKeywords() { return new CategoryBuilder.EntityKeywordsBuilder(this); } public CategoryBuilder.EntityLinkBuilder enterEntityLink() { return new CategoryBuilder.EntityLinkBuilder(this); } public CategoryBuilder.EntityNameComBuilder enterEntityNameCom() { return new CategoryBuilder.EntityNameComBuilder(this); } public CategoryBuilder.EntityNameSysBuilder enterEntityNameSys() { return new CategoryBuilder.EntityNameSysBuilder(this); } public CategoryBuilder.EntityPolyBuilder enterEntityPoly() { return new CategoryBuilder.EntityPolyBuilder(this); } public CategoryBuilder.EntityPolySeqBuilder enterEntityPolySeq() { return new CategoryBuilder.EntityPolySeqBuilder(this); } public CategoryBuilder.EntryBuilder enterEntry() { return new CategoryBuilder.EntryBuilder(this); } public CategoryBuilder.EntryLinkBuilder enterEntryLink() { return new CategoryBuilder.EntryLinkBuilder(this); } public CategoryBuilder.ExptlBuilder enterExptl() { return new CategoryBuilder.ExptlBuilder(this); } public CategoryBuilder.ExptlCrystalBuilder enterExptlCrystal() { return new CategoryBuilder.ExptlCrystalBuilder(this); } public CategoryBuilder.ExptlCrystalFaceBuilder enterExptlCrystalFace() { return new CategoryBuilder.ExptlCrystalFaceBuilder(this); } public CategoryBuilder.ExptlCrystalGrowBuilder enterExptlCrystalGrow() { return new CategoryBuilder.ExptlCrystalGrowBuilder(this); } public CategoryBuilder.ExptlCrystalGrowCompBuilder enterExptlCrystalGrowComp() { return new CategoryBuilder.ExptlCrystalGrowCompBuilder(this); } public CategoryBuilder.GeomBuilder enterGeom() { return new CategoryBuilder.GeomBuilder(this); } public CategoryBuilder.GeomAngleBuilder enterGeomAngle() { return new CategoryBuilder.GeomAngleBuilder(this); } public CategoryBuilder.GeomBondBuilder enterGeomBond() { return new CategoryBuilder.GeomBondBuilder(this); } public CategoryBuilder.GeomContactBuilder enterGeomContact() { return new CategoryBuilder.GeomContactBuilder(this); } public CategoryBuilder.GeomHbondBuilder enterGeomHbond() { return new CategoryBuilder.GeomHbondBuilder(this); } public CategoryBuilder.GeomTorsionBuilder enterGeomTorsion() { return new CategoryBuilder.GeomTorsionBuilder(this); } public CategoryBuilder.JournalBuilder enterJournal() { return new CategoryBuilder.JournalBuilder(this); } public CategoryBuilder.JournalIndexBuilder enterJournalIndex() { return new CategoryBuilder.JournalIndexBuilder(this); } public CategoryBuilder.PhasingBuilder enterPhasing() { return new CategoryBuilder.PhasingBuilder(this); } public CategoryBuilder.PhasingAveragingBuilder enterPhasingAveraging() { return new CategoryBuilder.PhasingAveragingBuilder(this); } public CategoryBuilder.PhasingIsomorphousBuilder enterPhasingIsomorphous() { return new CategoryBuilder.PhasingIsomorphousBuilder(this); } public CategoryBuilder.PhasingMADBuilder enterPhasingMAD() { return new CategoryBuilder.PhasingMADBuilder(this); } public CategoryBuilder.PhasingMADClustBuilder enterPhasingMADClust() { return new CategoryBuilder.PhasingMADClustBuilder(this); } public CategoryBuilder.PhasingMADExptBuilder enterPhasingMADExpt() { return new CategoryBuilder.PhasingMADExptBuilder(this); } public CategoryBuilder.PhasingMADRatioBuilder enterPhasingMADRatio() { return new CategoryBuilder.PhasingMADRatioBuilder(this); } public CategoryBuilder.PhasingMADSetBuilder enterPhasingMADSet() { return new CategoryBuilder.PhasingMADSetBuilder(this); } public CategoryBuilder.PhasingMIRBuilder enterPhasingMIR() { return new CategoryBuilder.PhasingMIRBuilder(this); } public CategoryBuilder.PhasingMIRDerBuilder enterPhasingMIRDer() { return new CategoryBuilder.PhasingMIRDerBuilder(this); } public CategoryBuilder.PhasingMIRDerReflnBuilder enterPhasingMIRDerRefln() { return new CategoryBuilder.PhasingMIRDerReflnBuilder(this); } public CategoryBuilder.PhasingMIRDerShellBuilder enterPhasingMIRDerShell() { return new CategoryBuilder.PhasingMIRDerShellBuilder(this); } public CategoryBuilder.PhasingMIRDerSiteBuilder enterPhasingMIRDerSite() { return new CategoryBuilder.PhasingMIRDerSiteBuilder(this); } public CategoryBuilder.PhasingMIRShellBuilder enterPhasingMIRShell() { return new CategoryBuilder.PhasingMIRShellBuilder(this); } public CategoryBuilder.PhasingSetBuilder enterPhasingSet() { return new CategoryBuilder.PhasingSetBuilder(this); } public CategoryBuilder.PhasingSetReflnBuilder enterPhasingSetRefln() { return new CategoryBuilder.PhasingSetReflnBuilder(this); } public CategoryBuilder.PublBuilder enterPubl() { return new CategoryBuilder.PublBuilder(this); } public CategoryBuilder.PublAuthorBuilder enterPublAuthor() { return new CategoryBuilder.PublAuthorBuilder(this); } public CategoryBuilder.PublBodyBuilder enterPublBody() { return new CategoryBuilder.PublBodyBuilder(this); } public CategoryBuilder.PublManuscriptInclBuilder enterPublManuscriptIncl() { return new CategoryBuilder.PublManuscriptInclBuilder(this); } public CategoryBuilder.RefineBuilder enterRefine() { return new CategoryBuilder.RefineBuilder(this); } public CategoryBuilder.RefineAnalyzeBuilder enterRefineAnalyze() { return new CategoryBuilder.RefineAnalyzeBuilder(this); } public CategoryBuilder.RefineBIsoBuilder enterRefineBIso() { return new CategoryBuilder.RefineBIsoBuilder(this); } public CategoryBuilder.RefineFunctMinimizedBuilder enterRefineFunctMinimized() { return new CategoryBuilder.RefineFunctMinimizedBuilder(this); } public CategoryBuilder.RefineHistBuilder enterRefineHist() { return new CategoryBuilder.RefineHistBuilder(this); } public CategoryBuilder.RefineLsRestrBuilder enterRefineLsRestr() { return new CategoryBuilder.RefineLsRestrBuilder(this); } public CategoryBuilder.RefineLsRestrNcsBuilder enterRefineLsRestrNcs() { return new CategoryBuilder.RefineLsRestrNcsBuilder(this); } public CategoryBuilder.RefineLsRestrTypeBuilder enterRefineLsRestrType() { return new CategoryBuilder.RefineLsRestrTypeBuilder(this); } public CategoryBuilder.RefineLsShellBuilder enterRefineLsShell() { return new CategoryBuilder.RefineLsShellBuilder(this); } public CategoryBuilder.RefineOccupancyBuilder enterRefineOccupancy() { return new CategoryBuilder.RefineOccupancyBuilder(this); } public CategoryBuilder.ReflnBuilder enterRefln() { return new CategoryBuilder.ReflnBuilder(this); } public CategoryBuilder.ReflnSysAbsBuilder enterReflnSysAbs() { return new CategoryBuilder.ReflnSysAbsBuilder(this); } public CategoryBuilder.ReflnsBuilder enterReflns() { return new CategoryBuilder.ReflnsBuilder(this); } public CategoryBuilder.ReflnsScaleBuilder enterReflnsScale() { return new CategoryBuilder.ReflnsScaleBuilder(this); } public CategoryBuilder.ReflnsShellBuilder enterReflnsShell() { return new CategoryBuilder.ReflnsShellBuilder(this); } public CategoryBuilder.SoftwareBuilder enterSoftware() { return new CategoryBuilder.SoftwareBuilder(this); } public CategoryBuilder.StructBuilder enterStruct() { return new CategoryBuilder.StructBuilder(this); } public CategoryBuilder.StructAsymBuilder enterStructAsym() { return new CategoryBuilder.StructAsymBuilder(this); } public CategoryBuilder.StructBiolBuilder enterStructBiol() { return new CategoryBuilder.StructBiolBuilder(this); } public CategoryBuilder.StructBiolGenBuilder enterStructBiolGen() { return new CategoryBuilder.StructBiolGenBuilder(this); } public CategoryBuilder.StructBiolKeywordsBuilder enterStructBiolKeywords() { return new CategoryBuilder.StructBiolKeywordsBuilder(this); } public CategoryBuilder.StructBiolViewBuilder enterStructBiolView() { return new CategoryBuilder.StructBiolViewBuilder(this); } public CategoryBuilder.StructConfBuilder enterStructConf() { return new CategoryBuilder.StructConfBuilder(this); } public CategoryBuilder.StructConfTypeBuilder enterStructConfType() { return new CategoryBuilder.StructConfTypeBuilder(this); } public CategoryBuilder.StructConnBuilder enterStructConn() { return new CategoryBuilder.StructConnBuilder(this); } public CategoryBuilder.StructConnTypeBuilder enterStructConnType() { return new CategoryBuilder.StructConnTypeBuilder(this); } public CategoryBuilder.StructKeywordsBuilder enterStructKeywords() { return new CategoryBuilder.StructKeywordsBuilder(this); } public CategoryBuilder.StructMonDetailsBuilder enterStructMonDetails() { return new CategoryBuilder.StructMonDetailsBuilder(this); } public CategoryBuilder.StructMonNuclBuilder enterStructMonNucl() { return new CategoryBuilder.StructMonNuclBuilder(this); } public CategoryBuilder.StructMonProtBuilder enterStructMonProt() { return new CategoryBuilder.StructMonProtBuilder(this); } public CategoryBuilder.StructMonProtCisBuilder enterStructMonProtCis() { return new CategoryBuilder.StructMonProtCisBuilder(this); } public CategoryBuilder.StructNcsDomBuilder enterStructNcsDom() { return new CategoryBuilder.StructNcsDomBuilder(this); } public CategoryBuilder.StructNcsDomLimBuilder enterStructNcsDomLim() { return new CategoryBuilder.StructNcsDomLimBuilder(this); } public CategoryBuilder.StructNcsEnsBuilder enterStructNcsEns() { return new CategoryBuilder.StructNcsEnsBuilder(this); } public CategoryBuilder.StructNcsEnsGenBuilder enterStructNcsEnsGen() { return new CategoryBuilder.StructNcsEnsGenBuilder(this); } public CategoryBuilder.StructNcsOperBuilder enterStructNcsOper() { return new CategoryBuilder.StructNcsOperBuilder(this); } public CategoryBuilder.StructRefBuilder enterStructRef() { return new CategoryBuilder.StructRefBuilder(this); } public CategoryBuilder.StructRefSeqBuilder enterStructRefSeq() { return new CategoryBuilder.StructRefSeqBuilder(this); } public CategoryBuilder.StructRefSeqDifBuilder enterStructRefSeqDif() { return new CategoryBuilder.StructRefSeqDifBuilder(this); } public CategoryBuilder.StructSheetBuilder enterStructSheet() { return new CategoryBuilder.StructSheetBuilder(this); } public CategoryBuilder.StructSheetHbondBuilder enterStructSheetHbond() { return new CategoryBuilder.StructSheetHbondBuilder(this); } public CategoryBuilder.StructSheetOrderBuilder enterStructSheetOrder() { return new CategoryBuilder.StructSheetOrderBuilder(this); } public CategoryBuilder.StructSheetRangeBuilder enterStructSheetRange() { return new CategoryBuilder.StructSheetRangeBuilder(this); } public CategoryBuilder.StructSheetTopologyBuilder enterStructSheetTopology() { return new CategoryBuilder.StructSheetTopologyBuilder(this); } public CategoryBuilder.StructSiteBuilder enterStructSite() { return new CategoryBuilder.StructSiteBuilder(this); } public CategoryBuilder.StructSiteGenBuilder enterStructSiteGen() { return new CategoryBuilder.StructSiteGenBuilder(this); } public CategoryBuilder.StructSiteKeywordsBuilder enterStructSiteKeywords() { return new CategoryBuilder.StructSiteKeywordsBuilder(this); } public CategoryBuilder.StructSiteViewBuilder enterStructSiteView() { return new CategoryBuilder.StructSiteViewBuilder(this); } public CategoryBuilder.SymmetryBuilder enterSymmetry() { return new CategoryBuilder.SymmetryBuilder(this); } public CategoryBuilder.SymmetryEquivBuilder enterSymmetryEquiv() { return new CategoryBuilder.SymmetryEquivBuilder(this); } public CategoryBuilder.AuditLinkBuilder enterAuditLink() { return new CategoryBuilder.AuditLinkBuilder(this); } public CategoryBuilder.DiffrnReflnsClassBuilder enterDiffrnReflnsClass() { return new CategoryBuilder.DiffrnReflnsClassBuilder(this); } public CategoryBuilder.RefineLsClassBuilder enterRefineLsClass() { return new CategoryBuilder.RefineLsClassBuilder(this); } public CategoryBuilder.ReflnsClassBuilder enterReflnsClass() { return new CategoryBuilder.ReflnsClassBuilder(this); } public CategoryBuilder.SpaceGroupBuilder enterSpaceGroup() { return new CategoryBuilder.SpaceGroupBuilder(this); } public CategoryBuilder.SpaceGroupSymopBuilder enterSpaceGroupSymop() { return new CategoryBuilder.SpaceGroupSymopBuilder(this); } public CategoryBuilder.ValenceParamBuilder enterValenceParam() { return new CategoryBuilder.ValenceParamBuilder(this); } public CategoryBuilder.ValenceRefBuilder enterValenceRef() { return new CategoryBuilder.ValenceRefBuilder(this); } public CategoryBuilder.PdbxAuditBuilder enterPdbxAudit() { return new CategoryBuilder.PdbxAuditBuilder(this); } public CategoryBuilder.PdbxVersionBuilder enterPdbxVersion() { return new CategoryBuilder.PdbxVersionBuilder(this); } public CategoryBuilder.PdbxAuditAuthorBuilder enterPdbxAuditAuthor() { return new CategoryBuilder.PdbxAuditAuthorBuilder(this); } public CategoryBuilder.PdbxDatabaseMessageBuilder enterPdbxDatabaseMessage() { return new CategoryBuilder.PdbxDatabaseMessageBuilder(this); } public CategoryBuilder.PdbxDatabasePDBObsSprBuilder enterPdbxDatabasePDBObsSpr() { return new CategoryBuilder.PdbxDatabasePDBObsSprBuilder(this); } public CategoryBuilder.PdbxDatabaseProcBuilder enterPdbxDatabaseProc() { return new CategoryBuilder.PdbxDatabaseProcBuilder(this); } public CategoryBuilder.PdbxDatabaseRemarkBuilder enterPdbxDatabaseRemark() { return new CategoryBuilder.PdbxDatabaseRemarkBuilder(this); } public CategoryBuilder.PdbxDatabaseStatusBuilder enterPdbxDatabaseStatus() { return new CategoryBuilder.PdbxDatabaseStatusBuilder(this); } public CategoryBuilder.PdbxEntityNameBuilder enterPdbxEntityName() { return new CategoryBuilder.PdbxEntityNameBuilder(this); } public CategoryBuilder.PdbxPrereleaseSeqBuilder enterPdbxPrereleaseSeq() { return new CategoryBuilder.PdbxPrereleaseSeqBuilder(this); } public CategoryBuilder.PdbxPolySeqSchemeBuilder enterPdbxPolySeqScheme() { return new CategoryBuilder.PdbxPolySeqSchemeBuilder(this); } public CategoryBuilder.PdbxNonpolySchemeBuilder enterPdbxNonpolyScheme() { return new CategoryBuilder.PdbxNonpolySchemeBuilder(this); } public CategoryBuilder.PdbxRefineBuilder enterPdbxRefine() { return new CategoryBuilder.PdbxRefineBuilder(this); } public CategoryBuilder.PdbxStructSheetHbondBuilder enterPdbxStructSheetHbond() { return new CategoryBuilder.PdbxStructSheetHbondBuilder(this); } public CategoryBuilder.PdbxXplorFileBuilder enterPdbxXplorFile() { return new CategoryBuilder.PdbxXplorFileBuilder(this); } public CategoryBuilder.PdbxRefineAuxFileBuilder enterPdbxRefineAuxFile() { return new CategoryBuilder.PdbxRefineAuxFileBuilder(this); } public CategoryBuilder.PdbxDatabaseRelatedBuilder enterPdbxDatabaseRelated() { return new CategoryBuilder.PdbxDatabaseRelatedBuilder(this); } public CategoryBuilder.PdbxEntityAssemblyBuilder enterPdbxEntityAssembly() { return new CategoryBuilder.PdbxEntityAssemblyBuilder(this); } public CategoryBuilder.PdbxExptlCrystalGrowCompBuilder enterPdbxExptlCrystalGrowComp() { return new CategoryBuilder.PdbxExptlCrystalGrowCompBuilder(this); } public CategoryBuilder.PdbxExptlCrystalGrowSolBuilder enterPdbxExptlCrystalGrowSol() { return new CategoryBuilder.PdbxExptlCrystalGrowSolBuilder(this); } public CategoryBuilder.PdbxExptlCrystalCryoTreatmentBuilder enterPdbxExptlCrystalCryoTreatment() { return new CategoryBuilder.PdbxExptlCrystalCryoTreatmentBuilder(this); } public CategoryBuilder.PdbxRefineTlsBuilder enterPdbxRefineTls() { return new CategoryBuilder.PdbxRefineTlsBuilder(this); } public CategoryBuilder.PdbxRefineTlsGroupBuilder enterPdbxRefineTlsGroup() { return new CategoryBuilder.PdbxRefineTlsGroupBuilder(this); } public CategoryBuilder.PdbxContactAuthorBuilder enterPdbxContactAuthor() { return new CategoryBuilder.PdbxContactAuthorBuilder(this); } public CategoryBuilder.PdbxSGProjectBuilder enterPdbxSGProject() { return new CategoryBuilder.PdbxSGProjectBuilder(this); } public CategoryBuilder.PdbxAtomSiteAnisoTlsBuilder enterPdbxAtomSiteAnisoTls() { return new CategoryBuilder.PdbxAtomSiteAnisoTlsBuilder(this); } public CategoryBuilder.PdbxNmrDetailsBuilder enterPdbxNmrDetails() { return new CategoryBuilder.PdbxNmrDetailsBuilder(this); } public CategoryBuilder.PdbxNmrSampleDetailsBuilder enterPdbxNmrSampleDetails() { return new CategoryBuilder.PdbxNmrSampleDetailsBuilder(this); } public CategoryBuilder.PdbxNmrExptlSampleBuilder enterPdbxNmrExptlSample() { return new CategoryBuilder.PdbxNmrExptlSampleBuilder(this); } public CategoryBuilder.PdbxNmrExptlSampleConditionsBuilder enterPdbxNmrExptlSampleConditions() { return new CategoryBuilder.PdbxNmrExptlSampleConditionsBuilder(this); } public CategoryBuilder.PdbxNmrSpectrometerBuilder enterPdbxNmrSpectrometer() { return new CategoryBuilder.PdbxNmrSpectrometerBuilder(this); } public CategoryBuilder.PdbxNmrExptlBuilder enterPdbxNmrExptl() { return new CategoryBuilder.PdbxNmrExptlBuilder(this); } public CategoryBuilder.PdbxNmrSoftwareBuilder enterPdbxNmrSoftware() { return new CategoryBuilder.PdbxNmrSoftwareBuilder(this); } public CategoryBuilder.PdbxNmrConstraintsBuilder enterPdbxNmrConstraints() { return new CategoryBuilder.PdbxNmrConstraintsBuilder(this); } public CategoryBuilder.PdbxNmrEnsembleBuilder enterPdbxNmrEnsemble() { return new CategoryBuilder.PdbxNmrEnsembleBuilder(this); } public CategoryBuilder.PdbxNmrEnsembleRmsBuilder enterPdbxNmrEnsembleRms() { return new CategoryBuilder.PdbxNmrEnsembleRmsBuilder(this); } public CategoryBuilder.PdbxNmrRepresentativeBuilder enterPdbxNmrRepresentative() { return new CategoryBuilder.PdbxNmrRepresentativeBuilder(this); } public CategoryBuilder.PdbxNmrRefineBuilder enterPdbxNmrRefine() { return new CategoryBuilder.PdbxNmrRefineBuilder(this); } public CategoryBuilder.PdbxNmrForceConstantsBuilder enterPdbxNmrForceConstants() { return new CategoryBuilder.PdbxNmrForceConstantsBuilder(this); } public CategoryBuilder.NdbStructConfNaBuilder enterNdbStructConfNa() { return new CategoryBuilder.NdbStructConfNaBuilder(this); } public CategoryBuilder.NdbStructFeatureNaBuilder enterNdbStructFeatureNa() { return new CategoryBuilder.NdbStructFeatureNaBuilder(this); } public CategoryBuilder.NdbStructNaBasePairBuilder enterNdbStructNaBasePair() { return new CategoryBuilder.NdbStructNaBasePairBuilder(this); } public CategoryBuilder.NdbStructNaBasePairStepBuilder enterNdbStructNaBasePairStep() { return new CategoryBuilder.NdbStructNaBasePairStepBuilder(this); } public CategoryBuilder.NdbOriginalNdbCoordinatesBuilder enterNdbOriginalNdbCoordinates() { return new CategoryBuilder.NdbOriginalNdbCoordinatesBuilder(this); } public CategoryBuilder.PdbxEntityNonpolyBuilder enterPdbxEntityNonpoly() { return new CategoryBuilder.PdbxEntityNonpolyBuilder(this); } public CategoryBuilder.PdbxPhasingDmBuilder enterPdbxPhasingDm() { return new CategoryBuilder.PdbxPhasingDmBuilder(this); } public CategoryBuilder.PdbxPhasingDmShellBuilder enterPdbxPhasingDmShell() { return new CategoryBuilder.PdbxPhasingDmShellBuilder(this); } public CategoryBuilder.PdbxPhasingMADShellBuilder enterPdbxPhasingMADShell() { return new CategoryBuilder.PdbxPhasingMADShellBuilder(this); } public CategoryBuilder.PdbxPhasingMADSetBuilder enterPdbxPhasingMADSet() { return new CategoryBuilder.PdbxPhasingMADSetBuilder(this); } public CategoryBuilder.PdbxPhasingMADSetShellBuilder enterPdbxPhasingMADSetShell() { return new CategoryBuilder.PdbxPhasingMADSetShellBuilder(this); } public CategoryBuilder.PdbxPhasingMADSetSiteBuilder enterPdbxPhasingMADSetSite() { return new CategoryBuilder.PdbxPhasingMADSetSiteBuilder(this); } public CategoryBuilder.PdbxPhasingMRBuilder enterPdbxPhasingMR() { return new CategoryBuilder.PdbxPhasingMRBuilder(this); } public CategoryBuilder.PdbxRefineComponentBuilder enterPdbxRefineComponent() { return new CategoryBuilder.PdbxRefineComponentBuilder(this); } public CategoryBuilder.PdbxEntityProdProtocolBuilder enterPdbxEntityProdProtocol() { return new CategoryBuilder.PdbxEntityProdProtocolBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenProdOtherBuilder enterPdbxEntitySrcGenProdOther() { return new CategoryBuilder.PdbxEntitySrcGenProdOtherBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenProdOtherParameterBuilder enterPdbxEntitySrcGenProdOtherParameter() { return new CategoryBuilder.PdbxEntitySrcGenProdOtherParameterBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenProdPcrBuilder enterPdbxEntitySrcGenProdPcr() { return new CategoryBuilder.PdbxEntitySrcGenProdPcrBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenProdDigestBuilder enterPdbxEntitySrcGenProdDigest() { return new CategoryBuilder.PdbxEntitySrcGenProdDigestBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenCloneBuilder enterPdbxEntitySrcGenClone() { return new CategoryBuilder.PdbxEntitySrcGenCloneBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenCloneLigationBuilder enterPdbxEntitySrcGenCloneLigation() { return new CategoryBuilder.PdbxEntitySrcGenCloneLigationBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenCloneRecombinationBuilder enterPdbxEntitySrcGenCloneRecombination() { return new CategoryBuilder.PdbxEntitySrcGenCloneRecombinationBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenExpressBuilder enterPdbxEntitySrcGenExpress() { return new CategoryBuilder.PdbxEntitySrcGenExpressBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenExpressTimepointBuilder enterPdbxEntitySrcGenExpressTimepoint() { return new CategoryBuilder.PdbxEntitySrcGenExpressTimepointBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenLysisBuilder enterPdbxEntitySrcGenLysis() { return new CategoryBuilder.PdbxEntitySrcGenLysisBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenRefoldBuilder enterPdbxEntitySrcGenRefold() { return new CategoryBuilder.PdbxEntitySrcGenRefoldBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenProteolysisBuilder enterPdbxEntitySrcGenProteolysis() { return new CategoryBuilder.PdbxEntitySrcGenProteolysisBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenChromBuilder enterPdbxEntitySrcGenChrom() { return new CategoryBuilder.PdbxEntitySrcGenChromBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenFractBuilder enterPdbxEntitySrcGenFract() { return new CategoryBuilder.PdbxEntitySrcGenFractBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenPureBuilder enterPdbxEntitySrcGenPure() { return new CategoryBuilder.PdbxEntitySrcGenPureBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenCharacterBuilder enterPdbxEntitySrcGenCharacter() { return new CategoryBuilder.PdbxEntitySrcGenCharacterBuilder(this); } public CategoryBuilder.PdbxConstructBuilder enterPdbxConstruct() { return new CategoryBuilder.PdbxConstructBuilder(this); } public CategoryBuilder.PdbxConstructFeatureBuilder enterPdbxConstructFeature() { return new CategoryBuilder.PdbxConstructFeatureBuilder(this); } public CategoryBuilder.PdbxRobotSystemBuilder enterPdbxRobotSystem() { return new CategoryBuilder.PdbxRobotSystemBuilder(this); } public CategoryBuilder.PdbxBufferBuilder enterPdbxBuffer() { return new CategoryBuilder.PdbxBufferBuilder(this); } public CategoryBuilder.PdbxBufferComponentsBuilder enterPdbxBufferComponents() { return new CategoryBuilder.PdbxBufferComponentsBuilder(this); } public CategoryBuilder.PdbxDomainBuilder enterPdbxDomain() { return new CategoryBuilder.PdbxDomainBuilder(this); } public CategoryBuilder.PdbxDomainRangeBuilder enterPdbxDomainRange() { return new CategoryBuilder.PdbxDomainRangeBuilder(this); } public CategoryBuilder.PdbxSequenceRangeBuilder enterPdbxSequenceRange() { return new CategoryBuilder.PdbxSequenceRangeBuilder(this); } public CategoryBuilder.PdbxFeatureEntryBuilder enterPdbxFeatureEntry() { return new CategoryBuilder.PdbxFeatureEntryBuilder(this); } public CategoryBuilder.PdbxFeatureDomainBuilder enterPdbxFeatureDomain() { return new CategoryBuilder.PdbxFeatureDomainBuilder(this); } public CategoryBuilder.PdbxFeatureSequenceRangeBuilder enterPdbxFeatureSequenceRange() { return new CategoryBuilder.PdbxFeatureSequenceRangeBuilder(this); } public CategoryBuilder.PdbxFeatureAssemblyBuilder enterPdbxFeatureAssembly() { return new CategoryBuilder.PdbxFeatureAssemblyBuilder(this); } public CategoryBuilder.PdbxFeatureMonomerBuilder enterPdbxFeatureMonomer() { return new CategoryBuilder.PdbxFeatureMonomerBuilder(this); } public CategoryBuilder.PdbxExptlPdBuilder enterPdbxExptlPd() { return new CategoryBuilder.PdbxExptlPdBuilder(this); } public CategoryBuilder.PdbxReflnsTwinBuilder enterPdbxReflnsTwin() { return new CategoryBuilder.PdbxReflnsTwinBuilder(this); } public CategoryBuilder.PdbxStructInfoBuilder enterPdbxStructInfo() { return new CategoryBuilder.PdbxStructInfoBuilder(this); } public CategoryBuilder.PdbxReRefinementBuilder enterPdbxReRefinement() { return new CategoryBuilder.PdbxReRefinementBuilder(this); } public CategoryBuilder.PdbxStructAssemblyPropBuilder enterPdbxStructAssemblyProp() { return new CategoryBuilder.PdbxStructAssemblyPropBuilder(this); } public CategoryBuilder.PdbxStructRefSeqFeatureBuilder enterPdbxStructRefSeqFeature() { return new CategoryBuilder.PdbxStructRefSeqFeatureBuilder(this); } public CategoryBuilder.PdbxStructRefSeqFeaturePropBuilder enterPdbxStructRefSeqFeatureProp() { return new CategoryBuilder.PdbxStructRefSeqFeaturePropBuilder(this); } public CategoryBuilder.PdbxStructChemCompDiagnosticsBuilder enterPdbxStructChemCompDiagnostics() { return new CategoryBuilder.PdbxStructChemCompDiagnosticsBuilder(this); } public CategoryBuilder.PdbxChemCompFeatureBuilder enterPdbxChemCompFeature() { return new CategoryBuilder.PdbxChemCompFeatureBuilder(this); } public CategoryBuilder.PdbxCoordinateModelBuilder enterPdbxCoordinateModel() { return new CategoryBuilder.PdbxCoordinateModelBuilder(this); } public CategoryBuilder.PdbxStructChemCompFeatureBuilder enterPdbxStructChemCompFeature() { return new CategoryBuilder.PdbxStructChemCompFeatureBuilder(this); } public CategoryBuilder.PdbxDiffrnReflnsShellBuilder enterPdbxDiffrnReflnsShell() { return new CategoryBuilder.PdbxDiffrnReflnsShellBuilder(this); } public CategoryBuilder.PdbxBondDistanceLimitsBuilder enterPdbxBondDistanceLimits() { return new CategoryBuilder.PdbxBondDistanceLimitsBuilder(this); } public CategoryBuilder.PdbxSolnScatterBuilder enterPdbxSolnScatter() { return new CategoryBuilder.PdbxSolnScatterBuilder(this); } public CategoryBuilder.PdbxSolnScatterModelBuilder enterPdbxSolnScatterModel() { return new CategoryBuilder.PdbxSolnScatterModelBuilder(this); } public CategoryBuilder.PdbxChemCompDescriptorBuilder enterPdbxChemCompDescriptor() { return new CategoryBuilder.PdbxChemCompDescriptorBuilder(this); } public CategoryBuilder.PdbxChemCompIdentifierBuilder enterPdbxChemCompIdentifier() { return new CategoryBuilder.PdbxChemCompIdentifierBuilder(this); } public CategoryBuilder.PdbxChemCompImportBuilder enterPdbxChemCompImport() { return new CategoryBuilder.PdbxChemCompImportBuilder(this); } public CategoryBuilder.PdbxChemCompAtomEditBuilder enterPdbxChemCompAtomEdit() { return new CategoryBuilder.PdbxChemCompAtomEditBuilder(this); } public CategoryBuilder.PdbxChemCompBondEditBuilder enterPdbxChemCompBondEdit() { return new CategoryBuilder.PdbxChemCompBondEditBuilder(this); } public CategoryBuilder.PdbxChemCompAuditBuilder enterPdbxChemCompAudit() { return new CategoryBuilder.PdbxChemCompAuditBuilder(this); } public CategoryBuilder.PdbxValidateCloseContactBuilder enterPdbxValidateCloseContact() { return new CategoryBuilder.PdbxValidateCloseContactBuilder(this); } public CategoryBuilder.PdbxValidateSymmContactBuilder enterPdbxValidateSymmContact() { return new CategoryBuilder.PdbxValidateSymmContactBuilder(this); } public CategoryBuilder.PdbxValidateRmsdBondBuilder enterPdbxValidateRmsdBond() { return new CategoryBuilder.PdbxValidateRmsdBondBuilder(this); } public CategoryBuilder.PdbxValidateRmsdAngleBuilder enterPdbxValidateRmsdAngle() { return new CategoryBuilder.PdbxValidateRmsdAngleBuilder(this); } public CategoryBuilder.PdbxValidateTorsionBuilder enterPdbxValidateTorsion() { return new CategoryBuilder.PdbxValidateTorsionBuilder(this); } public CategoryBuilder.PdbxValidatePeptideOmegaBuilder enterPdbxValidatePeptideOmega() { return new CategoryBuilder.PdbxValidatePeptideOmegaBuilder(this); } public CategoryBuilder.PdbxValidateChiralBuilder enterPdbxValidateChiral() { return new CategoryBuilder.PdbxValidateChiralBuilder(this); } public CategoryBuilder.PdbxValidatePlanesBuilder enterPdbxValidatePlanes() { return new CategoryBuilder.PdbxValidatePlanesBuilder(this); } public CategoryBuilder.PdbxValidatePlanesAtomBuilder enterPdbxValidatePlanesAtom() { return new CategoryBuilder.PdbxValidatePlanesAtomBuilder(this); } public CategoryBuilder.PdbxValidateMainChainPlaneBuilder enterPdbxValidateMainChainPlane() { return new CategoryBuilder.PdbxValidateMainChainPlaneBuilder(this); } public CategoryBuilder.PdbxStructConnAngleBuilder enterPdbxStructConnAngle() { return new CategoryBuilder.PdbxStructConnAngleBuilder(this); } public CategoryBuilder.PdbxUnobsOrZeroOccResiduesBuilder enterPdbxUnobsOrZeroOccResidues() { return new CategoryBuilder.PdbxUnobsOrZeroOccResiduesBuilder(this); } public CategoryBuilder.PdbxUnobsOrZeroOccAtomsBuilder enterPdbxUnobsOrZeroOccAtoms() { return new CategoryBuilder.PdbxUnobsOrZeroOccAtomsBuilder(this); } public CategoryBuilder.PdbxEntryDetailsBuilder enterPdbxEntryDetails() { return new CategoryBuilder.PdbxEntryDetailsBuilder(this); } public CategoryBuilder.PdbxStructModResidueBuilder enterPdbxStructModResidue() { return new CategoryBuilder.PdbxStructModResidueBuilder(this); } public CategoryBuilder.PdbxStructRefSeqInsertionBuilder enterPdbxStructRefSeqInsertion() { return new CategoryBuilder.PdbxStructRefSeqInsertionBuilder(this); } public CategoryBuilder.PdbxStructRefSeqDeletionBuilder enterPdbxStructRefSeqDeletion() { return new CategoryBuilder.PdbxStructRefSeqDeletionBuilder(this); } public CategoryBuilder.PdbxRemediationAtomSiteMappingBuilder enterPdbxRemediationAtomSiteMapping() { return new CategoryBuilder.PdbxRemediationAtomSiteMappingBuilder(this); } public CategoryBuilder.PdbxValidatePolymerLinkageBuilder enterPdbxValidatePolymerLinkage() { return new CategoryBuilder.PdbxValidatePolymerLinkageBuilder(this); } public CategoryBuilder.PdbxHelicalSymmetryBuilder enterPdbxHelicalSymmetry() { return new CategoryBuilder.PdbxHelicalSymmetryBuilder(this); } public CategoryBuilder.PdbxPointSymmetryBuilder enterPdbxPointSymmetry() { return new CategoryBuilder.PdbxPointSymmetryBuilder(this); } public CategoryBuilder.PdbxStructEntityInstBuilder enterPdbxStructEntityInst() { return new CategoryBuilder.PdbxStructEntityInstBuilder(this); } public CategoryBuilder.PdbxStructOperListBuilder enterPdbxStructOperList() { return new CategoryBuilder.PdbxStructOperListBuilder(this); } public CategoryBuilder.PdbxStructAssemblyBuilder enterPdbxStructAssembly() { return new CategoryBuilder.PdbxStructAssemblyBuilder(this); } public CategoryBuilder.PdbxStructAssemblyGenBuilder enterPdbxStructAssemblyGen() { return new CategoryBuilder.PdbxStructAssemblyGenBuilder(this); } public CategoryBuilder.PdbxStructAsymGenBuilder enterPdbxStructAsymGen() { return new CategoryBuilder.PdbxStructAsymGenBuilder(this); } public CategoryBuilder.PdbxStructMsymGenBuilder enterPdbxStructMsymGen() { return new CategoryBuilder.PdbxStructMsymGenBuilder(this); } public CategoryBuilder.PdbxStructLegacyOperListBuilder enterPdbxStructLegacyOperList() { return new CategoryBuilder.PdbxStructLegacyOperListBuilder(this); } public CategoryBuilder.PdbxChemCompAtomFeatureBuilder enterPdbxChemCompAtomFeature() { return new CategoryBuilder.PdbxChemCompAtomFeatureBuilder(this); } public CategoryBuilder.PdbxReferenceMoleculeFamilyBuilder enterPdbxReferenceMoleculeFamily() { return new CategoryBuilder.PdbxReferenceMoleculeFamilyBuilder(this); } public CategoryBuilder.PdbxReferenceMoleculeListBuilder enterPdbxReferenceMoleculeList() { return new CategoryBuilder.PdbxReferenceMoleculeListBuilder(this); } public CategoryBuilder.PdbxReferenceMoleculeBuilder enterPdbxReferenceMolecule() { return new CategoryBuilder.PdbxReferenceMoleculeBuilder(this); } public CategoryBuilder.PdbxReferenceEntityListBuilder enterPdbxReferenceEntityList() { return new CategoryBuilder.PdbxReferenceEntityListBuilder(this); } public CategoryBuilder.PdbxReferenceEntityNonpolyBuilder enterPdbxReferenceEntityNonpoly() { return new CategoryBuilder.PdbxReferenceEntityNonpolyBuilder(this); } public CategoryBuilder.PdbxReferenceEntityLinkBuilder enterPdbxReferenceEntityLink() { return new CategoryBuilder.PdbxReferenceEntityLinkBuilder(this); } public CategoryBuilder.PdbxReferenceEntityPolyLinkBuilder enterPdbxReferenceEntityPolyLink() { return new CategoryBuilder.PdbxReferenceEntityPolyLinkBuilder(this); } public CategoryBuilder.PdbxReferenceEntityPolyBuilder enterPdbxReferenceEntityPoly() { return new CategoryBuilder.PdbxReferenceEntityPolyBuilder(this); } public CategoryBuilder.PdbxReferenceEntityPolySeqBuilder enterPdbxReferenceEntityPolySeq() { return new CategoryBuilder.PdbxReferenceEntityPolySeqBuilder(this); } public CategoryBuilder.PdbxReferenceEntitySequenceBuilder enterPdbxReferenceEntitySequence() { return new CategoryBuilder.PdbxReferenceEntitySequenceBuilder(this); } public CategoryBuilder.PdbxReferenceEntitySrcNatBuilder enterPdbxReferenceEntitySrcNat() { return new CategoryBuilder.PdbxReferenceEntitySrcNatBuilder(this); } public CategoryBuilder.PdbxReferenceMoleculeDetailsBuilder enterPdbxReferenceMoleculeDetails() { return new CategoryBuilder.PdbxReferenceMoleculeDetailsBuilder(this); } public CategoryBuilder.PdbxReferenceMoleculeSynonymsBuilder enterPdbxReferenceMoleculeSynonyms() { return new CategoryBuilder.PdbxReferenceMoleculeSynonymsBuilder(this); } public CategoryBuilder.PdbxReferenceEntitySubcomponentsBuilder enterPdbxReferenceEntitySubcomponents() { return new CategoryBuilder.PdbxReferenceEntitySubcomponentsBuilder(this); } public CategoryBuilder.PdbxReferenceMoleculeAnnotationBuilder enterPdbxReferenceMoleculeAnnotation() { return new CategoryBuilder.PdbxReferenceMoleculeAnnotationBuilder(this); } public CategoryBuilder.PdbxReferenceMoleculeFeaturesBuilder enterPdbxReferenceMoleculeFeatures() { return new CategoryBuilder.PdbxReferenceMoleculeFeaturesBuilder(this); } public CategoryBuilder.PdbxReferenceMoleculeRelatedStructuresBuilder enterPdbxReferenceMoleculeRelatedStructures() { return new CategoryBuilder.PdbxReferenceMoleculeRelatedStructuresBuilder(this); } public CategoryBuilder.PdbxStructGroupListBuilder enterPdbxStructGroupList() { return new CategoryBuilder.PdbxStructGroupListBuilder(this); } public CategoryBuilder.PdbxStructGroupComponentsBuilder enterPdbxStructGroupComponents() { return new CategoryBuilder.PdbxStructGroupComponentsBuilder(this); } public CategoryBuilder.PdbxStructGroupComponentRangeBuilder enterPdbxStructGroupComponentRange() { return new CategoryBuilder.PdbxStructGroupComponentRangeBuilder(this); } public CategoryBuilder.PdbxPrdAuditBuilder enterPdbxPrdAudit() { return new CategoryBuilder.PdbxPrdAuditBuilder(this); } public CategoryBuilder.PdbxFamilyPrdAuditBuilder enterPdbxFamilyPrdAudit() { return new CategoryBuilder.PdbxFamilyPrdAuditBuilder(this); } public CategoryBuilder.PdbxMoleculeBuilder enterPdbxMolecule() { return new CategoryBuilder.PdbxMoleculeBuilder(this); } public CategoryBuilder.PdbxMoleculeFeaturesBuilder enterPdbxMoleculeFeatures() { return new CategoryBuilder.PdbxMoleculeFeaturesBuilder(this); } public CategoryBuilder.PdbxFamilyGroupIndexBuilder enterPdbxFamilyGroupIndex() { return new CategoryBuilder.PdbxFamilyGroupIndexBuilder(this); } public CategoryBuilder.PdbxDistantSolventAtomsBuilder enterPdbxDistantSolventAtoms() { return new CategoryBuilder.PdbxDistantSolventAtomsBuilder(this); } public CategoryBuilder.PdbxStructSpecialSymmetryBuilder enterPdbxStructSpecialSymmetry() { return new CategoryBuilder.PdbxStructSpecialSymmetryBuilder(this); } public CategoryBuilder.PdbxReferencePublicationListBuilder enterPdbxReferencePublicationList() { return new CategoryBuilder.PdbxReferencePublicationListBuilder(this); } public CategoryBuilder.PdbxNmrAssignedChemShiftListBuilder enterPdbxNmrAssignedChemShiftList() { return new CategoryBuilder.PdbxNmrAssignedChemShiftListBuilder(this); } public CategoryBuilder.PdbxNmrChemShiftExperimentBuilder enterPdbxNmrChemShiftExperiment() { return new CategoryBuilder.PdbxNmrChemShiftExperimentBuilder(this); } public CategoryBuilder.PdbxNmrChemShiftRefBuilder enterPdbxNmrChemShiftRef() { return new CategoryBuilder.PdbxNmrChemShiftRefBuilder(this); } public CategoryBuilder.PdbxNmrChemShiftReferenceBuilder enterPdbxNmrChemShiftReference() { return new CategoryBuilder.PdbxNmrChemShiftReferenceBuilder(this); } public CategoryBuilder.PdbxNmrChemShiftSoftwareBuilder enterPdbxNmrChemShiftSoftware() { return new CategoryBuilder.PdbxNmrChemShiftSoftwareBuilder(this); } public CategoryBuilder.PdbxNmrConstraintFileBuilder enterPdbxNmrConstraintFile() { return new CategoryBuilder.PdbxNmrConstraintFileBuilder(this); } public CategoryBuilder.PdbxNmrSoftwareTaskBuilder enterPdbxNmrSoftwareTask() { return new CategoryBuilder.PdbxNmrSoftwareTaskBuilder(this); } public CategoryBuilder.PdbxNmrSpectralDimBuilder enterPdbxNmrSpectralDim() { return new CategoryBuilder.PdbxNmrSpectralDimBuilder(this); } public CategoryBuilder.PdbxNmrSpectralPeakListBuilder enterPdbxNmrSpectralPeakList() { return new CategoryBuilder.PdbxNmrSpectralPeakListBuilder(this); } public CategoryBuilder.PdbxNmrSpectralPeakSoftwareBuilder enterPdbxNmrSpectralPeakSoftware() { return new CategoryBuilder.PdbxNmrSpectralPeakSoftwareBuilder(this); } public CategoryBuilder.PdbxNmrSystematicChemShiftOffsetBuilder enterPdbxNmrSystematicChemShiftOffset() { return new CategoryBuilder.PdbxNmrSystematicChemShiftOffsetBuilder(this); } public CategoryBuilder.PdbxNmrUploadBuilder enterPdbxNmrUpload() { return new CategoryBuilder.PdbxNmrUploadBuilder(this); } public CategoryBuilder.PdbxAuditSupportBuilder enterPdbxAuditSupport() { return new CategoryBuilder.PdbxAuditSupportBuilder(this); } public CategoryBuilder.PdbxChemCompSubcomponentStructConnBuilder enterPdbxChemCompSubcomponentStructConn() { return new CategoryBuilder.PdbxChemCompSubcomponentStructConnBuilder(this); } public CategoryBuilder.PdbxChemCompSubcomponentEntityListBuilder enterPdbxChemCompSubcomponentEntityList() { return new CategoryBuilder.PdbxChemCompSubcomponentEntityListBuilder(this); } public CategoryBuilder.EntitySrcNatBuilder enterEntitySrcNat() { return new CategoryBuilder.EntitySrcNatBuilder(this); } public CategoryBuilder.EntitySrcGenBuilder enterEntitySrcGen() { return new CategoryBuilder.EntitySrcGenBuilder(this); } public CategoryBuilder.PdbxEntitySrcSynBuilder enterPdbxEntitySrcSyn() { return new CategoryBuilder.PdbxEntitySrcSynBuilder(this); } public CategoryBuilder.PdbxEntityPolyCompLinkListBuilder enterPdbxEntityPolyCompLinkList() { return new CategoryBuilder.PdbxEntityPolyCompLinkListBuilder(this); } public CategoryBuilder.PdbxLinkedEntityBuilder enterPdbxLinkedEntity() { return new CategoryBuilder.PdbxLinkedEntityBuilder(this); } public CategoryBuilder.PdbxLinkedEntityInstanceListBuilder enterPdbxLinkedEntityInstanceList() { return new CategoryBuilder.PdbxLinkedEntityInstanceListBuilder(this); } public CategoryBuilder.PdbxLinkedEntityListBuilder enterPdbxLinkedEntityList() { return new CategoryBuilder.PdbxLinkedEntityListBuilder(this); } public CategoryBuilder.PdbxLinkedEntityLinkListBuilder enterPdbxLinkedEntityLinkList() { return new CategoryBuilder.PdbxLinkedEntityLinkListBuilder(this); } public CategoryBuilder.PdbxEntityDescriptorBuilder enterPdbxEntityDescriptor() { return new CategoryBuilder.PdbxEntityDescriptorBuilder(this); } public CategoryBuilder.PdbxReferenceLinkedEntityBuilder enterPdbxReferenceLinkedEntity() { return new CategoryBuilder.PdbxReferenceLinkedEntityBuilder(this); } public CategoryBuilder.PdbxReferenceLinkedEntityCompListBuilder enterPdbxReferenceLinkedEntityCompList() { return new CategoryBuilder.PdbxReferenceLinkedEntityCompListBuilder(this); } public CategoryBuilder.PdbxReferenceLinkedEntityCompLinkBuilder enterPdbxReferenceLinkedEntityCompLink() { return new CategoryBuilder.PdbxReferenceLinkedEntityCompLinkBuilder(this); } public CategoryBuilder.PdbxReferenceLinkedEntityLinkBuilder enterPdbxReferenceLinkedEntityLink() { return new CategoryBuilder.PdbxReferenceLinkedEntityLinkBuilder(this); } public CategoryBuilder.PdbxRelatedExpDataSetBuilder enterPdbxRelatedExpDataSet() { return new CategoryBuilder.PdbxRelatedExpDataSetBuilder(this); } public CategoryBuilder.PdbxDatabaseStatusHistoryBuilder enterPdbxDatabaseStatusHistory() { return new CategoryBuilder.PdbxDatabaseStatusHistoryBuilder(this); } public CategoryBuilder.EmAssemblyBuilder enterEmAssembly() { return new CategoryBuilder.EmAssemblyBuilder(this); } public CategoryBuilder.EmEntityAssemblyBuilder enterEmEntityAssembly() { return new CategoryBuilder.EmEntityAssemblyBuilder(this); } public CategoryBuilder.EmVirusEntityBuilder enterEmVirusEntity() { return new CategoryBuilder.EmVirusEntityBuilder(this); } public CategoryBuilder.EmSamplePreparationBuilder enterEmSamplePreparation() { return new CategoryBuilder.EmSamplePreparationBuilder(this); } public CategoryBuilder.EmSampleSupportBuilder enterEmSampleSupport() { return new CategoryBuilder.EmSampleSupportBuilder(this); } public CategoryBuilder.EmBufferBuilder enterEmBuffer() { return new CategoryBuilder.EmBufferBuilder(this); } public CategoryBuilder.EmVitrificationBuilder enterEmVitrification() { return new CategoryBuilder.EmVitrificationBuilder(this); } public CategoryBuilder.EmImagingBuilder enterEmImaging() { return new CategoryBuilder.EmImagingBuilder(this); } public CategoryBuilder.EmDetectorBuilder enterEmDetector() { return new CategoryBuilder.EmDetectorBuilder(this); } public CategoryBuilder.EmImageScansBuilder enterEmImageScans() { return new CategoryBuilder.EmImageScansBuilder(this); } public CategoryBuilder.Em2dProjectionSelectionBuilder enterEm2dProjectionSelection() { return new CategoryBuilder.Em2dProjectionSelectionBuilder(this); } public CategoryBuilder.Em3dReconstructionBuilder enterEm3dReconstruction() { return new CategoryBuilder.Em3dReconstructionBuilder(this); } public CategoryBuilder.Em3dFittingBuilder enterEm3dFitting() { return new CategoryBuilder.Em3dFittingBuilder(this); } public CategoryBuilder.Em3dFittingListBuilder enterEm3dFittingList() { return new CategoryBuilder.Em3dFittingListBuilder(this); } public CategoryBuilder.EmHelicalEntityBuilder enterEmHelicalEntity() { return new CategoryBuilder.EmHelicalEntityBuilder(this); } public CategoryBuilder.EmExperimentBuilder enterEmExperiment() { return new CategoryBuilder.EmExperimentBuilder(this); } public CategoryBuilder.EmSingleParticleEntityBuilder enterEmSingleParticleEntity() { return new CategoryBuilder.EmSingleParticleEntityBuilder(this); } public CategoryBuilder.EmAdminBuilder enterEmAdmin() { return new CategoryBuilder.EmAdminBuilder(this); } public CategoryBuilder.EmAuthorListBuilder enterEmAuthorList() { return new CategoryBuilder.EmAuthorListBuilder(this); } public CategoryBuilder.EmDbReferenceBuilder enterEmDbReference() { return new CategoryBuilder.EmDbReferenceBuilder(this); } public CategoryBuilder.EmDbReferenceAuxiliaryBuilder enterEmDbReferenceAuxiliary() { return new CategoryBuilder.EmDbReferenceAuxiliaryBuilder(this); } public CategoryBuilder.EmDepuiBuilder enterEmDepui() { return new CategoryBuilder.EmDepuiBuilder(this); } public CategoryBuilder.EmObsoleteBuilder enterEmObsolete() { return new CategoryBuilder.EmObsoleteBuilder(this); } public CategoryBuilder.EmSupersedeBuilder enterEmSupersede() { return new CategoryBuilder.EmSupersedeBuilder(this); } public CategoryBuilder.EmEntityAssemblyMolwtBuilder enterEmEntityAssemblyMolwt() { return new CategoryBuilder.EmEntityAssemblyMolwtBuilder(this); } public CategoryBuilder.EmEntityAssemblyNaturalsourceBuilder enterEmEntityAssemblyNaturalsource() { return new CategoryBuilder.EmEntityAssemblyNaturalsourceBuilder(this); } public CategoryBuilder.EmEntityAssemblyRecombinantBuilder enterEmEntityAssemblyRecombinant() { return new CategoryBuilder.EmEntityAssemblyRecombinantBuilder(this); } public CategoryBuilder.EmVirusNaturalHostBuilder enterEmVirusNaturalHost() { return new CategoryBuilder.EmVirusNaturalHostBuilder(this); } public CategoryBuilder.EmVirusShellBuilder enterEmVirusShell() { return new CategoryBuilder.EmVirusShellBuilder(this); } public CategoryBuilder.EmSpecimenBuilder enterEmSpecimen() { return new CategoryBuilder.EmSpecimenBuilder(this); } public CategoryBuilder.EmEmbeddingBuilder enterEmEmbedding() { return new CategoryBuilder.EmEmbeddingBuilder(this); } public CategoryBuilder.EmFiducialMarkersBuilder enterEmFiducialMarkers() { return new CategoryBuilder.EmFiducialMarkersBuilder(this); } public CategoryBuilder.EmFocusedIonBeamBuilder enterEmFocusedIonBeam() { return new CategoryBuilder.EmFocusedIonBeamBuilder(this); } public CategoryBuilder.EmGridPretreatmentBuilder enterEmGridPretreatment() { return new CategoryBuilder.EmGridPretreatmentBuilder(this); } public CategoryBuilder.EmUltramicrotomyBuilder enterEmUltramicrotomy() { return new CategoryBuilder.EmUltramicrotomyBuilder(this); } public CategoryBuilder.EmHighPressureFreezingBuilder enterEmHighPressureFreezing() { return new CategoryBuilder.EmHighPressureFreezingBuilder(this); } public CategoryBuilder.EmShadowingBuilder enterEmShadowing() { return new CategoryBuilder.EmShadowingBuilder(this); } public CategoryBuilder.EmTomographySpecimenBuilder enterEmTomographySpecimen() { return new CategoryBuilder.EmTomographySpecimenBuilder(this); } public CategoryBuilder.EmCrystalFormationBuilder enterEmCrystalFormation() { return new CategoryBuilder.EmCrystalFormationBuilder(this); } public CategoryBuilder.EmStainingBuilder enterEmStaining() { return new CategoryBuilder.EmStainingBuilder(this); } public CategoryBuilder.EmSupportFilmBuilder enterEmSupportFilm() { return new CategoryBuilder.EmSupportFilmBuilder(this); } public CategoryBuilder.EmBufferComponentBuilder enterEmBufferComponent() { return new CategoryBuilder.EmBufferComponentBuilder(this); } public CategoryBuilder.EmDiffractionBuilder enterEmDiffraction() { return new CategoryBuilder.EmDiffractionBuilder(this); } public CategoryBuilder.EmDiffractionShellBuilder enterEmDiffractionShell() { return new CategoryBuilder.EmDiffractionShellBuilder(this); } public CategoryBuilder.EmDiffractionStatsBuilder enterEmDiffractionStats() { return new CategoryBuilder.EmDiffractionStatsBuilder(this); } public CategoryBuilder.EmTomographyBuilder enterEmTomography() { return new CategoryBuilder.EmTomographyBuilder(this); } public CategoryBuilder.EmImageRecordingBuilder enterEmImageRecording() { return new CategoryBuilder.EmImageRecordingBuilder(this); } public CategoryBuilder.EmImagingOpticsBuilder enterEmImagingOptics() { return new CategoryBuilder.EmImagingOpticsBuilder(this); } public CategoryBuilder.EmFinalClassificationBuilder enterEmFinalClassification() { return new CategoryBuilder.EmFinalClassificationBuilder(this); } public CategoryBuilder.EmStartModelBuilder enterEmStartModel() { return new CategoryBuilder.EmStartModelBuilder(this); } public CategoryBuilder.EmSoftwareBuilder enterEmSoftware() { return new CategoryBuilder.EmSoftwareBuilder(this); } public CategoryBuilder.EmEulerAngleAssignmentBuilder enterEmEulerAngleAssignment() { return new CategoryBuilder.EmEulerAngleAssignmentBuilder(this); } public CategoryBuilder.EmCtfCorrectionBuilder enterEmCtfCorrection() { return new CategoryBuilder.EmCtfCorrectionBuilder(this); } public CategoryBuilder.EmVolumeSelectionBuilder enterEmVolumeSelection() { return new CategoryBuilder.EmVolumeSelectionBuilder(this); } public CategoryBuilder.Em3dCrystalEntityBuilder enterEm3dCrystalEntity() { return new CategoryBuilder.Em3dCrystalEntityBuilder(this); } public CategoryBuilder.Em2dCrystalEntityBuilder enterEm2dCrystalEntity() { return new CategoryBuilder.Em2dCrystalEntityBuilder(this); } public CategoryBuilder.EmImageProcessingBuilder enterEmImageProcessing() { return new CategoryBuilder.EmImageProcessingBuilder(this); } public CategoryBuilder.EmParticleSelectionBuilder enterEmParticleSelection() { return new CategoryBuilder.EmParticleSelectionBuilder(this); } public CategoryBuilder.EmMapBuilder enterEmMap() { return new CategoryBuilder.EmMapBuilder(this); } public CategoryBuilder.EmFscCurveBuilder enterEmFscCurve() { return new CategoryBuilder.EmFscCurveBuilder(this); } public CategoryBuilder.EmInterpretFigureBuilder enterEmInterpretFigure() { return new CategoryBuilder.EmInterpretFigureBuilder(this); } public CategoryBuilder.EmLayerLinesBuilder enterEmLayerLines() { return new CategoryBuilder.EmLayerLinesBuilder(this); } public CategoryBuilder.EmStructureFactorsBuilder enterEmStructureFactors() { return new CategoryBuilder.EmStructureFactorsBuilder(this); } public CategoryBuilder.EmDepositorInfoBuilder enterEmDepositorInfo() { return new CategoryBuilder.EmDepositorInfoBuilder(this); } public CategoryBuilder.EmMapDepositorInfoBuilder enterEmMapDepositorInfo() { return new CategoryBuilder.EmMapDepositorInfoBuilder(this); } public CategoryBuilder.EmMaskDepositorInfoBuilder enterEmMaskDepositorInfo() { return new CategoryBuilder.EmMaskDepositorInfoBuilder(this); } public CategoryBuilder.EmFigureDepositorInfoBuilder enterEmFigureDepositorInfo() { return new CategoryBuilder.EmFigureDepositorInfoBuilder(this); } public CategoryBuilder.EmLayerLinesDepositorInfoBuilder enterEmLayerLinesDepositorInfo() { return new CategoryBuilder.EmLayerLinesDepositorInfoBuilder(this); } public CategoryBuilder.EmStructureFactorsDepositorInfoBuilder enterEmStructureFactorsDepositorInfo() { return new CategoryBuilder.EmStructureFactorsDepositorInfoBuilder(this); } public CategoryBuilder.PdbxSeqMapDepositorInfoBuilder enterPdbxSeqMapDepositorInfo() { return new CategoryBuilder.PdbxSeqMapDepositorInfoBuilder(this); } public CategoryBuilder.PdbxChemCompDepositorInfoBuilder enterPdbxChemCompDepositorInfo() { return new CategoryBuilder.PdbxChemCompDepositorInfoBuilder(this); } public CategoryBuilder.PdbxStructRefSeqDepositorInfoBuilder enterPdbxStructRefSeqDepositorInfo() { return new CategoryBuilder.PdbxStructRefSeqDepositorInfoBuilder(this); } public CategoryBuilder.PdbxStructRefSeqDifDepositorInfoBuilder enterPdbxStructRefSeqDifDepositorInfo() { return new CategoryBuilder.PdbxStructRefSeqDifDepositorInfoBuilder(this); } public CategoryBuilder.PdbxStructAssemblyPropDepositorInfoBuilder enterPdbxStructAssemblyPropDepositorInfo() { return new CategoryBuilder.PdbxStructAssemblyPropDepositorInfoBuilder(this); } public CategoryBuilder.PdbxStructAssemblyDepositorInfoBuilder enterPdbxStructAssemblyDepositorInfo() { return new CategoryBuilder.PdbxStructAssemblyDepositorInfoBuilder(this); } public CategoryBuilder.PdbxStructAssemblyGenDepositorInfoBuilder enterPdbxStructAssemblyGenDepositorInfo() { return new CategoryBuilder.PdbxStructAssemblyGenDepositorInfoBuilder(this); } public CategoryBuilder.PdbxStructOperListDepositorInfoBuilder enterPdbxStructOperListDepositorInfo() { return new CategoryBuilder.PdbxStructOperListDepositorInfoBuilder(this); } public CategoryBuilder.PdbxPointSymmetryDepositorInfoBuilder enterPdbxPointSymmetryDepositorInfo() { return new CategoryBuilder.PdbxPointSymmetryDepositorInfoBuilder(this); } public CategoryBuilder.PdbxHelicalSymmetryDepositorInfoBuilder enterPdbxHelicalSymmetryDepositorInfo() { return new CategoryBuilder.PdbxHelicalSymmetryDepositorInfoBuilder(this); } public CategoryBuilder.PdbxStructAssemblyAuthEvidenceDepositorInfoBuilder enterPdbxStructAssemblyAuthEvidenceDepositorInfo() { return new CategoryBuilder.PdbxStructAssemblyAuthEvidenceDepositorInfoBuilder(this); } public CategoryBuilder.PdbxSolventAtomSiteMappingBuilder enterPdbxSolventAtomSiteMapping() { return new CategoryBuilder.PdbxSolventAtomSiteMappingBuilder(this); } public CategoryBuilder.PdbxMoleculeFeaturesDepositorInfoBuilder enterPdbxMoleculeFeaturesDepositorInfo() { return new CategoryBuilder.PdbxMoleculeFeaturesDepositorInfoBuilder(this); } public CategoryBuilder.PdbxChemCompInstanceDepositorInfoBuilder enterPdbxChemCompInstanceDepositorInfo() { return new CategoryBuilder.PdbxChemCompInstanceDepositorInfoBuilder(this); } public CategoryBuilder.PdbxDepuiStatusFlagsBuilder enterPdbxDepuiStatusFlags() { return new CategoryBuilder.PdbxDepuiStatusFlagsBuilder(this); } public CategoryBuilder.PdbxDepuiUploadBuilder enterPdbxDepuiUpload() { return new CategoryBuilder.PdbxDepuiUploadBuilder(this); } public CategoryBuilder.PdbxDepuiValidationStatusFlagsBuilder enterPdbxDepuiValidationStatusFlags() { return new CategoryBuilder.PdbxDepuiValidationStatusFlagsBuilder(this); } public CategoryBuilder.PdbxChemCompUploadDepositorInfoBuilder enterPdbxChemCompUploadDepositorInfo() { return new CategoryBuilder.PdbxChemCompUploadDepositorInfoBuilder(this); } public CategoryBuilder.PdbxDepuiEntityStatusFlagsBuilder enterPdbxDepuiEntityStatusFlags() { return new CategoryBuilder.PdbxDepuiEntityStatusFlagsBuilder(this); } public CategoryBuilder.PdbxDepuiEntityFeaturesBuilder enterPdbxDepuiEntityFeatures() { return new CategoryBuilder.PdbxDepuiEntityFeaturesBuilder(this); } public CategoryBuilder.PdbxDepositionMessageInfoBuilder enterPdbxDepositionMessageInfo() { return new CategoryBuilder.PdbxDepositionMessageInfoBuilder(this); } public CategoryBuilder.PdbxDepositionMessageFileReferenceBuilder enterPdbxDepositionMessageFileReference() { return new CategoryBuilder.PdbxDepositionMessageFileReferenceBuilder(this); } public CategoryBuilder.PdbxDepuiEntryDetailsBuilder enterPdbxDepuiEntryDetails() { return new CategoryBuilder.PdbxDepuiEntryDetailsBuilder(this); } public CategoryBuilder.PdbxDataProcessingStatusBuilder enterPdbxDataProcessingStatus() { return new CategoryBuilder.PdbxDataProcessingStatusBuilder(this); } public CategoryBuilder.PdbxEntityInstanceFeatureBuilder enterPdbxEntityInstanceFeature() { return new CategoryBuilder.PdbxEntityInstanceFeatureBuilder(this); } public CategoryBuilder.PdbxEntitySrcGenDepositorInfoBuilder enterPdbxEntitySrcGenDepositorInfo() { return new CategoryBuilder.PdbxEntitySrcGenDepositorInfoBuilder(this); } public CategoryBuilder.PdbxChemCompModelBuilder enterPdbxChemCompModel() { return new CategoryBuilder.PdbxChemCompModelBuilder(this); } public CategoryBuilder.PdbxChemCompModelAtomBuilder enterPdbxChemCompModelAtom() { return new CategoryBuilder.PdbxChemCompModelAtomBuilder(this); } public CategoryBuilder.PdbxChemCompModelBondBuilder enterPdbxChemCompModelBond() { return new CategoryBuilder.PdbxChemCompModelBondBuilder(this); } public CategoryBuilder.PdbxChemCompModelFeatureBuilder enterPdbxChemCompModelFeature() { return new CategoryBuilder.PdbxChemCompModelFeatureBuilder(this); } public CategoryBuilder.PdbxChemCompModelDescriptorBuilder enterPdbxChemCompModelDescriptor() { return new CategoryBuilder.PdbxChemCompModelDescriptorBuilder(this); } public CategoryBuilder.PdbxChemCompModelAuditBuilder enterPdbxChemCompModelAudit() { return new CategoryBuilder.PdbxChemCompModelAuditBuilder(this); } public CategoryBuilder.PdbxChemCompModelReferenceBuilder enterPdbxChemCompModelReference() { return new CategoryBuilder.PdbxChemCompModelReferenceBuilder(this); } public CategoryBuilder.PdbxViewCategoryGroupBuilder enterPdbxViewCategoryGroup() { return new CategoryBuilder.PdbxViewCategoryGroupBuilder(this); } public CategoryBuilder.PdbxViewCategoryBuilder enterPdbxViewCategory() { return new CategoryBuilder.PdbxViewCategoryBuilder(this); } public CategoryBuilder.PdbxViewItemBuilder enterPdbxViewItem() { return new CategoryBuilder.PdbxViewItemBuilder(this); } public CategoryBuilder.PdbxCoordBuilder enterPdbxCoord() { return new CategoryBuilder.PdbxCoordBuilder(this); } public CategoryBuilder.PdbxConnectBuilder enterPdbxConnect() { return new CategoryBuilder.PdbxConnectBuilder(this); } public CategoryBuilder.PdbxConnectTypeBuilder enterPdbxConnectType() { return new CategoryBuilder.PdbxConnectTypeBuilder(this); } public CategoryBuilder.PdbxConnectModificationBuilder enterPdbxConnectModification() { return new CategoryBuilder.PdbxConnectModificationBuilder(this); } public CategoryBuilder.PdbxConnectAtomBuilder enterPdbxConnectAtom() { return new CategoryBuilder.PdbxConnectAtomBuilder(this); } public CategoryBuilder.PdbxDatabasePDBMasterBuilder enterPdbxDatabasePDBMaster() { return new CategoryBuilder.PdbxDatabasePDBMasterBuilder(this); } public CategoryBuilder.PdbxDatabasePdbOmitBuilder enterPdbxDatabasePdbOmit() { return new CategoryBuilder.PdbxDatabasePdbOmitBuilder(this); } public CategoryBuilder.PdbxDbrefBuilder enterPdbxDbref() { return new CategoryBuilder.PdbxDbrefBuilder(this); } public CategoryBuilder.PdbxDrugInfoBuilder enterPdbxDrugInfo() { return new CategoryBuilder.PdbxDrugInfoBuilder(this); } public CategoryBuilder.PdbxInhibitorInfoBuilder enterPdbxInhibitorInfo() { return new CategoryBuilder.PdbxInhibitorInfoBuilder(this); } public CategoryBuilder.PdbxIonInfoBuilder enterPdbxIonInfo() { return new CategoryBuilder.PdbxIonInfoBuilder(this); } public CategoryBuilder.PdbxHybridBuilder enterPdbxHybrid() { return new CategoryBuilder.PdbxHybridBuilder(this); } public CategoryBuilder.PdbxNaStrandInfoBuilder enterPdbxNaStrandInfo() { return new CategoryBuilder.PdbxNaStrandInfoBuilder(this); } public CategoryBuilder.PdbxNonstandardListBuilder enterPdbxNonstandardList() { return new CategoryBuilder.PdbxNonstandardListBuilder(this); } public CategoryBuilder.PdbxPdbCompndBuilder enterPdbxPdbCompnd() { return new CategoryBuilder.PdbxPdbCompndBuilder(this); } public CategoryBuilder.PdbxPdbSourceBuilder enterPdbxPdbSource() { return new CategoryBuilder.PdbxPdbSourceBuilder(this); } public CategoryBuilder.PdbxProteinInfoBuilder enterPdbxProteinInfo() { return new CategoryBuilder.PdbxProteinInfoBuilder(this); } public CategoryBuilder.PdbxSolventInfoBuilder enterPdbxSolventInfo() { return new CategoryBuilder.PdbxSolventInfoBuilder(this); } public CategoryBuilder.PdbxSourceBuilder enterPdbxSource() { return new CategoryBuilder.PdbxSourceBuilder(this); } public CategoryBuilder.PdbxStructBiolFuncBuilder enterPdbxStructBiolFunc() { return new CategoryBuilder.PdbxStructBiolFuncBuilder(this); } public CategoryBuilder.PdbxStructPackGenBuilder enterPdbxStructPackGen() { return new CategoryBuilder.PdbxStructPackGenBuilder(this); } public CategoryBuilder.PdbxTrnaInfoBuilder enterPdbxTrnaInfo() { return new CategoryBuilder.PdbxTrnaInfoBuilder(this); } public CategoryBuilder.PdbxUnpairBuilder enterPdbxUnpair() { return new CategoryBuilder.PdbxUnpairBuilder(this); } public CategoryBuilder.PdbxRefineLsRestrNcsBuilder enterPdbxRefineLsRestrNcs() { return new CategoryBuilder.PdbxRefineLsRestrNcsBuilder(this); } public CategoryBuilder.PdbxStructNcsVirusGenBuilder enterPdbxStructNcsVirusGen() { return new CategoryBuilder.PdbxStructNcsVirusGenBuilder(this); } public CategoryBuilder.PdbxSequenceAnnotationBuilder enterPdbxSequenceAnnotation() { return new CategoryBuilder.PdbxSequenceAnnotationBuilder(this); } public CategoryBuilder.PdbxPostProcessDetailsBuilder enterPdbxPostProcessDetails() { return new CategoryBuilder.PdbxPostProcessDetailsBuilder(this); } public CategoryBuilder.PdbxPostProcessStatusBuilder enterPdbxPostProcessStatus() { return new CategoryBuilder.PdbxPostProcessStatusBuilder(this); } public CategoryBuilder.PdbxStructLinkBuilder enterPdbxStructLink() { return new CategoryBuilder.PdbxStructLinkBuilder(this); } public CategoryBuilder.PdbxMissingResidueListBuilder enterPdbxMissingResidueList() { return new CategoryBuilder.PdbxMissingResidueListBuilder(this); } public CategoryBuilder.PdbxDataProcessingCellBuilder enterPdbxDataProcessingCell() { return new CategoryBuilder.PdbxDataProcessingCellBuilder(this); } public CategoryBuilder.PdbxDataProcessingReflnsBuilder enterPdbxDataProcessingReflns() { return new CategoryBuilder.PdbxDataProcessingReflnsBuilder(this); } public CategoryBuilder.PdbxDataProcessingDetectorBuilder enterPdbxDataProcessingDetector() { return new CategoryBuilder.PdbxDataProcessingDetectorBuilder(this); } public CategoryBuilder.PdbxChemCompNonstandardBuilder enterPdbxChemCompNonstandard() { return new CategoryBuilder.PdbxChemCompNonstandardBuilder(this); } public CategoryBuilder.PdbxEntityPolyProteinClassBuilder enterPdbxEntityPolyProteinClass() { return new CategoryBuilder.PdbxEntityPolyProteinClassBuilder(this); } public CategoryBuilder.PdbxEntityNameTaxonomyTreeBuilder enterPdbxEntityNameTaxonomyTree() { return new CategoryBuilder.PdbxEntityNameTaxonomyTreeBuilder(this); } public CategoryBuilder.PdbxEntityNameTaxonomyBuilder enterPdbxEntityNameTaxonomy() { return new CategoryBuilder.PdbxEntityNameTaxonomyBuilder(this); } public CategoryBuilder.PdbxEntityNameInstanceBuilder enterPdbxEntityNameInstance() { return new CategoryBuilder.PdbxEntityNameInstanceBuilder(this); } public CategoryBuilder.PdbxTableinfoBuilder enterPdbxTableinfo() { return new CategoryBuilder.PdbxTableinfoBuilder(this); } public CategoryBuilder.PdbxColumninfoBuilder enterPdbxColumninfo() { return new CategoryBuilder.PdbxColumninfoBuilder(this); } public CategoryBuilder.PdbxValAngleBuilder enterPdbxValAngle() { return new CategoryBuilder.PdbxValAngleBuilder(this); } public CategoryBuilder.PdbxValBondBuilder enterPdbxValBond() { return new CategoryBuilder.PdbxValBondBuilder(this); } public CategoryBuilder.PdbxValContactBuilder enterPdbxValContact() { return new CategoryBuilder.PdbxValContactBuilder(this); } public CategoryBuilder.PdbxValSymContactBuilder enterPdbxValSymContact() { return new CategoryBuilder.PdbxValSymContactBuilder(this); } public CategoryBuilder.PdbxRmchOutlierBuilder enterPdbxRmchOutlier() { return new CategoryBuilder.PdbxRmchOutlierBuilder(this); } public CategoryBuilder.PdbxMissingAtomPolyBuilder enterPdbxMissingAtomPoly() { return new CategoryBuilder.PdbxMissingAtomPolyBuilder(this); } public CategoryBuilder.PdbxMissingAtomNonpolyBuilder enterPdbxMissingAtomNonpoly() { return new CategoryBuilder.PdbxMissingAtomNonpolyBuilder(this); } public CategoryBuilder.PdbxValChiralBuilder enterPdbxValChiral() { return new CategoryBuilder.PdbxValChiralBuilder(this); } public CategoryBuilder.PdbxAtlasBuilder enterPdbxAtlas() { return new CategoryBuilder.PdbxAtlasBuilder(this); } public CategoryBuilder.PdbxSummaryFlagsBuilder enterPdbxSummaryFlags() { return new CategoryBuilder.PdbxSummaryFlagsBuilder(this); } public CategoryBuilder.PdbxEntityFuncBindModeBuilder enterPdbxEntityFuncBindMode() { return new CategoryBuilder.PdbxEntityFuncBindModeBuilder(this); } public CategoryBuilder.PdbxEntityFuncEnzymeBuilder enterPdbxEntityFuncEnzyme() { return new CategoryBuilder.PdbxEntityFuncEnzymeBuilder(this); } public CategoryBuilder.PdbxEntityFuncRegulatoryBuilder enterPdbxEntityFuncRegulatory() { return new CategoryBuilder.PdbxEntityFuncRegulatoryBuilder(this); } public CategoryBuilder.PdbxEntityFuncStructuralBuilder enterPdbxEntityFuncStructural() { return new CategoryBuilder.PdbxEntityFuncStructuralBuilder(this); } public CategoryBuilder.PdbxEntityFuncOtherBuilder enterPdbxEntityFuncOther() { return new CategoryBuilder.PdbxEntityFuncOtherBuilder(this); } public CategoryBuilder.PdbxEntityPolyDomainBuilder enterPdbxEntityPolyDomain() { return new CategoryBuilder.PdbxEntityPolyDomainBuilder(this); } public CategoryBuilder.PdbxNaStructKeywdsBuilder enterPdbxNaStructKeywds() { return new CategoryBuilder.PdbxNaStructKeywdsBuilder(this); } public CategoryBuilder.PdbxEntityPolyNaTypeBuilder enterPdbxEntityPolyNaType() { return new CategoryBuilder.PdbxEntityPolyNaTypeBuilder(this); } public CategoryBuilder.PdbxEntityPolyNaNonstandardBuilder enterPdbxEntityPolyNaNonstandard() { return new CategoryBuilder.PdbxEntityPolyNaNonstandardBuilder(this); } public CategoryBuilder.PdbxVirtualAngleBuilder enterPdbxVirtualAngle() { return new CategoryBuilder.PdbxVirtualAngleBuilder(this); } public CategoryBuilder.PdbxVirtualBondBuilder enterPdbxVirtualBond() { return new CategoryBuilder.PdbxVirtualBondBuilder(this); } public CategoryBuilder.PdbxVirtualTorsionBuilder enterPdbxVirtualTorsion() { return new CategoryBuilder.PdbxVirtualTorsionBuilder(this); } public CategoryBuilder.PdbxSequencePatternBuilder enterPdbxSequencePattern() { return new CategoryBuilder.PdbxSequencePatternBuilder(this); } public CategoryBuilder.PdbxStereochemistryBuilder enterPdbxStereochemistry() { return new CategoryBuilder.PdbxStereochemistryBuilder(this); } public CategoryBuilder.PdbxRmsDevsCovalentBuilder enterPdbxRmsDevsCovalent() { return new CategoryBuilder.PdbxRmsDevsCovalentBuilder(this); } public CategoryBuilder.PdbxRmsDevsCovByMonomerBuilder enterPdbxRmsDevsCovByMonomer() { return new CategoryBuilder.PdbxRmsDevsCovByMonomerBuilder(this); } public CategoryBuilder.PdbxSugarPhosphateGeometryBuilder enterPdbxSugarPhosphateGeometry() { return new CategoryBuilder.PdbxSugarPhosphateGeometryBuilder(this); } public CategoryBuilder.PdbxNmrComputingBuilder enterPdbxNmrComputing() { return new CategoryBuilder.PdbxNmrComputingBuilder(this); } public CategoryBuilder.PdbxAuditConformExtensionBuilder enterPdbxAuditConformExtension() { return new CategoryBuilder.PdbxAuditConformExtensionBuilder(this); } public CategoryBuilder.PdbxDccMapmanBuilder enterPdbxDccMapman() { return new CategoryBuilder.PdbxDccMapmanBuilder(this); } public CategoryBuilder.PdbxDccRsccMapmanBuilder enterPdbxDccRsccMapman() { return new CategoryBuilder.PdbxDccRsccMapmanBuilder(this); } public CategoryBuilder.PdbxDccRsccMapmanOverallBuilder enterPdbxDccRsccMapmanOverall() { return new CategoryBuilder.PdbxDccRsccMapmanOverallBuilder(this); } public CategoryBuilder.PdbxDccDensityBuilder enterPdbxDccDensity() { return new CategoryBuilder.PdbxDccDensityBuilder(this); } public CategoryBuilder.PdbxDccGeometryBuilder enterPdbxDccGeometry() { return new CategoryBuilder.PdbxDccGeometryBuilder(this); } public CategoryBuilder.PdbxDccDensityCorrBuilder enterPdbxDccDensityCorr() { return new CategoryBuilder.PdbxDccDensityCorrBuilder(this); } public CategoryBuilder.PdbxDccMapBuilder enterPdbxDccMap() { return new CategoryBuilder.PdbxDccMapBuilder(this); } public CategoryBuilder.PdbxDepositGroupBuilder enterPdbxDepositGroup() { return new CategoryBuilder.PdbxDepositGroupBuilder(this); } public CategoryBuilder.PdbxDepositGroupIndexBuilder enterPdbxDepositGroupIndex() { return new CategoryBuilder.PdbxDepositGroupIndexBuilder(this); } public CategoryBuilder.PdbxStructAssemblyAuthEvidenceBuilder enterPdbxStructAssemblyAuthEvidence() { return new CategoryBuilder.PdbxStructAssemblyAuthEvidenceBuilder(this); } public CategoryBuilder.PdbxStructAssemblyAuthClassificationBuilder enterPdbxStructAssemblyAuthClassification() { return new CategoryBuilder.PdbxStructAssemblyAuthClassificationBuilder(this); } public CategoryBuilder.PdbxCrystalAlignmentBuilder enterPdbxCrystalAlignment() { return new CategoryBuilder.PdbxCrystalAlignmentBuilder(this); } public CategoryBuilder.PdbxAuditRevisionHistoryBuilder enterPdbxAuditRevisionHistory() { return new CategoryBuilder.PdbxAuditRevisionHistoryBuilder(this); } public CategoryBuilder.PdbxAuditRevisionGroupBuilder enterPdbxAuditRevisionGroup() { return new CategoryBuilder.PdbxAuditRevisionGroupBuilder(this); } public CategoryBuilder.PdbxAuditRevisionCategoryBuilder enterPdbxAuditRevisionCategory() { return new CategoryBuilder.PdbxAuditRevisionCategoryBuilder(this); } public CategoryBuilder.PdbxAuditRevisionDetailsBuilder enterPdbxAuditRevisionDetails() { return new CategoryBuilder.PdbxAuditRevisionDetailsBuilder(this); } public CategoryBuilder.PdbxAuditRevisionItemBuilder enterPdbxAuditRevisionItem() { return new CategoryBuilder.PdbxAuditRevisionItemBuilder(this); } public CategoryBuilder.PdbxSupportingExpDataSetBuilder enterPdbxSupportingExpDataSet() { return new CategoryBuilder.PdbxSupportingExpDataSetBuilder(this); } public CategoryBuilder.PdbxSerialCrystallographyMeasurementBuilder enterPdbxSerialCrystallographyMeasurement() { return new CategoryBuilder.PdbxSerialCrystallographyMeasurementBuilder(this); } public CategoryBuilder.PdbxSerialCrystallographySampleDeliveryBuilder enterPdbxSerialCrystallographySampleDelivery() { return new CategoryBuilder.PdbxSerialCrystallographySampleDeliveryBuilder(this); } public CategoryBuilder.PdbxSerialCrystallographySampleDeliveryInjectionBuilder enterPdbxSerialCrystallographySampleDeliveryInjection() { return new CategoryBuilder.PdbxSerialCrystallographySampleDeliveryInjectionBuilder(this); } public CategoryBuilder.PdbxSerialCrystallographySampleDeliveryFixedTargetBuilder enterPdbxSerialCrystallographySampleDeliveryFixedTarget() { return new CategoryBuilder.PdbxSerialCrystallographySampleDeliveryFixedTargetBuilder(this); } public CategoryBuilder.PdbxSerialCrystallographyDataReductionBuilder enterPdbxSerialCrystallographyDataReduction() { return new CategoryBuilder.PdbxSerialCrystallographyDataReductionBuilder(this); } public CategoryBuilder.PdbxChemCompSynonymsBuilder enterPdbxChemCompSynonyms() { return new CategoryBuilder.PdbxChemCompSynonymsBuilder(this); } public CategoryBuilder.PdbxChemCompRelatedBuilder enterPdbxChemCompRelated() { return new CategoryBuilder.PdbxChemCompRelatedBuilder(this); } public CategoryBuilder.PdbxChemCompAtomRelatedBuilder enterPdbxChemCompAtomRelated() { return new CategoryBuilder.PdbxChemCompAtomRelatedBuilder(this); } public CategoryBuilder.PdbxEntityBranchListBuilder enterPdbxEntityBranchList() { return new CategoryBuilder.PdbxEntityBranchListBuilder(this); } public CategoryBuilder.PdbxEntityBranchLinkBuilder enterPdbxEntityBranchLink() { return new CategoryBuilder.PdbxEntityBranchLinkBuilder(this); } public CategoryBuilder.PdbxEntityBranchBuilder enterPdbxEntityBranch() { return new CategoryBuilder.PdbxEntityBranchBuilder(this); } public CategoryBuilder.PdbxBranchSchemeBuilder enterPdbxBranchScheme() { return new CategoryBuilder.PdbxBranchSchemeBuilder(this); } public CategoryBuilder.IhmStartingModelDetailsBuilder enterIhmStartingModelDetails() { return new CategoryBuilder.IhmStartingModelDetailsBuilder(this); } public CategoryBuilder.IhmStartingComparativeModelsBuilder enterIhmStartingComparativeModels() { return new CategoryBuilder.IhmStartingComparativeModelsBuilder(this); } public CategoryBuilder.IhmStartingComputationalModelsBuilder enterIhmStartingComputationalModels() { return new CategoryBuilder.IhmStartingComputationalModelsBuilder(this); } public CategoryBuilder.IhmStartingModelSeqDifBuilder enterIhmStartingModelSeqDif() { return new CategoryBuilder.IhmStartingModelSeqDifBuilder(this); } public CategoryBuilder.IhmModelRepresentationBuilder enterIhmModelRepresentation() { return new CategoryBuilder.IhmModelRepresentationBuilder(this); } public CategoryBuilder.IhmStructAssemblyBuilder enterIhmStructAssembly() { return new CategoryBuilder.IhmStructAssemblyBuilder(this); } public CategoryBuilder.IhmStructAssemblyDetailsBuilder enterIhmStructAssemblyDetails() { return new CategoryBuilder.IhmStructAssemblyDetailsBuilder(this); } public CategoryBuilder.IhmStructAssemblyClassListBuilder enterIhmStructAssemblyClassList() { return new CategoryBuilder.IhmStructAssemblyClassListBuilder(this); } public CategoryBuilder.IhmStructAssemblyClassBuilder enterIhmStructAssemblyClass() { return new CategoryBuilder.IhmStructAssemblyClassBuilder(this); } public CategoryBuilder.IhmModelingProtocolBuilder enterIhmModelingProtocol() { return new CategoryBuilder.IhmModelingProtocolBuilder(this); } public CategoryBuilder.IhmMultiStateModelingBuilder enterIhmMultiStateModeling() { return new CategoryBuilder.IhmMultiStateModelingBuilder(this); } public CategoryBuilder.IhmOrderedEnsembleBuilder enterIhmOrderedEnsemble() { return new CategoryBuilder.IhmOrderedEnsembleBuilder(this); } public CategoryBuilder.IhmModelingPostProcessBuilder enterIhmModelingPostProcess() { return new CategoryBuilder.IhmModelingPostProcessBuilder(this); } public CategoryBuilder.IhmEnsembleInfoBuilder enterIhmEnsembleInfo() { return new CategoryBuilder.IhmEnsembleInfoBuilder(this); } public CategoryBuilder.IhmModelListBuilder enterIhmModelList() { return new CategoryBuilder.IhmModelListBuilder(this); } public CategoryBuilder.IhmModelRepresentativeBuilder enterIhmModelRepresentative() { return new CategoryBuilder.IhmModelRepresentativeBuilder(this); } public CategoryBuilder.IhmDatasetListBuilder enterIhmDatasetList() { return new CategoryBuilder.IhmDatasetListBuilder(this); } public CategoryBuilder.IhmDatasetGroupBuilder enterIhmDatasetGroup() { return new CategoryBuilder.IhmDatasetGroupBuilder(this); } public CategoryBuilder.IhmRelatedDatasetsBuilder enterIhmRelatedDatasets() { return new CategoryBuilder.IhmRelatedDatasetsBuilder(this); } public CategoryBuilder.IhmDatasetRelatedDbReferenceBuilder enterIhmDatasetRelatedDbReference() { return new CategoryBuilder.IhmDatasetRelatedDbReferenceBuilder(this); } public CategoryBuilder.IhmExternalReferenceInfoBuilder enterIhmExternalReferenceInfo() { return new CategoryBuilder.IhmExternalReferenceInfoBuilder(this); } public CategoryBuilder.IhmExternalFilesBuilder enterIhmExternalFiles() { return new CategoryBuilder.IhmExternalFilesBuilder(this); } public CategoryBuilder.IhmDatasetExternalReferenceBuilder enterIhmDatasetExternalReference() { return new CategoryBuilder.IhmDatasetExternalReferenceBuilder(this); } public CategoryBuilder.IhmLocalizationDensityFilesBuilder enterIhmLocalizationDensityFiles() { return new CategoryBuilder.IhmLocalizationDensityFilesBuilder(this); } public CategoryBuilder.IhmPredictedContactRestraintBuilder enterIhmPredictedContactRestraint() { return new CategoryBuilder.IhmPredictedContactRestraintBuilder(this); } public CategoryBuilder.IhmHydroxylRadicalFpRestraintBuilder enterIhmHydroxylRadicalFpRestraint() { return new CategoryBuilder.IhmHydroxylRadicalFpRestraintBuilder(this); } public CategoryBuilder.IhmCrossLinkListBuilder enterIhmCrossLinkList() { return new CategoryBuilder.IhmCrossLinkListBuilder(this); } public CategoryBuilder.IhmCrossLinkRestraintBuilder enterIhmCrossLinkRestraint() { return new CategoryBuilder.IhmCrossLinkRestraintBuilder(this); } public CategoryBuilder.IhmCrossLinkResultBuilder enterIhmCrossLinkResult() { return new CategoryBuilder.IhmCrossLinkResultBuilder(this); } public CategoryBuilder.IhmCrossLinkResultParametersBuilder enterIhmCrossLinkResultParameters() { return new CategoryBuilder.IhmCrossLinkResultParametersBuilder(this); } public CategoryBuilder.Ihm2demClassAverageRestraintBuilder enterIhm2demClassAverageRestraint() { return new CategoryBuilder.Ihm2demClassAverageRestraintBuilder(this); } public CategoryBuilder.Ihm2demClassAverageFittingBuilder enterIhm2demClassAverageFitting() { return new CategoryBuilder.Ihm2demClassAverageFittingBuilder(this); } public CategoryBuilder.Ihm3demRestraintBuilder enterIhm3demRestraint() { return new CategoryBuilder.Ihm3demRestraintBuilder(this); } public CategoryBuilder.IhmSasRestraintBuilder enterIhmSasRestraint() { return new CategoryBuilder.IhmSasRestraintBuilder(this); } public CategoryBuilder.IhmStartingModelCoordBuilder enterIhmStartingModelCoord() { return new CategoryBuilder.IhmStartingModelCoordBuilder(this); } public CategoryBuilder.IhmSphereObjSiteBuilder enterIhmSphereObjSite() { return new CategoryBuilder.IhmSphereObjSiteBuilder(this); } public CategoryBuilder.IhmGaussianObjSiteBuilder enterIhmGaussianObjSite() { return new CategoryBuilder.IhmGaussianObjSiteBuilder(this); } public CategoryBuilder.IhmGaussianObjEnsembleBuilder enterIhmGaussianObjEnsemble() { return new CategoryBuilder.IhmGaussianObjEnsembleBuilder(this); } public CategoryBuilder.IhmResiduesNotModeledBuilder enterIhmResiduesNotModeled() { return new CategoryBuilder.IhmResiduesNotModeledBuilder(this); } public CategoryBuilder.IhmFeatureListBuilder enterIhmFeatureList() { return new CategoryBuilder.IhmFeatureListBuilder(this); } public CategoryBuilder.IhmPseudoSiteFeatureBuilder enterIhmPseudoSiteFeature() { return new CategoryBuilder.IhmPseudoSiteFeatureBuilder(this); } public CategoryBuilder.IhmPolyAtomFeatureBuilder enterIhmPolyAtomFeature() { return new CategoryBuilder.IhmPolyAtomFeatureBuilder(this); } public CategoryBuilder.IhmPolyResidueFeatureBuilder enterIhmPolyResidueFeature() { return new CategoryBuilder.IhmPolyResidueFeatureBuilder(this); } public CategoryBuilder.IhmNonPolyFeatureBuilder enterIhmNonPolyFeature() { return new CategoryBuilder.IhmNonPolyFeatureBuilder(this); } public CategoryBuilder.IhmInterfaceResidueFeatureBuilder enterIhmInterfaceResidueFeature() { return new CategoryBuilder.IhmInterfaceResidueFeatureBuilder(this); } public CategoryBuilder.IhmDerivedDistanceRestraintBuilder enterIhmDerivedDistanceRestraint() { return new CategoryBuilder.IhmDerivedDistanceRestraintBuilder(this); } public CategoryBuilder.IhmGeometricObjectListBuilder enterIhmGeometricObjectList() { return new CategoryBuilder.IhmGeometricObjectListBuilder(this); } public CategoryBuilder.IhmGeometricObjectCenterBuilder enterIhmGeometricObjectCenter() { return new CategoryBuilder.IhmGeometricObjectCenterBuilder(this); } public CategoryBuilder.IhmGeometricObjectTransformationBuilder enterIhmGeometricObjectTransformation() { return new CategoryBuilder.IhmGeometricObjectTransformationBuilder(this); } public CategoryBuilder.IhmGeometricObjectSphereBuilder enterIhmGeometricObjectSphere() { return new CategoryBuilder.IhmGeometricObjectSphereBuilder(this); } public CategoryBuilder.IhmGeometricObjectTorusBuilder enterIhmGeometricObjectTorus() { return new CategoryBuilder.IhmGeometricObjectTorusBuilder(this); } public CategoryBuilder.IhmGeometricObjectHalfTorusBuilder enterIhmGeometricObjectHalfTorus() { return new CategoryBuilder.IhmGeometricObjectHalfTorusBuilder(this); } public CategoryBuilder.IhmGeometricObjectAxisBuilder enterIhmGeometricObjectAxis() { return new CategoryBuilder.IhmGeometricObjectAxisBuilder(this); } public CategoryBuilder.IhmGeometricObjectPlaneBuilder enterIhmGeometricObjectPlane() { return new CategoryBuilder.IhmGeometricObjectPlaneBuilder(this); } public CategoryBuilder.IhmGeometricObjectDistanceRestraintBuilder enterIhmGeometricObjectDistanceRestraint() { return new CategoryBuilder.IhmGeometricObjectDistanceRestraintBuilder(this); } }
package com.jyh.main.modle; public class User { private String username; private String password; private String name; private String nikeName; private String reMark; private String icoPath; private String summarise; private String age; private String r_id; private String p_id; private String s_id; private String pos_id; public String getPassWord() { return password; } public void setPassWord(String passWord) { this.password = passWord; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNikeName() { return nikeName; } public void setNikeName(String nikeName) { this.nikeName = nikeName; } public String getReMark() { return reMark; } public void setReMark(String reMark) { this.reMark = reMark; } public String getIcoPath() { return icoPath; } public void setIcoPath(String icoPath) { this.icoPath = icoPath; } public String getSummarise() { return summarise; } public void setSummarise(String summarise) { this.summarise = summarise; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getR_id() { return r_id; } public void setR_id(String r_id) { this.r_id = r_id; } public String getS_id() { return s_id; } public void setS_id(String s_id) { this.s_id = s_id; } public String getPos_id() { return pos_id; } public void setPos_id(String pos_id) { this.pos_id = pos_id; } }
/* * Non numeric Exception * * Version 1.0 * * September 28, 2017 * * Copyright © 2017 Jacy Mark, CMPUT301, University of Alberta - All Rights Reserved. * You may use, distribute, or modify this code under terms and conditions of the Code of Student Behavior at University of Alberta. * You can find a copy of the license in this project. Otherwise please contact contact@abc.ca */ package com.example.jmark.jmark_countbook; /** * Created by jmark on 2017-09-29. */ public class counterNonNumeric extends Exception { }
package gov.sequarius; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FuckaaoApplication { public static void main(String[] args) { SpringApplication.run(AAOClientApplication.class, args); } }
// // 이 파일은 JAXB(JavaTM Architecture for XML Binding) 참조 구현 2.2.6 버전을 통해 생성되었습니다. // <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>를 참조하십시오. // 이 파일을 수정하면 소스 스키마를 재컴파일할 때 수정 사항이 손실됩니다. // 생성 날짜: 2012.10.05 시간 10:52:30 AM KST // package com.athena.chameleon.engine.entity.xml.application.weblogic.v8_1; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "roleName", "principalName" }) @XmlRootElement(name = "security-role-assignment") public class SecurityRoleAssignment { @XmlElement(name = "role-name", required = true) protected String roleName; @XmlElement(name = "principal-name", required = true) protected List<PrincipalName> principalName; /** * roleName 속성의 값을 가져옵니다. * * @return * possible object is * {@link String } * */ public String getRoleName() { return roleName; } /** * roleName 속성의 값을 설정합니다. * * @param value * allowed object is * {@link String } * */ public void setRoleName(String value) { this.roleName = value; } /** * Gets the value of the principalName property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the principalName property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPrincipalName().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PrincipalName } * * */ public List<PrincipalName> getPrincipalName() { if (principalName == null) { principalName = new ArrayList<PrincipalName>(); } return this.principalName; } }
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.model.application.provider; import com.yahoo.component.Version; import com.yahoo.component.Vtag; import com.yahoo.config.application.ConfigDefinitionDir; import com.yahoo.config.application.Xml; import com.yahoo.config.application.XmlPreProcessor; import com.yahoo.config.application.api.ApplicationFile; import com.yahoo.config.application.api.ApplicationMetaData; import com.yahoo.config.application.api.ApplicationPackage; import com.yahoo.config.application.api.ComponentInfo; import com.yahoo.config.application.api.DeployLogger; import com.yahoo.config.application.api.UnparsedConfigDefinition; import com.yahoo.config.codegen.DefParser; import com.yahoo.config.model.application.AbstractApplicationPackage; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.ApplicationName; import com.yahoo.config.provision.InstanceName; import com.yahoo.config.provision.TenantName; import com.yahoo.config.provision.Zone; import com.yahoo.io.HexDump; import com.yahoo.io.IOUtils; import com.yahoo.io.reader.NamedReader; import com.yahoo.path.Path; import com.yahoo.text.Utf8; import com.yahoo.vespa.config.ConfigDefinition; import com.yahoo.vespa.config.ConfigDefinitionBuilder; import com.yahoo.vespa.config.ConfigDefinitionKey; import com.yahoo.vespa.config.util.ConfigUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.nio.file.Files; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.BiFunction; import java.util.logging.Level; import java.util.logging.Logger; import static com.yahoo.text.Lowercase.toLowerCase; /** * Application package derived from local files, i.e. during deploy. * Construct using {@link com.yahoo.config.model.application.provider.FilesApplicationPackage#fromFile(java.io.File)} or * {@link com.yahoo.config.model.application.provider.FilesApplicationPackage#fromFileWithDeployData(java.io.File, DeployData)}. * * @author Vegard Havdal */ public class FilesApplicationPackage extends AbstractApplicationPackage { /** * The name of the subdirectory (below the original application package root) * where a preprocessed version of this application package is stored. * As it happens, the config model is first created with an application package in this subdirectory, * and later backed by an application package which is not in this subdirectory. * To enable model code to correct for this, this constant must be publicly known. * * All of this stuff is Very Unfortunate and should be fixed. -Jon */ public static final String preprocessed = ".preprocessed"; private static final Logger log = Logger.getLogger(FilesApplicationPackage.class.getName()); private static final String META_FILE_NAME = ".applicationMetaData"; private static final Map<Path, Set<String>> validFileExtensions; private final File appDir; private final File preprocessedDir; private final File configDefsDir; private final AppSubDirs appSubDirs; // NOTE: these directories exist in the original user app, but their locations are given in 'services.xml' private final List<String> userIncludeDirs = new ArrayList<>(); private final ApplicationMetaData metaData; private final boolean includeSourceFiles; private final TransformerFactory transformerFactory; /** Creates from a directory with source files included */ public static FilesApplicationPackage fromFile(File appDir) { return fromFile(appDir, false); } /** * Returns an application package object based on the given application dir * * @param appDir application package directory * @param includeSourceFiles read files from source directories /src/main and src/test in addition * to the application package location. This is useful during development * to be able to run tests without a complete build first. * @return an Application package instance */ public static FilesApplicationPackage fromFile(File appDir, boolean includeSourceFiles) { return new Builder(appDir).preprocessedDir(applicationFile(appDir, preprocessed)) .includeSourceFiles(includeSourceFiles) .build(); } /** Creates package from a local directory, typically deploy app */ public static FilesApplicationPackage fromFileWithDeployData(File appDir, DeployData deployData) { return fromFileWithDeployData(appDir, deployData, false); } /** Creates package from a local directory, typically deploy app */ public static FilesApplicationPackage fromFileWithDeployData(File appDir, DeployData deployData, boolean includeSourceFiles) { return new Builder(appDir).includeSourceFiles(includeSourceFiles).deployData(deployData).build(); } private static ApplicationMetaData metaDataFromDeployData(File appDir, DeployData deployData) { return new ApplicationMetaData(deployData.getDeployedByUser(), deployData.getDeployedFromDir(), deployData.getDeployTimestamp(), deployData.isInternalRedeploy(), deployData.getApplicationId(), computeCheckSum(appDir), deployData.getGeneration(), deployData.getCurrentlyActiveGeneration()); } /** * New package from given path on local file system. Retrieves config definition files from * the default location '$VESPA_HOME/share/vespa/configdefinitions'. * * @param appDir application package directory * @param preprocessedDir preprocessed application package output directory * @param metaData metadata for this application package * @param includeSourceFiles include files from source dirs */ private FilesApplicationPackage(File appDir, File preprocessedDir, ApplicationMetaData metaData, boolean includeSourceFiles) { verifyAppDir(appDir); this.includeSourceFiles = includeSourceFiles; this.appDir = appDir; this.preprocessedDir = preprocessedDir; appSubDirs = new AppSubDirs(appDir); configDefsDir = applicationFile(appDir, CONFIG_DEFINITIONS_DIR); addUserIncludeDirs(); this.metaData = metaData; transformerFactory = TransformerFactory.newInstance(); } @Override @SuppressWarnings("deprecation") public String getApplicationName() { return metaData.getApplicationId().application().value(); } @Override public ApplicationId getApplicationId() { return metaData.getApplicationId(); } @Override public List<NamedReader> getFiles(Path relativePath, String suffix, boolean recurse) { return getFiles(relativePath, "", suffix, recurse); } @Override public ApplicationFile getFile(Path path) { File file = (path.isRoot() ? appDir : applicationFile(appDir, path.getRelative())); return new FilesApplicationFile(path, file); } @Override public ApplicationMetaData getMetaData() { return metaData; } private List<NamedReader> getFiles(Path relativePath, String namePrefix, String suffix, boolean recurse) { try { List<NamedReader> readers=new ArrayList<>(); File dir = applicationFile(appDir, relativePath); if ( ! dir.isDirectory()) return readers; File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { if (recurse) readers.addAll(getFiles(relativePath.append(file.getName()), namePrefix + "/" + file.getName(), suffix, recurse)); } else { if (suffix == null || file.getName().endsWith(suffix)) readers.add(new NamedReader(file.getName(), new FileReader(file))); } } } return readers; } catch (IOException e) { throw new RuntimeException("Could not open (all) files in '" + relativePath + "'",e); } } private void verifyAppDir(File appDir) { Objects.requireNonNull(appDir, "Path cannot be null"); if ( ! appDir.exists()) { throw new IllegalArgumentException("Path '" + appDir + "' does not exist"); } if ( ! appDir.isDirectory()) { throw new IllegalArgumentException("Path '" + appDir + "' is not a directory"); } if (! appDir.canRead()){ throw new IllegalArgumentException("Cannot read from application directory '" + appDir + "'"); } } @Override public Reader getHosts() { try { File hostsFile = getHostsFile(); if (!hostsFile.exists()) return null; return new FileReader(hostsFile); } catch (Exception e) { throw new IllegalArgumentException(e); } } @Override public String getHostSource() { return getHostsFile().getPath(); } private File getHostsFile() { return applicationFile(appDir, HOSTS); } @Override public String getServicesSource() { return getServicesFile().getPath(); } private File getServicesFile() { return applicationFile(appDir, SERVICES); } @Override public Optional<Reader> getDeployment() { return optionalFile(DEPLOYMENT_FILE); } @Override public Optional<Reader> getValidationOverrides() { return optionalFile(VALIDATION_OVERRIDES); } private Optional<Reader> optionalFile(Path filePath) { try { return Optional.of(getFile(filePath).createReader()); } catch (FileNotFoundException e) { return Optional.empty(); } } @Override public List<String> getUserIncludeDirs() { return Collections.unmodifiableList(userIncludeDirs); } public void addUserIncludeDirs() { Document services; try { services = Xml.getDocument(getServices()); } catch (Exception e) { return; // This method does not validate that services.xml exists, or that it is valid xml. } NodeList includeNodes = services.getElementsByTagName(IncludeDirs.INCLUDE); for (int i=0; i < includeNodes.getLength(); i++) { Node includeNode = includeNodes.item(i); addIncludeDir(includeNode); } } private void addIncludeDir(Node includeNode) { if (! (includeNode instanceof Element)) return; Element include = (Element) includeNode; if (! include.hasAttribute(IncludeDirs.DIR)) return; String dir = include.getAttribute(IncludeDirs.DIR); validateIncludeDir(dir); IncludeDirs.validateFilesInIncludedDir(dir, include.getParentNode(), this); log.log(Level.FINE, () -> "Adding user include dir '" + dir + "'"); userIncludeDirs.add(dir); } @Override public void validateIncludeDir(String dirName) { IncludeDirs.validateIncludeDir(dirName, this); } @Override public Collection<NamedReader> getSchemas() { Set<NamedReader> ret = new LinkedHashSet<>(); try { for (File f : getSearchDefinitionFiles()) { ret.add(new NamedReader(f.getName(), new FileReader(f))); } } catch (Exception e) { throw new IllegalArgumentException("Couldn't get schema contents.", e); } return ret; } /** * Creates a reader for a config definition * * @param defPath the path to the application package * @return the reader of this config definition */ private Reader retrieveConfigDefReader(File defPath) { try { return new NamedReader(defPath.getPath(), new FileReader(defPath)); } catch (IOException e) { throw new IllegalArgumentException("Could not read config definition file '" + defPath + "'", e); } } @Override public Map<ConfigDefinitionKey, UnparsedConfigDefinition> getAllExistingConfigDefs() { Map<ConfigDefinitionKey, UnparsedConfigDefinition> defs = new LinkedHashMap<>(); addAllDefsFromConfigDir(defs, configDefsDir); if (includeSourceFiles) { // allow running from source, assuming mvn file project layout addAllDefsFromConfigDir(defs, new File("src/main/resources/configdefinitions")); addAllDefsFromConfigDir(defs, new File("src/test/resources/configdefinitions")); } addAllDefsFromBundles(defs, getComponents(appDir)); return defs; } private void addAllDefsFromBundles(Map<ConfigDefinitionKey, UnparsedConfigDefinition> defs, List<Component> components) { for (Component component : components) { Bundle bundle = component.getBundle(); for (final Bundle.DefEntry def : bundle.getDefEntries()) { final ConfigDefinitionKey defKey = new ConfigDefinitionKey(def.defName, def.defNamespace); if (!defs.containsKey(defKey)) { defs.put(defKey, new UnparsedConfigDefinition() { @Override public ConfigDefinition parse() { DefParser parser = new DefParser(defKey.getName(), new StringReader(def.contents)); return ConfigDefinitionBuilder.createConfigDefinition(parser.getTree()); } @Override public String getUnparsedContent() { return def.contents; } }); } } } } private void addAllDefsFromConfigDir(Map<ConfigDefinitionKey, UnparsedConfigDefinition> defs, File configDefsDir) { if (! configDefsDir.isDirectory()) return; log.log(Level.FINE, () -> "Getting all config definitions from '" + configDefsDir + "'"); for (File def : configDefsDir.listFiles((File dir, String name) -> name.matches(".*\\.def"))) { String[] nv = def.getName().split("\\.def"); ConfigDefinitionKey key; try { key = ConfigUtils.createConfigDefinitionKeyFromDefFile(def); } catch (IOException e) { e.printStackTrace(); // TODO: Fix break; } if (key.getNamespace().isEmpty()) throw new IllegalArgumentException("Config definition '" + def + "' has no namespace"); if (defs.containsKey(key)) { if (nv[0].contains(".")) { log.log(Level.INFO, "Two config definitions found for the same name and namespace: " + key + ". The file '" + def + "' will take precedence"); } else { log.log(Level.INFO, "Two config definitions found for the same name and namespace: " + key + ". Skipping '" + def + "', as it does not contain namespace in filename"); continue; // skip } } defs.put(key, new UnparsedConfigDefinition() { @Override public ConfigDefinition parse() { DefParser parser = new DefParser(key.getName(), retrieveConfigDefReader(def)); return ConfigDefinitionBuilder.createConfigDefinition(parser.getTree()); } @Override public String getUnparsedContent() { return readConfigDefinition(def); } }); } } private String readConfigDefinition(File defPath) { try (Reader reader = retrieveConfigDefReader(defPath)) { return IOUtils.readAll(reader); } catch (IOException e) { throw new RuntimeException("Error reading config definition '" + defPath + "'", e); } } @Override public Reader getServices() { try { return new FileReader(getServicesSource()); } catch (Exception e) { throw new IllegalArgumentException(e); } } static List<File> getSearchDefinitionFiles(File appDir) { List<File> schemaFiles = new ArrayList<>(); File sdDir = applicationFile(appDir, SEARCH_DEFINITIONS_DIR.getRelative()); if (sdDir.isDirectory()) schemaFiles.addAll(Arrays.asList(sdDir.listFiles((dir, name) -> name.matches(".*\\" + SD_NAME_SUFFIX)))); sdDir = applicationFile(appDir, SCHEMAS_DIR.getRelative()); if (sdDir.isDirectory()) schemaFiles.addAll(Arrays.asList(sdDir.listFiles((dir, name) -> name.matches(".*\\" + SD_NAME_SUFFIX)))); return schemaFiles; } public List<File> getSearchDefinitionFiles() { return getSearchDefinitionFiles(appDir); } // Only for use by deploy processor public static List<Component> getComponents(File appDir) { return components(appDir, Component::new); } private static List<ComponentInfo> getComponentsInfo(File appDir) { return components(appDir, (__, info) -> info); } private static <T> List<T> components(File appDir, BiFunction<Bundle, ComponentInfo, T> toValue) { List<T> components = new ArrayList<>(); for (Bundle bundle : Bundle.getBundles(applicationFile(appDir, COMPONENT_DIR))) { components.add(toValue.apply(bundle, new ComponentInfo(Path.fromString(COMPONENT_DIR).append(bundle.getFile().getName()).getRelative()))); } return components; } @Override public List<ComponentInfo> getComponentsInfo(Version vespaVersion) { return getComponentsInfo(appDir); } /** * Returns a list of all components in this package. * * @return A list of components. */ public List<Component> getComponents() { return getComponents(appDir); } public File getAppDir() throws IOException { return appDir.getCanonicalFile(); } private static ApplicationMetaData readMetaData(File appDir) { String originalAppDir = preprocessed.equals(appDir.getName()) ? appDir.getParentFile().getName() : appDir.getName(); ApplicationMetaData defaultMetaData = new ApplicationMetaData("n/a", "n/a", 0L, false, ApplicationId.from(TenantName.defaultName(), ApplicationName.from(originalAppDir), InstanceName.defaultName()), "", 0L, 0L); File metaFile = applicationFile(appDir, META_FILE_NAME); if ( ! metaFile.exists()) { return defaultMetaData; } try (FileReader reader = new FileReader(metaFile)) { return ApplicationMetaData.fromJsonString(IOUtils.readAll(reader)); } catch (Exception e) { // Not a big deal, return default return defaultMetaData; } } /** * Represents a component in the application package. Immutable. */ public static class Component { public final ComponentInfo info; private final Bundle bundle; public Component(Bundle bundle, ComponentInfo info) { this.bundle = bundle; this.info = info; } public List<Bundle.DefEntry> getDefEntries() { return bundle.getDefEntries(); } public Bundle getBundle() { return bundle; } } /** * Reads a ranking expression from file to a string and returns it. * * @param name the name of the file to return, * relative to the search definition directory in the application package * @return the content of a ranking expression file * @throws IllegalArgumentException if the file was not found or could not be read */ @Override public Reader getRankingExpression(String name) { try { return IOUtils.createReader(expressionFileNameToFile(name), "utf-8"); } catch (IOException e) { throw new IllegalArgumentException("Could not read ranking expression file '" + name + "'", e); } } private File expressionFileNameToFile(String name) { if (new File(name).isAbsolute()) throw new IllegalArgumentException("Absolute path to ranking expression file is not allowed: " + name); Path path = Path.fromString(name); File expressionFile = applicationFile(appDir, SCHEMAS_DIR.append(path)); if ( ! expressionFile.exists()) { expressionFile = applicationFile(appDir, SEARCH_DEFINITIONS_DIR.append(path)); } return expressionFile; } @Override public File getFileReference(Path pathRelativeToAppDir) { return applicationFile(appDir, pathRelativeToAppDir.getRelative()); } @Override public void validateXML() throws IOException { validateXMLFor(Optional.empty()); } @Override public void validateXMLFor(Optional<Version> vespaVersion) throws IOException { Version modelVersion = vespaVersion.orElse(Vtag.currentVersion); ApplicationPackageXmlFilesValidator validator = ApplicationPackageXmlFilesValidator.create(appDir, modelVersion); validator.checkApplication(); validator.checkIncludedDirs(this); } @Override public void writeMetaData() throws IOException { File metaFile = applicationFile(appDir, META_FILE_NAME); IOUtils.writeFile(metaFile, metaData.asJsonBytes()); } private void preprocessXML(File destination, File inputXml, Zone zone) throws IOException { if ( ! inputXml.exists()) return; try { Document document = new XmlPreProcessor(appDir, inputXml, metaData.getApplicationId().instance(), zone.environment(), zone.region()) .run(); try (FileOutputStream outputStream = new FileOutputStream(destination)) { transformerFactory.newTransformer().transform(new DOMSource(document), new StreamResult(outputStream)); } } catch (TransformerException | ParserConfigurationException | SAXException e) { throw new RuntimeException("Error preprocessing " + inputXml.getAbsolutePath() + ": " + e.getMessage(), e); } } @Override public ApplicationPackage preprocess(Zone zone, DeployLogger logger) throws IOException { IOUtils.recursiveDeleteDir(preprocessedDir); IOUtils.copyDirectory(appDir, preprocessedDir, -1, (__, name) -> ! List.of(preprocessed, SERVICES, HOSTS, CONFIG_DEFINITIONS_DIR).contains(name)); File servicesFile = validateServicesFile(); preprocessXML(applicationFile(preprocessedDir, SERVICES), servicesFile, zone); preprocessXML(applicationFile(preprocessedDir, HOSTS), getHostsFile(), zone); FilesApplicationPackage preprocessed = fromFile(preprocessedDir, includeSourceFiles); preprocessed.copyUserDefsIntoApplication(); return preprocessed; } private File validateServicesFile() throws IOException { File servicesFile = getServicesFile(); if ( ! servicesFile.exists() || IOUtils.readFile(servicesFile).isEmpty()) throw new IllegalArgumentException(SERVICES + " in application package is empty"); return servicesFile; } private void copyUserDefsIntoApplication() { File destination = appSubDirs.configDefs(); destination.mkdir(); ConfigDefinitionDir defDir = new ConfigDefinitionDir(destination); // Copy the user's def files from components. List<Bundle> bundlesAdded = new ArrayList<>(); for (Component component : getComponents(appSubDirs.root())) { Bundle bundle = component.getBundle(); defDir.addConfigDefinitionsFromBundle(bundle, bundlesAdded); bundlesAdded.add(bundle); } } /** * Computes an md5 hash of the contents of the application package * * @return an md5sum of the application package */ private static String computeCheckSum(File appDir) { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); for (File file : appDir.listFiles((dir, name) -> !name.equals(EXT_DIR) && !name.startsWith("."))) { addPathToDigest(file, "", md5, true, false); } return toLowerCase(HexDump.toHexString(md5.digest())); } catch (Exception e) { throw new RuntimeException(e); } } /** * Adds the given path to the digest, or does nothing if path is neither file nor dir * * @param path path to add to message digest * @param suffix only files with this suffix are considered * @param digest the {link @MessageDigest} to add the file paths to * @param recursive whether to recursively find children in the paths * @param fullPathNames whether to include the full paths in checksum or only the names * @throws java.io.IOException if adding path to digest fails when reading files from path */ private static void addPathToDigest(File path, String suffix, MessageDigest digest, boolean recursive, boolean fullPathNames) throws IOException { if (!path.exists()) return; if (fullPathNames) { digest.update(path.getPath().getBytes(Utf8.getCharset())); } else { digest.update(path.getName().getBytes(Utf8.getCharset())); } if (path.isFile()) { FileInputStream is = new FileInputStream(path); addToDigest(is, digest); is.close(); } else if (path.isDirectory()) { final File[] files = path.listFiles(); if (files != null) { for (File elem : files) { if ((elem.isDirectory() && recursive) || elem.getName().endsWith(suffix)) { addPathToDigest(elem, suffix, digest, recursive, fullPathNames); } } } } } private static final int MD5_BUFFER_SIZE = 65536; private static void addToDigest(InputStream is, MessageDigest digest) throws IOException { if (is == null) return; byte[] buffer = new byte[MD5_BUFFER_SIZE]; int i; do { i = is.read(buffer); if (i > 0) { digest.update(buffer, 0, i); } } while(i != -1); } /** * Builder for {@link com.yahoo.config.model.application.provider.FilesApplicationPackage}. Use * this to create instances in a flexible manner. */ public static class Builder { private final File appDir; private Optional<File> preprocessedDir = Optional.empty(); private Optional<ApplicationMetaData> metaData = Optional.empty(); private boolean includeSourceFiles = false; public Builder(File appDir) { this.appDir = appDir; } public Builder preprocessedDir(File preprocessedDir) { this.preprocessedDir = Optional.ofNullable(preprocessedDir); return this; } public Builder deployData(DeployData deployData) { this.metaData = Optional.of(metaDataFromDeployData(appDir, deployData)); return this; } public Builder includeSourceFiles(boolean includeSourceFiles) { this.includeSourceFiles = includeSourceFiles; return this; } public FilesApplicationPackage build() { return new FilesApplicationPackage(appDir, preprocessedDir.orElse(applicationFile(appDir, preprocessed)), metaData.orElse(readMetaData(appDir)), includeSourceFiles); } } static File applicationFile(File parent, String path) { return applicationFile(parent, Path.fromString(path)); } static File applicationFile(File parent, Path path) { File file = new File(parent, path.getRelative()); if ( ! file.getAbsolutePath().startsWith(parent.getAbsolutePath())) throw new IllegalArgumentException(file + " is not a child of " + parent); return file; } /* Validates that files in application dir and subdirectories have a known extension */ public void validateFileExtensions() { validFileExtensions.forEach((subDir, __) -> validateInDir(subDir.toFile().toPath())); } private void validateInDir(java.nio.file.Path subDir) { java.nio.file.Path path = appDir.toPath().resolve(subDir); File subDirectory = path.toFile(); if ( ! subDirectory.exists() || ! subDirectory.isDirectory()) return; try (var filesInPath = Files.list(path)) { filesInPath.forEach(filePath -> { if (filePath.toFile().isDirectory()) validateInDir(appDir.toPath().relativize(filePath)); else validateFileExtensions(filePath); }); } catch (IOException e) { log.log(Level.WARNING, "Unable to list files in " + subDirectory, e); } } static { // Note: Directories intentionally not validated: MODELS_DIR (custom models can contain files with any extension) // TODO: Files that according to doc (https://docs.vespa.ai/en/reference/schema-reference.html) can be anywhere in the application package: // constant tensors (.json, .json.lz4) // onnx model files (.onnx) validFileExtensions = Map.ofEntries( Map.entry(Path.fromString(COMPONENT_DIR), Set.of(".jar")), Map.entry(CONSTANTS_DIR, Set.of(".json", ".json.lz4")), Map.entry(Path.fromString(DOCPROCCHAINS_DIR), Set.of(".xml")), Map.entry(PAGE_TEMPLATES_DIR, Set.of(".xml")), Map.entry(Path.fromString(PROCESSORCHAINS_DIR), Set.of(".xml")), Map.entry(QUERY_PROFILES_DIR, Set.of(".xml")), Map.entry(QUERY_PROFILE_TYPES_DIR, Set.of(".xml")), Map.entry(Path.fromString(ROUTINGTABLES_DIR), Set.of(".xml")), Map.entry(RULES_DIR, Set.of(RULES_NAME_SUFFIX)), // Note: Might have rank profiles in subdirs: schema-name]/[rank-profile].profile Map.entry(SCHEMAS_DIR, Set.of(SD_NAME_SUFFIX, RANKEXPRESSION_NAME_SUFFIX)), Map.entry(Path.fromString(SEARCHCHAINS_DIR), Set.of(".xml")), // Note: Might have rank profiles in subdirs: [schema-name]/[rank-profile].profile Map.entry(SEARCH_DEFINITIONS_DIR, Set.of(SD_NAME_SUFFIX, RANKEXPRESSION_NAME_SUFFIX)), Map.entry(SECURITY_DIR, Set.of(".pem"))); } private void validateFileExtensions(java.nio.file.Path pathToFile) { Set<String> allowedExtensions = findAllowedExtensions(appDir.toPath().relativize(pathToFile).getParent()); log.log(Level.FINE, "Checking " + pathToFile + " against " + allowedExtensions); String fileName = pathToFile.toFile().getName(); if (allowedExtensions.stream().noneMatch(fileName::endsWith)) { String message = "File in application package with unknown extension: " + appDir.toPath().relativize(pathToFile.getParent()).resolve(fileName) + ", please delete or move file to another directory."; throw new IllegalArgumentException(message); } } private Set<String> findAllowedExtensions(java.nio.file.Path relativeDirectory) { Set<String> validExtensions = new HashSet<>(); validExtensions.add(".gitignore"); // Special case, since subdirs in schemas/ can have any name if (isSubDirInSchemas(relativeDirectory)) validExtensions.add(".profile"); else validExtensions.addAll(validFileExtensions.entrySet().stream() .filter(entry -> entry.getKey() .equals(Path.fromString(relativeDirectory.toString()))) .map(Map.Entry::getValue) .findFirst() .orElse(Set.of())); return validExtensions; } private boolean isSubDirInSchemas(java.nio.file.Path relativeDirectory) { java.nio.file.Path schemasPath = SCHEMAS_DIR.toFile().toPath().getName(0); java.nio.file.Path searchDefinitionsPath = SEARCH_DEFINITIONS_DIR.toFile().toPath().getName(0); if (relativeDirectory.equals(schemasPath) ||relativeDirectory.equals(searchDefinitionsPath)) return false; return (relativeDirectory.startsWith(schemasPath + "/") || relativeDirectory.startsWith(SEARCH_DEFINITIONS_DIR.toFile().toPath().getName(0) + "/")); } }
/* * Copyright 2015 Goldman Sachs. * * 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.gs.collections.impl.set.fixed; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ExecutorService; import com.gs.collections.api.block.predicate.Predicate; import com.gs.collections.api.block.predicate.Predicate2; import com.gs.collections.api.set.FixedSizeSet; import com.gs.collections.api.set.MutableSet; import com.gs.collections.api.set.ParallelUnsortedSetIterable; import com.gs.collections.impl.factory.Sets; import com.gs.collections.impl.set.mutable.AbstractMutableSet; import com.gs.collections.impl.utility.Iterate; abstract class AbstractMemoryEfficientMutableSet<T> extends AbstractMutableSet<T> implements FixedSizeSet<T> { protected int nullSafeHashCode(Object element) { return element == null ? 0 : element.hashCode(); } @Override public boolean addAll(Collection<? extends T> collection) { throw new UnsupportedOperationException("Cannot add to a fixed size set: " + this.getClass()); } @Override public boolean addAllIterable(Iterable<? extends T> iterable) { throw new UnsupportedOperationException("Cannot add to a fixed size set: " + this.getClass()); } @Override public boolean retainAll(Collection<?> collection) { throw new UnsupportedOperationException("Cannot remove from a fixed size set: " + this.getClass()); } @Override public boolean retainAllIterable(Iterable<?> iterable) { throw new UnsupportedOperationException("Cannot remove from a fixed size set: " + this.getClass()); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException("Cannot remove from a fixed size set: " + this.getClass()); } @Override public boolean removeAll(Collection<?> collection) { throw new UnsupportedOperationException("Cannot remove from a fixed size set: " + this.getClass()); } @Override public boolean removeAllIterable(Iterable<?> iterable) { throw new UnsupportedOperationException("Cannot remove from a fixed size set: " + this.getClass()); } @Override public boolean removeIf(Predicate<? super T> predicate) { throw new UnsupportedOperationException("Cannot remove from a fixed size set: " + this.getClass()); } @Override public <P> boolean removeIfWith(Predicate2<? super T, ? super P> predicate, P parameter) { throw new UnsupportedOperationException("Cannot removeIfWith from a fixed size set: " + this.getClass()); } public void clear() { throw new UnsupportedOperationException("Cannot clear a fixed size set: " + this.getClass()); } public MutableSet<T> withAll(Iterable<? extends T> elements) { if (Iterate.isEmpty(elements)) { return this; } return Sets.fixedSize.ofAll(this.toList().withAll(elements)); } public MutableSet<T> withoutAll(Iterable<? extends T> elements) { if (Iterate.isEmpty(elements)) { return this; } return Sets.fixedSize.ofAll(this.toList().withoutAll(elements)); } protected abstract class MemoryEfficientSetIterator implements Iterator<T> { private int next; // next entry to return, defaults to 0 protected abstract T getElement(int i); public boolean hasNext() { return this.next < AbstractMemoryEfficientMutableSet.this.size(); } public T next() { return this.getElement(this.next++); } public void remove() { throw new UnsupportedOperationException("Cannot remove from a fixed size set: " + this.getClass()); } } public ParallelUnsortedSetIterable<T> asParallel(ExecutorService executorService, int batchSize) { return this.toSet().asParallel(executorService, batchSize); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import model.Database; /** * * @author Meneses */ public class TelaEditarEstoque extends javax.swing.JFrame { Connection conexao = null; PreparedStatement pst = null; ResultSet rs = null; boolean clique = false; public void ListarProd(){ String sql = "select nome from produto where sta_prod = true"; try { pst = conexao.prepareStatement(sql); rs = pst.executeQuery(sql); while(rs.next()){ Nome_ed.addItem(rs.getString("nome")); } } catch (SQLException ex) { Logger.getLogger(TelaAddEstoque.class.getName()).log(Level.SEVERE, null, ex); } } public int pegarIdEst() throws SQLException{ String sql = "select e.id from estoque e inner join produto p on e.ID_produto = p.id where p.nome = '" + Nome_ed.getSelectedItem().toString() + "'"; try{ pst = conexao.prepareStatement(sql); rs = pst.executeQuery(sql); while(rs.next()){ return rs.getInt("e.id"); } } catch(SQLException ex){ Logger.getLogger(TelaAddEstoque.class.getName()).log(Level.SEVERE, null, ex); } return 0; } public void TirarMp() throws SQLException{ String sql = "update materiaprima set quantidade = quantidade - '" + Double.parseDouble((Qtd_materiaprima.getText())) + "' where nome = '" + jLabel6.getText() + "'"; try { //preparando o banco pra ser usado pst = conexao.prepareStatement(sql); pst.executeUpdate(); //mensagem para o usuario //fechando a conexao e o banco } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } } public void updateestoquequantidade(){ try { String sql = "update estoque set quantidade = quantidade + '" + Double.parseDouble(Qtd_est.getText()) + "', quantidade_materiaprima = quantidade_materiaprima + '" + Double.parseDouble(Qtd_materiaprima.getText()) + "' where id = '" + pegarIdEst() + "'"; pst = conexao.prepareStatement(sql); pst.executeUpdate(); JOptionPane.showMessageDialog(null, "Estoque atualizado com sucesso"); TirarMp(); //pst.close(); //conexao.close(); } catch (SQLException ex) { Logger.getLogger(TelaEditarEstoque.class.getName()).log(Level.SEVERE, null, ex); } } public void listarmp(){ try { String sql = "select ma.nome from estoque es inner join materiaprima ma on ma.lote = es.LOTE_materia where es.id = '" + pegarIdEst() + "'"; pst = conexao.prepareStatement(sql); rs = pst.executeQuery(sql); while(rs.next()){ jLabel6.setText(rs.getString("ma.nome")); } } catch (SQLException ex) { Logger.getLogger(TelaEditarEstoque.class.getName()).log(Level.SEVERE, null, ex); } } /** * Creates new form TelaEditarEstoque */ public TelaEditarEstoque() throws ClassNotFoundException { conexao = Database.conector(); initComponents(); ListarProd(); clique = false; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jComboBox1 = new javax.swing.JComboBox<>(); jLabel4 = new javax.swing.JLabel(); jComboBox2 = new javax.swing.JComboBox<>(); Qtd_materiaprima = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); Qtd_est = new javax.swing.JTextField(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); Nome_ed = new javax.swing.JComboBox<>(); jLabel12 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jButton3 = new javax.swing.JButton(); jLabel1.setText("Nome"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jLabel2.setText("Matéria-prima"); jLabel3.setText("Quantidade"); jButton1.setText("Cancelar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Concluir"); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Coco" })); jLabel4.setText("Selecione o item do estoque"); jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); jLabel9.setText("Selecione o produto no estoque "); jLabel11.setText("Quantidade do estoque"); jButton5.setText("Cancelar"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); jButton6.setText("Concluir"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); Nome_ed.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Nome_edActionPerformed(evt); } }); jLabel12.setText("Quantidade de matéria prima"); jLabel5.setText("Matéria Prima"); jLabel6.setText("-"); jButton3.setText("Pesquisar estoque"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9) .addGroup(layout.createSequentialGroup() .addComponent(Nome_ed, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3))) .addGap(226, 226, 226)) .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 430, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jButton5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton6)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(Qtd_materiaprima, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(83, 83, 83) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Qtd_est, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11)))) .addGap(88, 88, 88))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel9) .addGap(8, 8, 8) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Nome_ed, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3)) .addGap(18, 18, 18) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel6)) .addGap(43, 43, 43) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Qtd_materiaprima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Qtd_est, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(52, 52, 52) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton5) .addComponent(jButton6)) .addContainerGap(52, Short.MAX_VALUE)) ); getAccessibleContext().setAccessibleName("Editar Estoque"); setSize(new java.awt.Dimension(490, 353)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton1ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed int confirmar = JOptionPane.showConfirmDialog(null, "Tem certeza que deseja cancelar a edição do estoque?", "Atenção",JOptionPane.YES_NO_OPTION); if(confirmar==JOptionPane.YES_OPTION){ this.dispose(); } }//GEN-LAST:event_jButton5ActionPerformed private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed if(clique){ if(Qtd_materiaprima.getText().isEmpty() || Qtd_est.getText().isEmpty()){ JOptionPane.showMessageDialog(null, "Preencha os campos corretamente"); }else{ try { String sql = "select quantidade from materiaprima where nome = '" + jLabel6.getText() + "'"; pst = conexao.prepareStatement(sql); rs = pst.executeQuery(sql); while(rs.next()){ if((rs.getDouble("quantidade") - Double.parseDouble(Qtd_materiaprima.getText())) >= 0){ updateestoquequantidade(); this.dispose(); }else{ JOptionPane.showMessageDialog(null, "Quantidade de matéria prima excedida"); } } }catch (SQLException ex) { Logger.getLogger(TelaEditarEstoque.class.getName()).log(Level.SEVERE, null, ex); } } }else{ JOptionPane.showMessageDialog(null, "Pesquise o estoque"); } }//GEN-LAST:event_jButton6ActionPerformed private void Nome_edActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Nome_edActionPerformed }//GEN-LAST:event_Nome_edActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed clique = true; listarmp(); }//GEN-LAST:event_jButton3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaEditarEstoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaEditarEstoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaEditarEstoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaEditarEstoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { new TelaEditarEstoque().setVisible(true); } catch (ClassNotFoundException ex) { Logger.getLogger(TelaEditarEstoque.class.getName()).log(Level.SEVERE, null, ex); } } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox<String> Nome_ed; private javax.swing.JTextField Qtd_est; private javax.swing.JTextField Qtd_materiaprima; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JComboBox<String> jComboBox2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel9; private javax.swing.JSeparator jSeparator1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration//GEN-END:variables }
/** * Copyright (C) 2017 Red Hat, 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 io.atlasmap.xml.inspect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.nio.file.Paths; import java.util.List; import org.junit.Assert; import org.junit.Test; import io.atlasmap.v2.CollectionType; import io.atlasmap.v2.FieldType; import io.atlasmap.xml.v2.Restriction; import io.atlasmap.xml.v2.RestrictionType; import io.atlasmap.xml.v2.XmlComplexType; import io.atlasmap.xml.v2.XmlDocument; import io.atlasmap.xml.v2.XmlEnumField; import io.atlasmap.xml.v2.XmlField; import io.atlasmap.xml.v2.XmlNamespace; public class XmlSchemaInspectionTest extends BaseXmlInspectionServiceTest { @Test public void testInspectSchemaString() throws Exception { final String source = "<xs:schema attributeFormDefault=\"unqualified\" elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:element name=\"data\">\n" + " <xs:complexType>\n" + " <xs:sequence>\n" + " <xs:element type=\"xs:int\" name=\"intField\"/>\n" + " <xs:element type=\"xs:long\" name=\"longField\"/>\n" + " <xs:element type=\"xs:string\" name=\"stringField\"/>\n" + " <xs:element type=\"xs:boolean\" name=\"booleanField\"/>\n" + " <xs:element type=\"xs:double\" name=\"doubleField\"/>\n" + " <xs:element type=\"xs:short\" name=\"shortField\"/>\n" + " <xs:element type=\"xs:float\" name=\"floatField\"/>\n" + " <xs:element type=\"xs:string\" name=\"charField\"/>\n" + " </xs:sequence>\n" + " </xs:complexType>\n" + " </xs:element>\n" + "</xs:schema>"; XmlInspectionService service = new XmlInspectionService(); XmlDocument xmlDocument = service.inspectSchema(source); assertNotNull(xmlDocument); assertNotNull(xmlDocument.getFields()); assertEquals(1, xmlDocument.getFields().getField().size()); XmlComplexType root = (XmlComplexType) xmlDocument.getFields().getField().get(0); assertNotNull(root); assertEquals(8, root.getXmlFields().getXmlField().size()); // debugFields(xmlDocument.getFields()); } @Test public void testInspectSchemaFile() throws Exception { File schemaFile = Paths.get("src/test/resources/inspect/simple-schema.xsd").toFile(); XmlInspectionService service = new XmlInspectionService(); XmlDocument xmlDocument = service.inspectSchema(schemaFile); assertNotNull(xmlDocument); assertNotNull(xmlDocument.getFields()); assertEquals(1, xmlDocument.getFields().getField().size()); XmlComplexType root = (XmlComplexType) xmlDocument.getFields().getField().get(0); assertNotNull(root); assertEquals(15, root.getXmlFields().getXmlField().size()); XmlField nmtokenField = root.getXmlFields().getXmlField().get(8); assertEquals("nmtokenField", nmtokenField.getName()); assertEquals(FieldType.STRING, nmtokenField.getFieldType()); XmlField anyuriField = root.getXmlFields().getXmlField().get(9); assertEquals("anyuriField", anyuriField.getName()); assertEquals(FieldType.STRING, anyuriField.getFieldType()); XmlField base64BinaryField = root.getXmlFields().getXmlField().get(10); assertEquals("base64binaryField", base64BinaryField.getName()); assertEquals(FieldType.STRING, base64BinaryField.getFieldType()); XmlField byteField = root.getXmlFields().getXmlField().get(11); assertEquals("byteField", byteField.getName()); assertEquals(FieldType.SHORT, byteField.getFieldType()); XmlField unsignedByteField = root.getXmlFields().getXmlField().get(12); assertEquals("unsignedByteField", unsignedByteField.getName()); assertEquals(FieldType.UNSIGNED_SHORT, unsignedByteField.getFieldType()); XmlField hexBinaryField = root.getXmlFields().getXmlField().get(13); assertEquals("hexBinaryField", hexBinaryField.getName()); assertEquals(FieldType.STRING, hexBinaryField.getFieldType()); XmlField qnameField = root.getXmlFields().getXmlField().get(14); assertEquals("qnameField", qnameField.getName()); assertEquals(FieldType.STRING, qnameField.getFieldType()); // debugFields(xmlDocument.getFields()); } @Test public void testInspectSchemaFileComplex() throws Exception { File schemaFile = Paths.get("src/test/resources/inspect/complex-schema.xsd").toFile(); XmlInspectionService service = new XmlInspectionService(); XmlDocument xmlDocument = service.inspectSchema(schemaFile); assertNotNull(xmlDocument); assertNotNull(xmlDocument.getFields()); assertEquals(1, xmlDocument.getFields().getField().size()); XmlComplexType root = (XmlComplexType) xmlDocument.getFields().getField().get(0); assertNotNull(root); assertEquals(10, root.getXmlFields().getXmlField().size()); XmlField enumField = root.getXmlFields().getXmlField().get(9); assertEquals("enumField", enumField.getName()); assertEquals(FieldType.COMPLEX, enumField.getFieldType()); XmlComplexType enumComplex = (XmlComplexType) enumField; assertTrue(enumComplex.isEnumeration()); List<XmlEnumField> enumFields = enumComplex.getXmlEnumFields().getXmlEnumField(); assertEquals(6, enumFields.size()); assertEquals("aaa", enumFields.get(0).getName()); assertEquals("fff", enumFields.get(5).getName()); // debugFields(xmlDocument.getFields()); } @Test public void testInspectSchemaFileWithNamespace() throws Exception { File schemaFile = Paths.get("src/test/resources/inspect/simple-namespace-schema.xsd").toFile(); XmlInspectionService service = new XmlInspectionService(); XmlDocument xmlDocument = service.inspectSchema(schemaFile); assertNotNull(xmlDocument); assertNotNull(xmlDocument.getFields()); assertEquals(1, xmlDocument.getFields().getField().size()); assertNotNull(xmlDocument.getXmlNamespaces()); assertEquals(1, xmlDocument.getXmlNamespaces().getXmlNamespace().size()); XmlNamespace namespace = xmlDocument.getXmlNamespaces().getXmlNamespace().get(0); assertEquals("tns", namespace.getAlias()); assertEquals("http://example.com/", namespace.getUri()); // debugFields(xmlDocument.getFields()); } @Test public void testInspectShipOrderSchemaFile() throws Exception { File schemaFile = Paths.get("src/test/resources/inspect/ship-order-schema.xsd").toFile(); XmlInspectionService service = new XmlInspectionService(); XmlDocument xmlDocument = service.inspectSchema(schemaFile); assertNotNull(xmlDocument); assertNotNull(xmlDocument.getFields()); assertEquals(1, xmlDocument.getFields().getField().size()); XmlComplexType root = (XmlComplexType) xmlDocument.getFields().getField().get(0); assertNotNull(root); assertEquals(4, root.getXmlFields().getXmlField().size()); // @orderId XmlField orderIdAttr = root.getXmlFields().getXmlField().get(0); assertNotNull(orderIdAttr); assertEquals("orderid", orderIdAttr.getName()); assertEquals("2", orderIdAttr.getValue()); assertEquals("/shiporder/@orderid", orderIdAttr.getPath()); assertEquals(FieldType.STRING, orderIdAttr.getFieldType()); assertEquals(true, orderIdAttr.isAttribute()); // orderperson XmlField orderPerson = root.getXmlFields().getXmlField().get(1); assertNotNull(orderPerson); assertEquals("orderperson", orderPerson.getName()); assertNull(orderPerson.getValue()); assertEquals("/shiporder/orderperson", orderPerson.getPath()); assertEquals(FieldType.STRING, orderPerson.getFieldType()); assertEquals(false, orderPerson.isAttribute()); // shipTo XmlField shipTo = root.getXmlFields().getXmlField().get(2); assertNotNull(shipTo); assertTrue(shipTo instanceof XmlComplexType); assertEquals(4, ((XmlComplexType) shipTo).getXmlFields().getXmlField().size()); // item XmlField item = root.getXmlFields().getXmlField().get(3); assertNotNull(item); assertTrue(item instanceof XmlComplexType); assertEquals(4, ((XmlComplexType) item).getXmlFields().getXmlField().size()); // debugFields(xmlDocument.getFields()); } @Test public void testInspectPOExampleSchemaFile() throws Exception { File schemaFile = Paths.get("src/test/resources/inspect/po-example-schema.xsd").toFile(); XmlInspectionService service = new XmlInspectionService(); XmlDocument xmlDocument = service.inspectSchema(schemaFile); assertNotNull(xmlDocument); assertNotNull(xmlDocument.getFields()); assertEquals(2, xmlDocument.getFields().getField().size()); // PurchaseOrderType XmlComplexType purchaseOrder = (XmlComplexType) xmlDocument.getFields().getField().get(0); assertNotNull(purchaseOrder); assertEquals(5, purchaseOrder.getXmlFields().getXmlField().size()); // orderDate XmlField orderDateAttr = purchaseOrder.getXmlFields().getXmlField().get(0); assertNotNull(orderDateAttr); assertEquals("orderDate", orderDateAttr.getName()); assertNull(orderDateAttr.getValue()); assertEquals("/tns:purchaseOrder/@orderDate", orderDateAttr.getPath()); assertEquals(FieldType.DATE, orderDateAttr.getFieldType()); assertEquals(true, orderDateAttr.isAttribute()); // shipTo XmlField shipTo = purchaseOrder.getXmlFields().getXmlField().get(1); assertNotNull(shipTo); assertEquals("shipTo", shipTo.getName()); assertNull(shipTo.getValue()); assertEquals("/tns:purchaseOrder/shipTo", shipTo.getPath()); assertEquals(FieldType.COMPLEX, shipTo.getFieldType()); assertEquals(6, ((XmlComplexType) shipTo).getXmlFields().getXmlField().size()); // shipTo/@country XmlField shipToCountry = ((XmlComplexType) shipTo).getXmlFields().getXmlField().get(0); assertNotNull(shipTo); assertEquals("country", shipToCountry.getName()); assertEquals("US", shipToCountry.getValue()); assertEquals("/tns:purchaseOrder/shipTo/@country", shipToCountry.getPath()); assertEquals(FieldType.STRING, shipToCountry.getFieldType()); assertEquals(true, shipToCountry.isAttribute()); XmlField shipToName = ((XmlComplexType) shipTo).getXmlFields().getXmlField().get(1); assertNotNull(shipToName); assertEquals("name", shipToName.getName()); assertNull(shipToName.getValue()); assertEquals("/tns:purchaseOrder/shipTo/name", shipToName.getPath()); assertEquals(FieldType.STRING, shipToName.getFieldType()); assertEquals(false, shipToName.isAttribute()); XmlField shipToStreet = ((XmlComplexType) shipTo).getXmlFields().getXmlField().get(2); assertNotNull(shipToStreet); assertEquals("street", shipToStreet.getName()); assertNull(shipToStreet.getValue()); assertEquals("/tns:purchaseOrder/shipTo/street", shipToStreet.getPath()); assertEquals(FieldType.STRING, shipToStreet.getFieldType()); assertEquals(false, shipToStreet.isAttribute()); XmlField shipToCity = ((XmlComplexType) shipTo).getXmlFields().getXmlField().get(3); assertNotNull(shipToCity); assertEquals("city", shipToCity.getName()); assertNull(shipToCity.getValue()); assertEquals("/tns:purchaseOrder/shipTo/city", shipToCity.getPath()); assertEquals(FieldType.STRING, shipToCity.getFieldType()); assertEquals(false, shipToCity.isAttribute()); XmlField shipToState = ((XmlComplexType) shipTo).getXmlFields().getXmlField().get(4); assertNotNull(shipToState); assertEquals("state", shipToState.getName()); assertNull(shipToState.getValue()); assertEquals("/tns:purchaseOrder/shipTo/state", shipToState.getPath()); assertEquals(FieldType.STRING, shipToState.getFieldType()); assertEquals(false, shipToState.isAttribute()); XmlField shipToZip = ((XmlComplexType) shipTo).getXmlFields().getXmlField().get(5); assertNotNull(shipToZip); assertEquals("zip", shipToZip.getName()); assertNull(shipToZip.getValue()); assertEquals("/tns:purchaseOrder/shipTo/zip", shipToZip.getPath()); assertEquals(FieldType.DECIMAL, shipToZip.getFieldType()); assertEquals(false, shipToZip.isAttribute()); // comment XmlField comment = purchaseOrder.getXmlFields().getXmlField().get(3); assertNotNull(comment); assertEquals("tns:comment", comment.getName()); assertNull(comment.getValue()); assertEquals("/tns:purchaseOrder/tns:comment", comment.getPath()); assertEquals(FieldType.STRING, comment.getFieldType()); assertEquals(false, comment.isAttribute()); // items XmlField items = purchaseOrder.getXmlFields().getXmlField().get(4); assertNotNull(items); assertEquals("items", items.getName()); assertNull(items.getValue()); assertEquals("/tns:purchaseOrder/items", items.getPath()); assertEquals(FieldType.COMPLEX, items.getFieldType()); assertEquals(false, items.isAttribute()); assertEquals(1, ((XmlComplexType) items).getXmlFields().getXmlField().size()); // items/item XmlComplexType item = (XmlComplexType) ((XmlComplexType) items).getXmlFields().getXmlField().get(0); assertNotNull(item); assertEquals("item", item.getName()); assertNull(item.getValue()); assertEquals("/tns:purchaseOrder/items/item", item.getPath()); assertEquals(FieldType.COMPLEX, item.getFieldType()); assertEquals(false, item.isAttribute()); assertEquals(CollectionType.LIST, item.getCollectionType()); assertEquals(6, item.getXmlFields().getXmlField().size()); // partNum XmlField partNum = item.getXmlFields().getXmlField().get(0); assertNotNull(partNum); assertEquals("partNum", partNum.getName()); assertNull(partNum.getValue()); assertEquals("/tns:purchaseOrder/items/item/@partNum", partNum.getPath()); assertEquals(FieldType.STRING, partNum.getFieldType()); assertEquals("SKU", partNum.getTypeName()); assertEquals(true, partNum.isAttribute()); // productName XmlField productName = item.getXmlFields().getXmlField().get(1); assertNotNull(productName); assertEquals("productName", productName.getName()); assertNull(productName.getValue()); assertEquals("/tns:purchaseOrder/items/item/productName", productName.getPath()); assertEquals(FieldType.STRING, productName.getFieldType()); assertEquals(false, productName.isAttribute()); // quantity XmlField quantity = item.getXmlFields().getXmlField().get(2); assertNotNull(quantity); assertEquals("quantity", quantity.getName()); assertNull(quantity.getValue()); assertEquals("/tns:purchaseOrder/items/item/quantity", quantity.getPath()); assertEquals(FieldType.BIG_INTEGER, quantity.getFieldType()); assertEquals(false, quantity.isAttribute()); assertNotNull(quantity.getRestrictions().getRestriction()); assertEquals(1, quantity.getRestrictions().getRestriction().size()); Restriction qRestriction = quantity.getRestrictions().getRestriction().get(0); assertNotNull(qRestriction); assertNotNull(qRestriction.getType()); assertEquals(RestrictionType.MAX_EXCLUSIVE, qRestriction.getType()); assertNotNull(qRestriction.getValue()); assertEquals("99", qRestriction.getValue()); // USPrice XmlField usPrice = item.getXmlFields().getXmlField().get(3); assertNotNull(usPrice); assertEquals("USPrice", usPrice.getName()); assertNull(usPrice.getValue()); assertEquals("/tns:purchaseOrder/items/item/USPrice", usPrice.getPath()); assertEquals(FieldType.DECIMAL, usPrice.getFieldType()); assertEquals(false, usPrice.isAttribute()); // comment XmlField itemComment = item.getXmlFields().getXmlField().get(4); Assert.assertNotNull(itemComment); assertEquals("tns:comment", itemComment.getName()); assertNull(itemComment.getValue()); assertEquals("/tns:purchaseOrder/items/item/tns:comment", itemComment.getPath()); assertEquals(FieldType.STRING, itemComment.getFieldType()); assertEquals(false, itemComment.isAttribute()); // shipDate XmlField shipDate = item.getXmlFields().getXmlField().get(5); assertNotNull(shipDate); assertEquals("shipDate", shipDate.getName()); assertNull(shipDate.getValue()); assertEquals("/tns:purchaseOrder/items/item/shipDate", shipDate.getPath()); assertEquals(FieldType.DATE, shipDate.getFieldType()); assertEquals(false, shipDate.isAttribute()); // namespaces Assert.assertNotNull(xmlDocument.getXmlNamespaces()); assertEquals(1, xmlDocument.getXmlNamespaces().getXmlNamespace().size()); XmlNamespace namespace = xmlDocument.getXmlNamespaces().getXmlNamespace().get(0); assertEquals("tns", namespace.getAlias()); assertEquals("http://tempuri.org/po.xsd", namespace.getUri()); // debugFields(xmlDocument.getFields()); } @Test(expected = IllegalArgumentException.class) public void testInspectSchemaStringAsSourceNull() throws Exception { XmlInspectionService service = new XmlInspectionService(); String schema = null; service.inspectSchema(schema); } @Test(expected = IllegalArgumentException.class) public void testInspectSchemaStringAsSourceBlank() throws Exception { XmlInspectionService service = new XmlInspectionService(); String schema = ""; service.inspectSchema(schema); } @Test(expected = IllegalArgumentException.class) public void testInspectSchemaFileAsSourceNull() throws Exception { XmlInspectionService service = new XmlInspectionService(); File schema = null; service.inspectSchema(schema); } @Test(expected = XmlInspectionException.class) public void testInspectSchemaBad() throws Exception { final String source = "<xs:schema/>"; XmlInspectionService service = new XmlInspectionService(); service.inspectSchema(source); } @Test(expected = XmlInspectionException.class) public void testInspectSchemaFileBad() throws Exception { File schemaFile = Paths.get("src/test/resources/inspect/simple-schema-bad.xsd").toFile(); XmlInspectionService service = new XmlInspectionService(); service.inspectSchema(schemaFile); } }
package io.github.cweijan.mock.feign.proxy; import org.springframework.cglib.proxy.Callback; import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.objenesis.ObjenesisHelper; /** * 用于创建controller代理, 内部代码为调用feign客户端. * @author cweijan * @since 2020/05/26 14:23 */ public class CglibClient implements FeignClientWrapper { /** * create feign invoker wrapper * @param controllerClass wrapper class * @param feignInvoke invoker * @return feign wrpper proxy */ @SuppressWarnings("unchecked") @Override public <T> T create(Class<T> controllerClass, FeignInvoke feignInvoke) { Enhancer e = new Enhancer(); e.setSuperclass(controllerClass); e.setCallbackType(MethodInterceptor.class); Class<?> dynamicClass = e.createClass(); Enhancer.registerCallbacks(dynamicClass, new Callback[]{(MethodInterceptor) (o1, method, args, methodProxy) -> feignInvoke.invoke(method, args)}); return (T) ObjenesisHelper.newInstance(dynamicClass); } }
package com.webaddicted.kotlinproject.global.blink; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.Matrix; import android.os.SystemClock; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; public class GameGLRenderer implements GLSurfaceView.Renderer { private Triangle mTriangle; private Rectangle mRectangle; private Cube mCube; float x=0,y=0,z=1; float[] scratch = new float[16]; float[] scratch1 = new float[16]; private final float[] mMVPMatrix = new float[16]; private final float[] mMVPMatrix1 = new float[16]; private final float[] mProjectionMatrix = new float[16]; private final float[] mViewMatrix = new float[16]; private final float[] mProjectionMatrix1 = new float[16]; private final float[] mViewMatrix1 = new float[16]; private final float[] mRotationMatrix = new float[16]; private final float[] mRotationMatrix1 = new float[16]; private final float[] mModelMatrix = new float[16]; private final float [] mModelMatrix1 = new float[16]; public void onSurfaceCreated(GL10 unused, EGLConfig config) { // Set the background frame color GLES20.glClearColor(1.0f, 1.0f, 1.0f, 0.5f); mTriangle = new Triangle(); mRectangle = new Rectangle(); mCube = new Cube(); //unused.glTranslatef(0,0,0); } public void onDrawFrame(GL10 unused) { // Redraw background color GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); // Set the camera position (View matrix) Matrix.setLookAtM(mViewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f); // Calculate the projection and view transformation Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0); // Calculate the projection and view transformation long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); Matrix.setRotateM(mRotationMatrix, 0, angle, 0, 0, -1.0f); // Combine the rotation matrix with the projection and camera view // Note that the mMVPMatrix factor *must be first* in order // for the matrix multiplication product to be correct. Matrix.multiplyMM(scratch, 0, mMVPMatrix, 0, mRotationMatrix, 0); // Draw triangle mTriangle.draw(scratch); } public void onSurfaceChanged(GL10 unused, int width, int height) { GLES20.glViewport(0, 0, width, height); float ratio = (float) width / height; // this projection matrix is applied to object coordinates // in the onDrawFrame() method Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 3, 100); Matrix.frustumM(mProjectionMatrix1, 0, -ratio, ratio, -1, 1, 3, 7); } public static int loadShader(int type, String shaderCode){ // create a vertex shader type (GLES20.GL_VERTEX_SHADER) // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER) int shader = GLES20.glCreateShader(type); // add the source code to the shader and compile it GLES20.glShaderSource(shader, shaderCode); GLES20.glCompileShader(shader); return shader; } }
package com.common.basic.net; import com.google.gson.Gson; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import com.common.basic.tools.StringUtils; public abstract class DataObject { public static <T extends DataObject> T get(Class<T> clazz, String json) { Gson gson = new Gson(); return gson.fromJson(json, clazz); } public static <T extends DataObject> List<T> getList(Type type, String json) { if (!StringUtils.isEmpty(json)) return new ArrayList<T>(); Gson gson = new Gson(); return gson.fromJson(json, type); } }
/* * Copyright 1999-2019 Seata.io Group. * * 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 io.seata.rm.datasource.undo.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Date; import io.seata.common.loader.LoadLevel; import io.seata.common.util.BlobUtils; import io.seata.core.compressor.CompressorType; import io.seata.core.constants.ClientTableColumnsName; import io.seata.rm.datasource.undo.AbstractUndoLogManager; import io.seata.rm.datasource.undo.UndoLogParser; import io.seata.sqlparser.util.JdbcConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author jsbxyyx */ @LoadLevel(name = JdbcConstants.MYSQL) public class MySQLUndoLogManager extends AbstractUndoLogManager { private static final Logger LOGGER = LoggerFactory.getLogger(MySQLUndoLogManager.class); /** * branch_id, xid, context, rollback_info, log_status, log_created, log_modified */ private static final String INSERT_UNDO_LOG_SQL = "INSERT INTO " + UNDO_LOG_TABLE_NAME + " (" + ClientTableColumnsName.UNDO_LOG_BRANCH_XID + ", " + ClientTableColumnsName.UNDO_LOG_XID + ", " + ClientTableColumnsName.UNDO_LOG_CONTEXT + ", " + ClientTableColumnsName.UNDO_LOG_ROLLBACK_INFO + ", " + ClientTableColumnsName.UNDO_LOG_LOG_STATUS + ", " + ClientTableColumnsName.UNDO_LOG_LOG_CREATED + ", " + ClientTableColumnsName.UNDO_LOG_LOG_MODIFIED + ")" + " VALUES (?, ?, ?, ?, ?, now(6), now(6))"; private static final String DELETE_UNDO_LOG_BY_CREATE_SQL = "DELETE FROM " + UNDO_LOG_TABLE_NAME + " WHERE " + ClientTableColumnsName.UNDO_LOG_LOG_CREATED + " <= ? LIMIT ?"; @Override public int deleteUndoLogByLogCreated(Date logCreated, int limitRows, Connection conn) throws SQLException { try (PreparedStatement deletePST = conn.prepareStatement(DELETE_UNDO_LOG_BY_CREATE_SQL)) { deletePST.setDate(1, new java.sql.Date(logCreated.getTime())); deletePST.setInt(2, limitRows); int deleteRows = deletePST.executeUpdate(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("batch delete undo log size {}", deleteRows); } return deleteRows; } catch (Exception e) { if (!(e instanceof SQLException)) { e = new SQLException(e); } throw (SQLException) e; } } @Override protected void insertUndoLogWithNormal(String xid, long branchId, String rollbackCtx, byte[] undoLogContent, Connection conn) throws SQLException { insertUndoLog(xid, branchId, rollbackCtx, undoLogContent, State.Normal, conn); } @Override protected void insertUndoLogWithGlobalFinished(String xid, long branchId, UndoLogParser parser, Connection conn) throws SQLException { insertUndoLog(xid, branchId, buildContext(parser.getName(), CompressorType.NONE), parser.getDefaultContent(), State.GlobalFinished, conn); } private void insertUndoLog(String xid, long branchId, String rollbackCtx, byte[] undoLogContent, State state, Connection conn) throws SQLException { try (PreparedStatement pst = conn.prepareStatement(INSERT_UNDO_LOG_SQL)) { pst.setLong(1, branchId); pst.setString(2, xid); pst.setString(3, rollbackCtx); pst.setBlob(4, BlobUtils.bytes2Blob(undoLogContent)); pst.setInt(5, state.getValue()); pst.executeUpdate(); } catch (Exception e) { if (!(e instanceof SQLException)) { e = new SQLException(e); } throw (SQLException) e; } } }
package org.flowdev.parser.data; public class SourceData { private String name; private String content; private int pos; private int wherePrevNl = -1; private int whereLine = 1; public SourceData name(final String name) { this.name = name; return this; } public SourceData content(final String content) { this.content = content; return this; } public SourceData pos(final int pos) { this.pos = pos; return this; } public SourceData wherePrevNl(final int wherePrevNl) { this.wherePrevNl = wherePrevNl; return this; } public SourceData whereLine(final int whereLine) { this.whereLine = whereLine; return this; } public String name() { return name; } public String content() { return content; } public int pos() { return pos; } public int wherePrevNl() { return wherePrevNl; } public int whereLine() { return whereLine; } }
/* * Copyright (c) 2013-2019 Cinchapi 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.cinchapi.concourse.server.storage.db; import java.lang.reflect.Constructor; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import com.cinchapi.common.base.CheckedExceptions; import com.cinchapi.concourse.server.io.Byteables; import com.cinchapi.concourse.server.storage.Action; import com.cinchapi.concourse.time.Time; import com.cinchapi.concourse.util.TestData; /** * Unit tests for all the subclasses of * {@link com.cinchapi.concourse.server.storage.db.Revision}. * * @author Jeff Nelson */ @RunWith(Theories.class) public class RevisionTest { public static @DataPoints Revision<?, ?, ?>[] revisions = { TestData.getPrimaryRevision(), TestData.getSearchRevision(), TestData.getSecondaryRevision() }; @Test @Theory public void testSerialization(Revision<?, ?, ?> revision) { Assert.assertTrue( Byteables.read(revision.getBytes(), revision.getClass()) .equals(revision)); } @Test @Theory public void testEquals(Revision<?, ?, ?> revision) { Assert.assertEquals(revision, duplicate(revision)); } @Test @Theory public void testHashCode(Revision<?, ?, ?> revision) { Assert.assertEquals(revision.hashCode(), duplicate(revision).hashCode()); } /** * Duplicate {@code revision} with a different version. * * @param revision * @return the duplicated revision */ private Revision<?, ?, ?> duplicate(Revision<?, ?, ?> revision) { Constructor<?> constructor; try { constructor = revision.getClass().getDeclaredConstructor( revision.getLocator().getClass(), revision.getKey().getClass(), revision.getValue().getClass(), Long.TYPE, Action.class); constructor.setAccessible(true); return (Revision<?, ?, ?>) constructor.newInstance( revision.getLocator(), revision.getKey(), revision.getValue(), Time.now(), revision.getType()); } catch (Exception e) { throw CheckedExceptions.wrapAsRuntimeException(e); } } }
/* * Copyright (C) 2012 CyberAgent * * 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 woniu.cn.libcamera.camera.filter.helper; public enum Rotation { NORMAL, ROTATION_90, ROTATION_180, ROTATION_270; /** * Retrieves the int representation of the Rotation. * * @return 0, 90, 180 or 270 */ public int asInt() { switch (this) { case NORMAL: return 0; case ROTATION_90: return 90; case ROTATION_180: return 180; case ROTATION_270: return 270; default: throw new IllegalStateException("Unknown Rotation!"); } } /** * Create a Rotation from an integer. Needs to be either 0, 90, 180 or 270. * * @param rotation 0, 90, 180 or 270 * @return Rotation object */ public static Rotation fromInt(int rotation) { switch (rotation) { case 0: return NORMAL; case 90: return ROTATION_90; case 180: return ROTATION_180; case 270: return ROTATION_270; case 360: return NORMAL; default: throw new IllegalStateException( rotation + " is an unknown rotation. Needs to be either 0, 90, 180 or 270!"); } } }
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved. * Portions Copyright 2011 Jens Elkner. * Portions Copyright (c) 2017-2018, 2020, Chris Fraire <cfraire@me.com>. */ package org.opengrok.indexer.analysis; import java.io.IOException; import java.io.Reader; import java.io.Writer; import org.opengrok.indexer.analysis.Scopes.Scope; import org.opengrok.indexer.configuration.Project; import org.opengrok.indexer.configuration.RuntimeEnvironment; import org.opengrok.indexer.history.Annotation; import org.opengrok.indexer.web.QueryParameters; import org.opengrok.indexer.web.Util; /** * @author Lubos Kosco */ public class JFlexXref implements Xrefer, SymbolMatchedListener, NonSymbolMatchedListener { /** * Used to indicate pre-formatted output with * {@link Util#htmlize(java.lang.CharSequence, java.lang.Appendable, boolean)}. */ private static final boolean PRE = true; private final ScanningSymbolMatcher matcher; private Writer out; private final String urlPrefix = RuntimeEnvironment.getInstance().getUrlPrefix(); private Annotation annotation; private Project project; private Definitions defs; private boolean scopesEnabled; private boolean foldingEnabled; private boolean scopeOpen; private Scopes scopes = new Scopes(); private Scope scope; private int scopeLevel; /** * The following field is set to {@code true} (via * {@link #sourceCodeSeen(org.opengrok.indexer.analysis.SourceCodeSeenEvent)}) * when applicable during lexing before a call to {@link #startNewLine()} * so that the lines-of-code count is also incremented. */ private boolean didSeePhysicalLOC; private int loc; /** * See {@link RuntimeEnvironment#getUserPage()}. Per default initialized in * the constructor and here to be consistent and avoid lot of unnecessary * lookups. * * @see #startNewLine() */ private String userPageLink; /** * See {@link RuntimeEnvironment#getUserPageSuffix()}. Per default * initialized in the constructor and here to be consistent and avoid lot of * unnecessary lookups. * * @see #startNewLine() */ private String userPageSuffix; /** * The span class name from the last call to * {@link #disjointSpan(java.lang.String)}. */ private String disjointSpanClassName; /** * Initialize an instance, passing a {@link ScanningSymbolMatcher} which * will be owned by the {@link JFlexXref}. * @param matcher a defined instance */ public JFlexXref(ScanningSymbolMatcher matcher) { if (matcher == null) { throw new IllegalArgumentException("`matcher' is null"); } this.matcher = matcher; matcher.setSymbolMatchedListener(this); matcher.setNonSymbolMatchedListener(this); // The xrefer will own the matcher, so we won't have to unsubscribe. userPageLink = RuntimeEnvironment.getInstance().getUserPage(); if (userPageLink != null && userPageLink.length() == 0) { userPageLink = null; } userPageSuffix = RuntimeEnvironment.getInstance().getUserPageSuffix(); if (userPageSuffix != null && userPageSuffix.length() == 0) { userPageSuffix = null; } } public void setReader(Reader input) { if (input == null) { throw new IllegalArgumentException("`input' is null"); } matcher.yyreset(input); matcher.reset(); } /** * Resets the instance. * Normally, it only makes sense to call this method after calling * {@link #setReader(java.io.Reader)} to reset the instance's * {@link ScanningSymbolMatcher} first as well. */ @Override public void reset() { annotation = null; didSeePhysicalLOC = false; disjointSpanClassName = null; loc = 0; scopes = new Scopes(); scope = null; scopeLevel = 0; scopeOpen = false; } /** * Gets the line number from {@link ScanningSymbolMatcher#getLineNumber()} * of the instance's {@link ScanningSymbolMatcher}. * @return yyline */ @Override public int getLineNumber() { return matcher.getLineNumber(); } /** * Gets the determined count of physical lines-of-code. * @return lines-of-code count */ @Override public int getLOC() { return loc; } @Override public void setAnnotation(Annotation annotation) { this.annotation = annotation; } /** * Set definitions. * @param defs definitions */ @Override public void setDefs(Definitions defs) { this.defs = defs; } @Override public void setProject(Project project) { this.project = project; } /** * Set scopes. * @param scopesEnabled if they should be enabled or disabled */ @Override public void setScopesEnabled(boolean scopesEnabled) { this.scopesEnabled = scopesEnabled; } /** * Set folding of code. * @param foldingEnabled whether to fold or not */ @Override public void setFoldingEnabled(boolean foldingEnabled) { this.foldingEnabled = foldingEnabled; } @Override public void symbolMatched(SymbolMatchedEvent evt) { try { JFlexXrefUtils.writeSymbol(out, defs, urlPrefix, project, evt.getStr(), null, matcher.getLineNumber(), false, false); } catch (IOException ex) { throw new RuntimeException(ex); } } /** * Sets a value indicating that source code was encountered such that * {@link #getLOC()} will be incremented upon the next * {@link #startNewLine()} or at end-of-file. * @param evt ignored */ @Override public void sourceCodeSeen(SourceCodeSeenEvent evt) { didSeePhysicalLOC = true; } @Override public void nonSymbolMatched(TextMatchedEvent evt) { String str = evt.getStr(); try { switch (evt.getHint()) { case EM: out.write("<em>"); Util.htmlize(str, out, PRE); out.write("</em>"); break; case STRONG: out.write("<strong>"); Util.htmlize(str, out, PRE); out.write("</strong>"); break; case NONE: default: Util.htmlize(str, out, PRE); break; } } catch (IOException ex) { throw new RuntimeException(ex); } } @Override public void keywordMatched(TextMatchedEvent evt) { try { writeKeyword(evt.getStr(), matcher.getLineNumber()); } catch (IOException ex) { throw new RuntimeException(ex); } } @Override public void endOfLineMatched(TextMatchedEvent evt) { try { startNewLine(); } catch (IOException ex) { throw new RuntimeException(ex); } } @Override public void disjointSpanChanged(DisjointSpanChangedEvent evt) { try { disjointSpan(evt.getDisjointSpanClassName()); } catch (IOException ex) { throw new RuntimeException(ex); } } @Override public void linkageMatched(LinkageMatchedEvent evt) { String str = evt.getStr(); String lstr = evt.getLinkStr(); LinkageType linkageType = evt.getLinkageType(); try { switch (linkageType) { case EMAIL: writeEMailAddress(str); break; case LABEL: // Only PowerShell seems to be using this. out.write("<a class=\"xlbl\" name=\""); Util.URIEncode(lstr, out); out.write("\">"); Util.htmlize(str, out, PRE); out.write("</a>"); break; case LABELDEF: // Only PowerShell seems to be using this. JFlexXrefUtils.writeSameFileLinkSymbol(out, str); break; case FILELIKE: out.write("<a href=\""); out.write(urlPrefix); out.write(QueryParameters.PATH_SEARCH_PARAM_EQ); /* * Maybe in the future the following should properly be * qurlencode(), but just htmlize() it for now. */ Util.htmlize(lstr, out); JFlexXrefUtils.appendProject(out, project); out.write("\">"); Util.htmlize(str, out, PRE); out.write("</a>"); break; case PATHLIKE: out.write(Util.breadcrumbPath(urlPrefix + QueryParameters.PATH_SEARCH_PARAM_EQ, str, '/')); break; case QUERY: out.write("<a href=\""); out.write(urlPrefix); out.write(QueryParameters.FULL_SEARCH_PARAM_EQ); Util.qurlencode(lstr, out); JFlexXrefUtils.appendProject(out, project); out.write("\">"); Util.htmlize(str, out, PRE); out.write("</a>"); break; case REFS: out.write("<a href=\""); out.write(urlPrefix); out.write(QueryParameters.REFS_SEARCH_PARAM_EQ); Util.qurlencode(lstr, out); JFlexXrefUtils.appendProject(out, project); out.write("\">"); Util.htmlize(str, out, PRE); out.write("</a>"); break; case URI: appendLink(str); break; default: throw new UnsupportedOperationException("LinkageType" + linkageType); } } catch (IOException ex) { throw new RuntimeException(ex); } } @Override public void pathlikeMatched(PathlikeMatchedEvent evt) { String str = evt.getStr(); String breadcrumbPath = Util.breadcrumbPath(urlPrefix + QueryParameters.PATH_SEARCH_PARAM_EQ, str, evt.getSep(), getProjectPostfix(true), evt.getCanonicalize()); try { out.write(breadcrumbPath); } catch (IOException ex) { throw new RuntimeException(ex); } } @Override public void scopeChanged(ScopeChangedEvent evt) { ScopeAction action = evt.getAction(); switch (action) { case INC: incScope(); break; case DEC: decScope(); break; case END: endScope(); break; default: throw new UnsupportedOperationException("ScopeAction " + action); } // // TODO: maybe retire this odd convention which I've kept to minimize // test differences. // String str = evt.getStr(); try { if (str.length() > 1) { out.write(str); } else if (str.length() > 0) { writeUnicodeChar(str.charAt(0)); } } catch (IOException ex) { throw new RuntimeException(ex); } } /** * Calls * {@link JFlexXrefUtils#appendLink(java.io.Writer, org.opengrok.indexer.analysis.JFlexLexer, java.lang.String, boolean, java.util.regex.Pattern)} * with the active {@link Writer}, the instance's * {@link ScanningSymbolMatcher}, {@code url}, {@code false}, and * {@code null}. * @param url the URL to append * @throws IOException if an error occurs while appending */ protected void appendLink(String url) throws IOException { JFlexXrefUtils.appendLink(out, matcher, url, false, null); } protected String getProjectPostfix(boolean encoded) { String amp = encoded ? "&amp;" : "&"; return project == null ? "" : (amp + QueryParameters.PROJECT_SEARCH_PARAM_EQ + project.getName()); } protected void startScope() { Scope newScope = JFlexXrefUtils.maybeNewScope(scopesEnabled, scope, matcher, defs); if (newScope != null) { scope = newScope; scopeLevel = 0; } } protected void incScope() { if (scope != null) { scopeLevel++; } } protected void decScope() { if (scope != null && scopeLevel > 0) { scopeLevel--; if (scopeLevel == 0) { scope.setLineTo(matcher.getLineNumber()); scopes.addScope(scope); scope = null; } } } protected void endScope() { if (scope != null && scopeLevel == 0) { scope.setLineTo(matcher.getLineNumber()); scopes.addScope(scope); scope = null; } } /** * Get generated scopes. * @return scopes for current line */ @Override public Scopes getScopes() { return scopes; } /** * Writes the closing of an open span tag previously opened by this method * and the opening -- if {@code className} is non-null -- of a new span * tag. * <p>This method's disjoint spans are independent of any span used for * scopes. * <p>Any open span is closed at the end of {@link #write(java.io.Writer)} * just before any open scope is closed. * @param className the class name for the new tag or {@code null} just to * close an open tag. * @throws IOException if an output error occurs */ private void disjointSpan(String className) throws IOException { disjointSpanClassName = JFlexXrefUtils.disjointSpan(out, className, disjointSpanClassName); } /** * Write xref to the specified {@code Writer}. * * @param out xref destination * @throws IOException on error when writing the xref */ @Override public void write(Writer out) throws IOException { this.out = out; if (defs != null) { defs.resetUnused(); } JFlexXrefUtils.writeSymbolTable(out, defs); startNewLine(); while (matcher.yylex() != matcher.getYYEOF()) { // NOPMD while statement intentionally empty // nothing to do here, yylex() will do the work } disjointSpan(null); // terminate scopes if (scopeOpen) { out.write("</span>"); scopeOpen = false; } while (!matcher.emptyStack()) { matcher.yypop(); } // Account for dangling line of code. Unlike line number, LOC is // incremented post- rather than pre-. if (didSeePhysicalLOC) { ++loc; didSeePhysicalLOC = false; } } /** * Terminate the current line and insert preamble for the next line. The * line count is taken from {@link ScanningSymbolMatcher#getLineNumber()}. * The lines-of-code count may be incremented if {@link #didSeePhysicalLOC} * has been set to {@code true} (after which it will be reset to * {@code false}). * @throws IOException on error when writing the xref */ public void startNewLine() throws IOException { String iconId = null; int line = matcher.getLineNumber(); boolean skipNl = false; if (didSeePhysicalLOC) { ++loc; didSeePhysicalLOC = false; } if (scopesEnabled) { startScope(); if (scopeOpen && scope == null) { scopeOpen = false; out.write("\n</span>"); skipNl = true; } else if (scope != null) { String scopeId = JFlexXrefUtils.generateId(scope); if (scope.getLineFrom() == line) { out.write("\n<span id='"); out.write(scopeId); out.write("' class='scope-head'><span class='scope-signature'>"); /* * It seems scope.getSignature() is sometimes null, so the * following can create values with "null" in the * concatenated string -- and tests are expecting that. */ Util.htmlize(scope.getName() + scope.getSignature(), out, PRE); out.write("</span>"); iconId = scopeId + "_fold_icon"; skipNl = true; } else if (scope.getLineFrom() == line - 1) { if (scopeOpen) { out.write("</span>"); } out.write("\n<span id='"); out.write(scopeId); out.write("_fold' class='scope-body'>"); skipNl = true; } scopeOpen = true; } } Util.readableLine(line, out, annotation, userPageLink, userPageSuffix, getProjectPostfix(true), skipNl); if (foldingEnabled && scopesEnabled) { if (iconId != null) { out.write("<a style='cursor:pointer;' onclick='fold(this.parentNode.id)' id='"); out.write(iconId); /* space inside span for IE support */ out.write("'><span class='fold-icon'>&nbsp;</span></a>"); } else { out.write("<span class='fold-space'>&nbsp;</span>"); } } } /** * Writes a keyword symbol. * * @param symbol the symbol to write * @param line the line number on which the symbol appears * @throws IOException if an error occurs while writing to the stream */ protected void writeKeyword(String symbol, int line) throws IOException { JFlexXrefUtils.writeSymbol(out, defs, urlPrefix, project, symbol, null, line, false, true); } /** * Calls {@link JFlexXrefUtils#writeUnicodeChar(java.io.Writer, char)} with * the active {@link Writer} and {@code c}. * @param c the character to write * @throws IOException if an error occurs while writing to the stream */ protected void writeUnicodeChar(char c) throws IOException { JFlexXrefUtils.writeUnicodeChar(out, c); } /** * Write an e-mail address. The address will be obfuscated if * {@link RuntimeEnvironment#isObfuscatingEMailAddresses()} returns * {@code true}. * * @param address the address to write * @throws IOException if an error occurs while writing to the stream */ protected void writeEMailAddress(String address) throws IOException { JFlexXrefUtils.writeEMailAddress(out, address); } }
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.subversion.remote.ui.update; import java.awt.Dialog; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.net.MalformedURLException; import java.util.logging.Level; import javax.swing.InputVerifier; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JRadioButton; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.JTextComponent; import org.netbeans.modules.subversion.remote.RepositoryFile; import org.netbeans.modules.subversion.remote.Subversion; import org.netbeans.modules.subversion.remote.api.SVNRevision; import org.netbeans.modules.subversion.remote.ui.browser.RepositoryPaths; import org.netbeans.modules.subversion.remote.ui.search.SvnSearch; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.util.HelpCtx; /** * * */ public class RevertModifications implements PropertyChangeListener { private RevertModificationsPanel panel; private JButton okButton; private JButton cancelButton; private RevertType[] types; public static class RevisionInterval { public RevisionInterval(SVNRevision revision) { this.startRevision = revision; this.endRevision = revision; } public RevisionInterval(SVNRevision startRevision, SVNRevision endRevision) { this.startRevision = startRevision; this.endRevision = endRevision; } SVNRevision startRevision; SVNRevision endRevision; } /** Creates a new instance of RevertModifications */ public RevertModifications(RepositoryFile repositoryFile) { this (repositoryFile, null); } /** Creates a new instance of RevertModifications */ public RevertModifications(RepositoryFile repositoryFile, String defaultRevision) { OneCommitRevertType ocrt = new OneCommitRevertType(repositoryFile, getPanel().oneCommitRadioButton); LocalRevertType lrt = new LocalRevertType(getPanel().localChangesRadioButton); types = new RevertType[] { lrt, ocrt, new MoreCommitsRevertType(repositoryFile, getPanel().moreCommitsRadioButton) }; okButton = new JButton(org.openide.util.NbBundle.getMessage(RevertModifications.class, "CTL_RevertForm_Action_Revert")); // NOI18N okButton.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(RevertModifications.class, "ACSD_RevertForm_Action_Revert")); // NOI18N cancelButton = new JButton(org.openide.util.NbBundle.getMessage(RevertModifications.class, "CTL_RevertForm_Action_Cancel")); // NOI18N cancelButton.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(RevertModifications.class, "ACSD_RevertForm_Action_Cancel")); // NOI18N if (defaultRevision != null) { panel.oneCommitRadioButton.setSelected(true); panel.oneRevisionTextField.setText(defaultRevision); ocrt.actionPerformed(null); } else { panel.localChangesRadioButton.setSelected(true); lrt.actionPerformed(null); } initInputVerifiers(); } private void initInputVerifiers () { InputVerifier iv = new InputVerifier() { @Override public boolean verify (JComponent input) { if (input == panel.startRevisionTextField || input == panel.endRevisionTextField || input == panel.oneRevisionTextField) { JTextComponent comp = (JTextComponent) input; if (comp.getText().trim().isEmpty()) { comp.setText(SVNRevision.HEAD.toString()); } } return true; } }; panel.startRevisionTextField.setInputVerifier(iv); panel.endRevisionTextField.setInputVerifier(iv); panel.oneRevisionTextField.setInputVerifier(iv); } private RevertModificationsPanel getPanel() { if(panel == null) { panel = new RevertModificationsPanel(); } return panel; } public RevisionInterval getRevisionInterval() { for (int i = 0; i < types.length; i++) { if(types[i].isSelected()) { return types[i].getRevisionInterval(); } } return null; } public boolean revertNewFiles() { for (int i = 0; i < types.length; i++) { if(types[i].isSelected()) { return types[i].revertNewFiles(); } } return false; } public boolean revertRecursively () { for (RevertType type : types) { if(type.isSelected()) { return type.revertRecursively(); } } return false; } public boolean showDialog() { DialogDescriptor dialogDescriptor = new DialogDescriptor(panel, org.openide.util.NbBundle.getMessage(RevertModifications.class, "CTL_RevertDialog")); // NOI18N dialogDescriptor.setOptions(new Object[] {okButton, cancelButton}); dialogDescriptor.setModal(true); dialogDescriptor.setHelpCtx(new HelpCtx(this.getClass())); dialogDescriptor.setValid(false); Dialog dialog = DialogDisplayer.getDefault().createDialog(dialogDescriptor); dialog.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(RevertModifications.class, "ACSD_RevertDialog")); // NOI18N dialog.setVisible(true); dialog.setResizable(false); boolean ret = dialogDescriptor.getValue() == okButton; return ret; } @Override public void propertyChange(PropertyChangeEvent evt) { if( evt.getPropertyName().equals(RepositoryPaths.PROP_VALID) ) { if(okButton != null) { boolean valid = ((Boolean)evt.getNewValue()).booleanValue(); okButton.setEnabled(valid); } } } protected void setMoreCommitsFieldsEnabled(boolean b) { getPanel().startRevisionTextField.setEnabled(b); getPanel().endRevisionTextField.setEnabled(b); getPanel().startSearchButton.setEnabled(b); getPanel().endSearchButton.setEnabled(b); } protected void setOneCommitFieldsEnabled(boolean b) { getPanel().oneRevisionSearchButton.setEnabled(b); getPanel().oneRevisionTextField.setEnabled(b); } protected final void setLocalModificationsFieldsEnabled (boolean b) { getPanel().cbRecursiveRevert.setEnabled(b); getPanel().revertNewFilesCheckBox.setEnabled(b); } private abstract class RevertType implements ActionListener, DocumentListener { private final JRadioButton button; RevertType(JRadioButton button) { this.button = button; button.addActionListener(this); } boolean isSelected() { return button.isSelected(); } boolean revertNewFiles() { return false; } boolean revertRecursively () { return true; } @Override public void insertUpdate(DocumentEvent e) { validateUserInput(); } @Override public void removeUpdate(DocumentEvent e) { validateUserInput(); } @Override public void changedUpdate(DocumentEvent e) { validateUserInput(); } void validateUserInput() { // default means nothing to do } RevisionInterval getRevisionInterval() { return null; // default means null } protected SVNRevision getRevision(RepositoryPaths path) { try { return path.getRepositoryFiles()[0].getRevision(); } catch (NumberFormatException ex) { // should be already checked and // not happen at this place anymore Subversion.LOG.log(Level.INFO, null, ex); } catch (MalformedURLException ex) { // should be already checked and // not happen at this place anymore Subversion.LOG.log(Level.INFO, null, ex); } return null; } protected boolean validateRevision(SVNRevision revision) { boolean valid = revision == null || revision.equals(SVNRevision.HEAD) || revision.getKind() == SVNRevision.Kind.number; RevertModifications.this.okButton.setEnabled(valid); return valid; } } private class LocalRevertType extends RevertType { LocalRevertType (JRadioButton button) { super(button); } @Override RevertModifications.RevisionInterval getRevisionInterval() { return null; } @Override public void actionPerformed(ActionEvent e) { setLocalModificationsFieldsEnabled(true); setOneCommitFieldsEnabled(false); setMoreCommitsFieldsEnabled(false); } @Override boolean revertRecursively () { return getPanel().cbRecursiveRevert.isSelected(); } @Override boolean revertNewFiles() { return panel.revertNewFilesCheckBox.isSelected(); } } private class OneCommitRevertType extends RevertType { private final RepositoryPaths oneRevisionPath; OneCommitRevertType (RepositoryFile repositoryFile, JRadioButton button) { super(button); oneRevisionPath = new RepositoryPaths( repositoryFile.getFileSystem(), repositoryFile, null, null, getPanel().oneRevisionTextField, getPanel().oneRevisionSearchButton ); oneRevisionPath.addPropertyChangeListener(RevertModifications.this); oneRevisionPath.setupBehavior(null, 0, null, SvnSearch.SEACRH_HELP_ID_REVERT); } @Override RevertModifications.RevisionInterval getRevisionInterval() { SVNRevision revision = getRevision(oneRevisionPath); RevisionInterval ret = new RevisionInterval(revision); return ret; } @Override void validateUserInput() { validateRevision(getRevision(oneRevisionPath)); } @Override public void actionPerformed(ActionEvent e) { setLocalModificationsFieldsEnabled(false); setOneCommitFieldsEnabled(true); setMoreCommitsFieldsEnabled(false); validateUserInput(); } } private class MoreCommitsRevertType extends RevertType { private final RepositoryPaths endPath; private final RepositoryPaths startPath; MoreCommitsRevertType (RepositoryFile repositoryFile, JRadioButton button) { super(button); startPath = new RepositoryPaths( repositoryFile.getFileSystem(), repositoryFile, null, null, getPanel().startRevisionTextField, getPanel().startSearchButton ); startPath.addPropertyChangeListener(RevertModifications.this); startPath.setupBehavior(null, 0, null, SvnSearch.SEACRH_HELP_ID_REVERT); endPath = new RepositoryPaths( repositoryFile.getFileSystem(), repositoryFile, null, null, getPanel().endRevisionTextField, getPanel().endSearchButton ); endPath.addPropertyChangeListener(RevertModifications.this); endPath.setupBehavior(null, 0, null, SvnSearch.SEACRH_HELP_ID_REVERT); } @Override RevertModifications.RevisionInterval getRevisionInterval() { SVNRevision revision1 = getRevision(startPath); SVNRevision revision2 = getRevision(endPath); if(revision1 == null || revision2 == null) { return null; } return getResortedRevisionInterval(revision1, revision2); } @Override void validateUserInput() { if(!validateRevision(getRevision(startPath))) { return; } if(!validateRevision(getRevision(endPath))) { return; } } @Override public void actionPerformed(ActionEvent e) { setLocalModificationsFieldsEnabled(false); setMoreCommitsFieldsEnabled(true); setOneCommitFieldsEnabled(false); validateUserInput(); } private RevisionInterval getResortedRevisionInterval(SVNRevision revision1, SVNRevision revision2) { RevisionInterval ret; if(revision1.equals(SVNRevision.HEAD) && revision2.equals(SVNRevision.HEAD)) { ret = new RevisionInterval (revision1, revision2); } else if (revision1.equals(SVNRevision.HEAD)) { ret = new RevisionInterval (revision2, revision1); } else if (revision2.equals(SVNRevision.HEAD)) { ret = new RevisionInterval (revision1, revision2); } else { Long r1 = Long.parseLong(revision1.toString()); Long r2 = Long.parseLong(revision2.toString()); if(r1.compareTo(r2) < 0) { ret = new RevisionInterval (revision1, revision2); } else { ret = new RevisionInterval (revision2, revision1); } } return ret; } } }
package pithreads.examples.tut6.collectingVotes.broadcastAndCollect; import pithreads.framework.PiAgent; import pithreads.framework.PiChannel; import pithreads.framework.RunException; import pithreads.framework.Task; import pithreads.framework.broadcast.PiChannelBroadcast; import pithreads.framework.broadcast.PiThreadBroadcast; import pithreads.framework.debug.DebugFactory; import pithreads.framework.debug.PiFactory; public class PollingBooth2 { private static final int NBVOTERS = 5; private static final int TURNS = 15; public static void main(String... args) { PiFactory myFactory = new DebugFactory(false); PiAgent agent = myFactory.newPiAgent(); final PiChannelBroadcast<PiChannel<Boolean>> vote = myFactory.newPiChannelBroadcast(agent,"vote"); for(int i = 0;i<NBVOTERS;i++){ PiThreadBroadcast voter = myFactory.newPiThreadBroadcast(agent, "voter#"+i); Voter2 taskVoter = new Voter2(vote,i); voter.assign(taskVoter); voter.start(); } Task ifYes = new Task(){ @Override public void body() throws RunException { log("global decision is YES"); } }; Task ifNo = new Task(){ @Override public void body() throws RunException { log("global decision is NO"); } }; PiThreadBroadcast coordinator = myFactory.newPiThreadBroadcast(agent,"coordinator"); Coordinator2 taskCoordinator = new Coordinator2(vote,TURNS,ifYes,ifNo); coordinator.assign(taskCoordinator); coordinator.start(); agent.detach(); } }
/****************************************************************************** * This research was sponsored by the U.S. Army Research Laboratory and the * U.K. Ministry of Defence under the Biennial Program Plane 2013 (BPP13), * Project 6, Task 3: Collaborative Intelligence Analysis. * The U.S. and U.K. Governments are authorized to reproduce and distribute * reprints for Government purposes notwithstanding any copyright notation * hereon. * ************************************************************************** * * * * @author Alice Toniolo * @version 1.0 * @since October 2014 * */ package plots; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import javax.imageio.ImageIO; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import provservice.JsonHelper; import com.google.gson.internal.LinkedTreeMap; /** * Servlet implementation class PlotServlet */ public class PlotProvServlet extends HttpServlet implements javax.servlet.Servlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ private String path; private String port; private String host; private String folder; private Boolean printnodes; private String ci_path; private JsonHelper jsh; public PlotProvServlet () { // TODO Auto-generated constructor stub super(); String pathfile=System.getenv("CATALINA_HOME"); if(pathfile==null){ path="./bin/provpng/"; folder="./bin/provpng"; }else{ path=pathfile+"/bin/provpng/"; folder=pathfile+"/bin/provpng"; } } @Override public void init(ServletConfig config) throws ServletException { ci_path=System.getenv("CISPACES"); try { String content = new String(Files.readAllBytes(Paths.get(ci_path+"/code/config/cis_settings.txt"))); //System.out.println(content); jsh=new JsonHelper(); HashMap settings=jsh.convertInputMap(content); LinkedTreeMap servers=(LinkedTreeMap) settings.get("Servers"); LinkedTreeMap provd=(LinkedTreeMap) servers.get("ProvDM"); port=(String) provd.get("port"); host=(String) provd.get("host_name"); } catch (Exception e) { } if(!test()){ //else read web.xml try { // System.out.println("hello2"); port=config.getInitParameter("port"); host=config.getInitParameter("host_name"); } catch (Exception e) { } } if(!test()){ // System.out.println("hello3"); //else set default port="8080"; host="localhost"; } printnodes=Boolean.parseBoolean(config.getInitParameter("aprov_print_nodes")); } private boolean test(){ if(port==null || host==null) return false; return true; } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String cmd; //System.out.println(request.toString()); createFolder(folder); cmd = request.getParameter("action"); // System.out.println(cmd); if (cmd != null) { /* * action: byloc byday byquest byans */ if (cmd.equals("printprov")) { goPrintProv(request, response); } } } private void goPrintProv(HttpServletRequest request, HttpServletResponse response) { String json=request.getParameter("json"); json=json.substring(0, json.lastIndexOf("}")+1); ProvControl cont=new ProvControl(path,port,host,printnodes); //System.out.println(json); String image=cont.getProv(json); response.setContentType("image/png"); /* Set the HTTP Response Type */ if(!image.equals("fail")){ //System.out.println(json); File f = new File(path+image+ "prov.png"); //System.out.print("HELLO!"+pathToWeb); OutputStream out; BufferedImage bi; try { bi = ImageIO.read(f); out = response.getOutputStream(); ImageIO.write(bi, "png", out); out.flush(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /* * http://localhost:8080/provgraphs/Prov?action=printprov&json={"request":"getprovnode","nodeID":"d2a0848e-e6e0-41huufb-b711-49dyfghhb96a","text": "Info pippo","source": "USERPIPPO", "dtg": "2014/08/13 01:19:17"} http://localhost:8080/provgraphs/Prov?action=printprov&json={"dtg":"2014/08/21 03:29:56","text":"The gang G is crossing the north border","request":"getprovnode","nodeID":"dadbcbd9-5963-4f42-920c-c6640e7c1815","source":"MessageReceived"} */ /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String cmd; //System.out.println(request.toString()); createFolder(folder); cmd = request.getParameter("action"); // System.out.println(cmd); if (cmd != null) { /* * action: byloc byday byquest byans */ if (cmd.equals("printprov")) { goPrintProv(request, response); } } } public void createFolder(String folderName){ File file = new File(folderName); if (!file.exists()) { file.mkdir(); } } }
package validation.leaf.is.of.value.equalto.booolean.trooe; import validation.Validatable; import validation.result.*; import validation.result.error.Error; // doc: all validatables are successful if the corresponding field is absent. // If you want it to be required, specify it explicitly. final public class IsTrue implements Validatable<Boolean> { private Validatable<Boolean> original; private Error error; public IsTrue(Validatable<Boolean> original, Error error) throws Exception { if (original == null) { throw new Exception("Decorated validatable element can not be null"); } if (error == null) { throw new Exception("Error can not be null"); } this.original = original; this.error = error; } public IsTrue(Validatable<Boolean> original) throws Exception { this(original, new MustBeTrue()); } public Result<Boolean> result() throws Exception { Result<Boolean> asBoolean = this.original.result(); if (!asBoolean.isSuccessful() || !asBoolean.value().isPresent()) { return asBoolean; } if (!asBoolean.value().raw().equals(true)) { return new NonSuccessfulWithCustomError<>(asBoolean, this.error); } return new SuccessfulWithCustomValue<>(asBoolean, asBoolean.value().raw()); } }
// // Decompiled by Procyon v0.5.36 // package org.codehaus.groovy.ast.expr; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; public class SpreadExpression extends Expression { private final Expression expression; public SpreadExpression(final Expression expression) { this.expression = expression; } public Expression getExpression() { return this.expression; } @Override public void visit(final GroovyCodeVisitor visitor) { visitor.visitSpreadExpression(this); } @Override public Expression transformExpression(final ExpressionTransformer transformer) { final Expression ret = new SpreadExpression(transformer.transform(this.expression)); ret.setSourcePosition(this); return ret; } @Override public String getText() { return "*" + this.expression.getText(); } @Override public ClassNode getType() { return this.expression.getType(); } }
/** * Copyright (C) 2014-2018 LinkedIn Corp. (pinot-core@linkedin.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.thirdeye.datalayer.entity; import com.linkedin.thirdeye.api.DimensionMap; public class MergedAnomalyResultIndex extends AbstractIndexEntity { long functionId; long detectionConfigId; long anomalyFeedbackId; long metricId; long startTime; long endTime; String collection; String metric; DimensionMap dimensions; boolean notified; public long getDetectionConfigId() { return detectionConfigId; } public void setDetectionConfigId(long detectionConfigId) { this.detectionConfigId = detectionConfigId; } public long getAnomalyFeedbackId() { return anomalyFeedbackId; } public void setAnomalyFeedbackId(long anomalyFeedbackId) { this.anomalyFeedbackId = anomalyFeedbackId; } public long getFunctionId() { return functionId; } public void setFunctionId(long anomalyFunctionId) { this.functionId = anomalyFunctionId; } public String getCollection() { return collection; } public void setCollection(String collection) { this.collection = collection; } public DimensionMap getDimensions() { return dimensions; } public void setDimensions(DimensionMap dimensions) { this.dimensions = dimensions; } public long getEndTime() { return endTime; } public void setEndTime(long endTime) { this.endTime = endTime; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public long getMetricId() { return metricId; } public void setMetricId(long metricId) { this.metricId = metricId; } public long getStartTime() { return startTime; } public void setStartTime(long startTime) { this.startTime = startTime; } public boolean isNotified() { return notified; } public void setNotified(boolean notified) { this.notified = notified; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pinot.core.segment.creator; public enum TextIndexType { NONE, LUCENE }
class Solution { public void moveZeroes(int[] nums) { int n = nums.length, left = 0, right = 0; while(right < n){ if(nums[right] != 0){ swap(nums, left, right); left++; } right++; } } private void swap(int[] nums, int left, int right){ int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; } }
package com.mz.jarboot.api.exception; /** * @author jianzhengma */ public class JarbootRunException extends RuntimeException { private static final long serialVersionUID = 3513491993982293262L; public JarbootRunException(String errMsg) { super(errMsg); } public JarbootRunException(Throwable throwable) { super(throwable); } public JarbootRunException(String errMsg, Throwable throwable) { super(errMsg, throwable); } }
package org.owasp.webgoat.plugin; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import org.owasp.webgoat.users.WebGoatUser; @RunWith(MockitoJUnitRunner.class) public class DisplayUserTest { @Test public void TestDisplayUserCreation() { DisplayUser displayUser = new DisplayUser(new WebGoatUser("user1","password1")); assert(!displayUser.isAdmin()); } @Test public void TesDisplayUserHash() { DisplayUser displayUser = new DisplayUser(new WebGoatUser("user1","password1")); assert(displayUser.getUserHash().equals("cplTjehjI/e5ajqTxWaXhU5NW9UotJfXj+gcbPvfWWc=")); } }
package okhttp3; import org.junit.jupiter.api.Test; import java.util.Objects; public class HttpUrlTest { @Test void get() { HttpUrl httpUrl = HttpUrl.get("https://www.baidu.com"); System.out.println(httpUrl); } @Test void resolve() { HttpUrl httpUrl = HttpUrl.get("https://www.baidu.com"); httpUrl = httpUrl.resolve("s"); System.out.println(httpUrl); } @Test void newBuilder() { HttpUrl httpUrl = HttpUrl.get("https://www.baidu.com"); httpUrl = Objects.requireNonNull(httpUrl.newBuilder("s")).build(); System.out.println(httpUrl); } @Test void addPathSegment() { HttpUrl httpUrl = HttpUrl.get("https://www.baidu.com").newBuilder().addPathSegment("img").addPathSegment("flexible").build(); System.out.println(httpUrl); } }
/* * 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 com.alibaba.dubbo.rpc.filter; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.beanutil.JavaBeanAccessor; import com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor; import com.alibaba.dubbo.common.beanutil.JavaBeanSerializeUtil; import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; import com.alibaba.dubbo.common.serialize.Serialization; import com.alibaba.dubbo.common.utils.PojoUtils; import com.alibaba.dubbo.common.utils.ReflectUtils; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.rpc.Filter; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcContext; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.RpcInvocation; import com.alibaba.dubbo.rpc.RpcResult; import com.alibaba.dubbo.rpc.service.GenericException; import com.alibaba.dubbo.rpc.service.GenericService; import com.alibaba.dubbo.rpc.support.ProtocolUtils; import java.io.IOException; import java.lang.reflect.Method; /** * GenericInvokerFilter. */ // @Activate(group = Constants.PROVIDER, order = -20000) public class GenericFilter implements Filter { @Override public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals(Constants.$INVOKE) && inv.getArguments() != null && inv.getArguments().length == 3 && !invoker.getInterface().equals(GenericService.class)) { String name = ((String) inv.getArguments()[0]).trim(); String[] types = (String[]) inv.getArguments()[1]; Object[] args = (Object[]) inv.getArguments()[2]; try { Method method = ReflectUtils.findMethodByMethodSignature(invoker.getInterface(), name, types); Class<?>[] params = method.getParameterTypes(); if (args == null) { args = new Object[params.length]; } String generic = inv.getAttachment(Constants.GENERIC_KEY); if (StringUtils.isBlank(generic)) { generic = RpcContext.getContext().getAttachment(Constants.GENERIC_KEY); } if (StringUtils.isEmpty(generic) || ProtocolUtils.isDefaultGenericSerialization(generic)) { args = PojoUtils.realize(args, params, method.getGenericParameterTypes()); } else if (ProtocolUtils.isJavaGenericSerialization(generic)) { for (int i = 0; i < args.length; i++) { if (byte[].class == args[i].getClass()) { try { UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream((byte[]) args[i]); args[i] = ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA) .deserialize(null, is).readObject(); } catch (Exception e) { throw new RpcException("Deserialize argument [" + (i + 1) + "] failed.", e); } } else { throw new RpcException( "Generic serialization [" + Constants.GENERIC_SERIALIZATION_NATIVE_JAVA + "] only support message type " + byte[].class + " and your message type is " + args[i].getClass()); } } } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { for (int i = 0; i < args.length; i++) { if (args[i] instanceof JavaBeanDescriptor) { args[i] = JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) args[i]); } else { throw new RpcException( "Generic serialization [" + Constants.GENERIC_SERIALIZATION_BEAN + "] only support message type " + JavaBeanDescriptor.class.getName() + " and your message type is " + args[i].getClass().getName()); } } } Result result = invoker.invoke(new RpcInvocation(method, args, inv.getAttachments())); if (result.hasException() && !(result.getException() instanceof GenericException)) { return new RpcResult(new GenericException(result.getException())); } if (ProtocolUtils.isJavaGenericSerialization(generic)) { try { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512); ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA) .serialize(null, os).writeObject(result.getValue()); return new RpcResult(os.toByteArray()); } catch (IOException e) { throw new RpcException("Serialize result failed.", e); } } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { return new RpcResult(JavaBeanSerializeUtil.serialize(result.getValue(), JavaBeanAccessor.METHOD)); } else { return new RpcResult(PojoUtils.generalize(result.getValue())); } } catch (NoSuchMethodException e) { throw new RpcException(e.getMessage(), e); } catch (ClassNotFoundException e) { throw new RpcException(e.getMessage(), e); } } return invoker.invoke(inv); } }
/** */ package com.model.dao; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Monitor; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import swing2swt.layout.BorderLayout; import org.eclipse.swt.widgets.Table; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.layout.GridData; import org.sql2o.Connection; import com.DbHelper; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.wb.swt.SWTResourceManager; public class KetquaXnListDlg extends Dialog { static Logger logger = LogManager.getLogger(KetquaXnListDlg.class.getName()); protected Object result; protected Shell shell; private class TableLabelProviderKetquaXn extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { if(element instanceof KetquaXn){ return ((KetquaXn) element).getIndex(columnIndex); } return ""; } } private static class ContentProviderKetquaXn implements IStructuredContentProvider { public Object[] getElements(Object inputElement) { if(inputElement instanceof ArrayList){ return ((ArrayList) inputElement).toArray(); } return new Object[0]; } public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } } private Table tableKetquaXn; private TableViewer tableViewerKetquaXn; private List<KetquaXn> listDataKetquaXn; private Text textSearchKetquaXn; private String textSearchKetquaXnString; public KetquaXn objKetquaXn = null; public int typeKetquaXnDlg = TYPE_DLG_CHOOSEN; public static final int TYPE_DLG_MANAGER = 0; public static final int TYPE_DLG_CHOOSEN = 1; public int intTypeDlgKetquaXn; public static final int TYPE_DLG_VIEW = 1; public static final int TYPE_DLG_EDIT = 2; /** * Create the dialog. * @param parent * @param style */ public KetquaXnListDlg(Shell parent, int style) { super(parent, style); setText("SWT Dialog"); } /** * Open the dialog. * @return the result */ public Object open() { createContents(); shell.open(); shell.layout(); Display display = getParent().getDisplay(); // Monitor primary = display.getPrimaryMonitor(); Rectangle bounds = primary.getBounds(); Rectangle rect = shell.getBounds(); int x = bounds.x + (bounds.width - rect.width) / 2; int y = bounds.y + (bounds.height - rect.height) / 2; shell.setLocation(x, y); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return result; } /** * Create contents of the dialog. */ private void createContents() { shell = new Shell(getParent(), SWT.SHELL_TRIM | SWT.BORDER | SWT.PRIMARY_MODAL); shell.setImage(SWTResourceManager.getImage(KetquaXnDlg.class, "/png/list-2x.png")); shell.setSize(610, 340); shell.setText("KetquaXn List View"); shell.setLayout(new BorderLayout(0, 0)); shell.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.keyCode==SWT.ESC){ objKetquaXn = null; } } }); Composite compositeInShellKetquaXn = new Composite(shell, SWT.NONE); compositeInShellKetquaXn.setLayout(new BorderLayout(0, 0)); compositeInShellKetquaXn.setLayoutData(BorderLayout.CENTER); Composite compositeHeaderKetquaXn = new Composite(compositeInShellKetquaXn, SWT.NONE); compositeHeaderKetquaXn.setLayoutData(BorderLayout.NORTH); compositeHeaderKetquaXn.setLayout(new GridLayout(2, false)); textSearchKetquaXn = new Text(compositeHeaderKetquaXn, SWT.BORDER); textSearchKetquaXn.setFont(SWTResourceManager.getFont("Tahoma", 11, SWT.NORMAL)); textSearchKetquaXn.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.keyCode==13){ reloadTableKetquaXn(); } } }); Button btnNewButtonSearchKetquaXn = new Button(compositeHeaderKetquaXn, SWT.NONE); btnNewButtonSearchKetquaXn.setImage(SWTResourceManager.getImage(KetquaXnDlg.class, "/png/media-play-2x.png")); btnNewButtonSearchKetquaXn.setFont(SWTResourceManager.getFont("Tahoma", 12, SWT.NORMAL)); btnNewButtonSearchKetquaXn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { reloadTableKetquaXn(); } }); GridData gd_btnNewButtonKetquaXn = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnNewButtonKetquaXn.widthHint = 87; btnNewButtonSearchKetquaXn.setLayoutData(gd_btnNewButtonKetquaXn); btnNewButtonSearchKetquaXn.setText("Search"); tableViewerKetquaXn = new TableViewer(compositeInShellKetquaXn, SWT.BORDER | SWT.FULL_SELECTION); tableKetquaXn = tableViewerKetquaXn.getTable(); tableKetquaXn.setFont(SWTResourceManager.getFont("Tahoma", 11, SWT.NORMAL)); tableKetquaXn.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.keyCode==SWT.F5){ reloadTableKetquaXn(); } if(e.keyCode==SWT.F4){ editTableKetquaXn(); } else if(e.keyCode==13){ selectTableKetquaXn(); } else if(e.keyCode==SWT.DEL){ deleteTableKetquaXn(); } else if(e.keyCode==SWT.F7){ newItemKetquaXn(); } } }); tableKetquaXn.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { selectTableKetquaXn(); } }); tableKetquaXn.setLinesVisible(true); tableKetquaXn.setHeaderVisible(true); tableKetquaXn.setLayoutData(BorderLayout.CENTER); TableColumn tbTableColumnKetquaXnCS_ID = new TableColumn(tableKetquaXn, SWT.RIGHT); tbTableColumnKetquaXnCS_ID.setWidth(100); tbTableColumnKetquaXnCS_ID.setText("CS_ID"); TableColumn tbTableColumnKetquaXnDV_ID = new TableColumn(tableKetquaXn, SWT.RIGHT); tbTableColumnKetquaXnDV_ID.setWidth(100); tbTableColumnKetquaXnDV_ID.setText("DV_ID"); TableColumn tbTableColumnKetquaXnMA_DVKT = new TableColumn(tableKetquaXn, SWT.LEFT); tbTableColumnKetquaXnMA_DVKT.setWidth(100); tbTableColumnKetquaXnMA_DVKT.setText("MA_DVKT"); TableColumn tbTableColumnKetquaXnTEN_DVKT = new TableColumn(tableKetquaXn, SWT.LEFT); tbTableColumnKetquaXnTEN_DVKT.setWidth(100); tbTableColumnKetquaXnTEN_DVKT.setText("TEN_DVKT"); TableColumn tbTableColumnKetquaXnCS_NAME = new TableColumn(tableKetquaXn, SWT.LEFT); tbTableColumnKetquaXnCS_NAME.setWidth(100); tbTableColumnKetquaXnCS_NAME.setText("CS_NAME"); TableColumn tbTableColumnKetquaXnCS_VALUE = new TableColumn(tableKetquaXn, SWT.LEFT); tbTableColumnKetquaXnCS_VALUE.setWidth(100); tbTableColumnKetquaXnCS_VALUE.setText("CS_VALUE"); TableColumn tbTableColumnKetquaXnCS_RANGE1 = new TableColumn(tableKetquaXn, SWT.LEFT); tbTableColumnKetquaXnCS_RANGE1.setWidth(100); tbTableColumnKetquaXnCS_RANGE1.setText("CS_RANGE1"); TableColumn tbTableColumnKetquaXnCS_RANGE2 = new TableColumn(tableKetquaXn, SWT.LEFT); tbTableColumnKetquaXnCS_RANGE2.setWidth(100); tbTableColumnKetquaXnCS_RANGE2.setText("CS_RANGE2"); TableColumn tbTableColumnKetquaXnCS_DEFAULT = new TableColumn(tableKetquaXn, SWT.LEFT); tbTableColumnKetquaXnCS_DEFAULT.setWidth(100); tbTableColumnKetquaXnCS_DEFAULT.setText("CS_DEFAULT"); TableColumn tbTableColumnKetquaXnIMAGE_URL = new TableColumn(tableKetquaXn, SWT.LEFT); tbTableColumnKetquaXnIMAGE_URL.setWidth(100); tbTableColumnKetquaXnIMAGE_URL.setText("IMAGE_URL"); TableColumn tbTableColumnKetquaXnMA_MAY = new TableColumn(tableKetquaXn, SWT.LEFT); tbTableColumnKetquaXnMA_MAY.setWidth(100); tbTableColumnKetquaXnMA_MAY.setText("MA_MAY"); TableColumn tbTableColumnKetquaXnMO_TA = new TableColumn(tableKetquaXn, SWT.LEFT); tbTableColumnKetquaXnMO_TA.setWidth(100); tbTableColumnKetquaXnMO_TA.setText("MO_TA"); TableColumn tbTableColumnKetquaXnKET_LUAN = new TableColumn(tableKetquaXn, SWT.LEFT); tbTableColumnKetquaXnKET_LUAN.setWidth(100); tbTableColumnKetquaXnKET_LUAN.setText("KET_LUAN"); TableColumn tbTableColumnKetquaXnSTS = new TableColumn(tableKetquaXn, SWT.RIGHT); tbTableColumnKetquaXnSTS.setWidth(100); tbTableColumnKetquaXnSTS.setText("STS"); Menu menuKetquaXn = new Menu(tableKetquaXn); tableKetquaXn.setMenu(menuKetquaXn); MenuItem mntmNewItemKetquaXn = new MenuItem(menuKetquaXn, SWT.NONE); mntmNewItemKetquaXn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { newItemKetquaXn(); } }); mntmNewItemKetquaXn.setImage(SWTResourceManager.getImage(KetquaXnDlg.class, "/png/arrow-circle-top-2x.png")); mntmNewItemKetquaXn.setText("New"); MenuItem mntmEditItemKetquaXn = new MenuItem(menuKetquaXn, SWT.NONE); mntmEditItemKetquaXn.setImage(SWTResourceManager.getImage(KetquaXnDlg.class, "/png/wrench-2x.png")); mntmEditItemKetquaXn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editTableKetquaXn(); } }); mntmEditItemKetquaXn.setText("Edit"); MenuItem mntmDeleteKetquaXn = new MenuItem(menuKetquaXn, SWT.NONE); mntmDeleteKetquaXn.setImage(SWTResourceManager.getImage(KetquaXnDlg.class, "/png/circle-x-2x.png")); mntmDeleteKetquaXn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { deleteTableKetquaXn(); } }); mntmDeleteKetquaXn.setText("Delete"); tableViewerKetquaXn.setLabelProvider(new TableLabelProviderKetquaXn()); tableViewerKetquaXn.setContentProvider(new ContentProviderKetquaXn()); tableViewerKetquaXn.setInput(listDataKetquaXn); // // loadDataKetquaXn(); // reloadTableKetquaXn(); } public void setDataKetquaXn(String textSearchString){ this.textSearchKetquaXnString = textSearchString; } private void loadDataKetquaXn() { if(textSearchKetquaXnString!=null){ textSearchKetquaXn.setText(textSearchKetquaXnString); } } protected void reloadTableKetquaXn() { if(DbHelper.checkPhanQuyen(DbHelper.READ, "ketqua_xn")==false){ logger.info("DON'T HAVE READ RIGHT"); return; } if(listDataKetquaXn!=null){ // tableViewerKetquaXn.setInput(listDataKetquaXn); tableViewerKetquaXn.refresh(); // if(listDataKetquaXn.size()==0){ textSearchKetquaXn.forceFocus(); } else{ tableKetquaXn.forceFocus(); tableKetquaXn.setSelection(0); } return; } // Do search in the first time String searchString = textSearchKetquaXn.getText().toLowerCase().trim(); String sql = "select * from ketqua_xn WHERE STS<> "+DbHelper.DELETE_STATUS+" "; if(searchString.length()>0){ sql += " and ( 0 "; sql += " or LOWER(MA_DVKT) like '%"+searchString+"%'"; sql += " or LOWER(TEN_DVKT) like '%"+searchString+"%'"; sql += " or LOWER(CS_NAME) like '%"+searchString+"%'"; sql += " or LOWER(CS_VALUE) like '%"+searchString+"%'"; sql += " or LOWER(CS_RANGE1) like '%"+searchString+"%'"; sql += " or LOWER(CS_RANGE2) like '%"+searchString+"%'"; sql += " or LOWER(CS_DEFAULT) like '%"+searchString+"%'"; sql += " or LOWER(IMAGE_URL) like '%"+searchString+"%'"; sql += " or LOWER(MA_MAY) like '%"+searchString+"%'"; sql += " or LOWER(MO_TA) like '%"+searchString+"%'"; sql += " or LOWER(KET_LUAN) like '%"+searchString+"%'"; sql += " )"; } try { logger.info(sql); Connection con = DbHelper.getSql2o(); listDataKetquaXn = con.createQuery(sql).executeAndFetch(KetquaXn.class); } catch(Exception e){ logger.error(e); MessageDialog.openError(shell, "Error", e.getMessage()); } // tableViewerKetquaXn.setInput(listDataKetquaXn); tableViewerKetquaXn.refresh(); // if(listDataKetquaXn.size()==0){ textSearchKetquaXn.forceFocus(); } else{ tableKetquaXn.forceFocus(); tableKetquaXn.setSelection(0); } } protected void selectTableKetquaXn() { if(tableKetquaXn.getSelectionCount()==0){ return; } TableItem item = tableKetquaXn.getSelection()[0]; KetquaXn obj = (KetquaXn)item.getData(); logger.info(obj.toString()); // // if(typeKetquaXnDlg==TYPE_DLG_CHOOSEN){ // Choosen and close dlg objKetquaXn = obj; shell.close(); } else{ if(DbHelper.checkPhanQuyen(DbHelper.UPDATE, "ketqua_xn")==false){ logger.info("DON'T HAVE UPDATE RIGHT"); return; } if(intTypeDlgKetquaXn==TYPE_DLG_VIEW){ return; } KetquaXnDlg dlg = new KetquaXnDlg(shell, 0); dlg.setKetquaXnDlgData(obj); dlg.open(); // reloadTableKetquaXn(); } } protected void editTableKetquaXn() { if(intTypeDlgKetquaXn==TYPE_DLG_VIEW){ return; } if(DbHelper.checkPhanQuyen(DbHelper.UPDATE, "ketqua_xn")==false){ logger.info("DON'T HAVE UPDATE RIGHT"); return; } if(tableKetquaXn.getSelectionCount()==0){ return; } TableItem item = tableKetquaXn.getSelection()[0]; KetquaXn obj = (KetquaXn)item.getData(); logger.info(obj.toString()); // // KetquaXnDlg dlg = new KetquaXnDlg(shell, 0); dlg.setKetquaXnDlgData(obj); dlg.open(); // reloadTableKetquaXn(); } protected void deleteTableKetquaXn() { if(intTypeDlgKetquaXn==TYPE_DLG_VIEW){ return; } // if(DbHelper.checkPhanQuyen(DbHelper.DELETE, "ketqua_xn")==false){ logger.info("DON'T HAVE DELETE RIGHT"); return; } if(tableKetquaXn.getSelectionCount()==0){ return; } if(MessageDialog.openConfirm(shell, "Confirm?", "Delete ?")==false){ return; } TableItem item = tableKetquaXn.getSelection()[0]; KetquaXn obj = (KetquaXn)item.getData(); logger.info(obj.toString()); // obj.delete(); listDataKetquaXn.remove(obj); // reloadTableKetquaXn(); } protected void newItemKetquaXn() { if(intTypeDlgKetquaXn==TYPE_DLG_VIEW){ return; } // if(DbHelper.checkPhanQuyen(DbHelper.INSERT, "ketqua_xn")==false){ logger.info("DON'T HAVE INSERT RIGHT"); return; } // KetquaXnDlg dlg = new KetquaXnDlg(shell, 0); KetquaXn obj = new KetquaXn(); dlg.setKetquaXnDlgData(obj); dlg.open(); listDataKetquaXn.add(obj); // reloadTableKetquaXn(); // } }
package com.company.project.controller; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.company.project.common.aop.annotation.DataScope; import com.company.project.common.aop.annotation.LogAnnotation; import com.company.project.common.enums.GrowthValueDetailsTypeEnum; import com.company.project.common.utils.NumberConstants; import io.swagger.annotations.Api; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.commons.lang.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.stereotype.Controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.core.metadata.IPage; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import java.util.List; import com.company.project.common.utils.DataResult; import com.company.project.entity.ShopMemberGrowthValueRecordEntity; import com.company.project.service.ShopMemberGrowthValueRecordService; import javax.annotation.Resource; /** * 会员成长值记录 * * @author zhoushuai * @email zhoushuai_0726@163.com * @date 2021-07-09 17:10:36 */ @Api(tags = "会员成长值记录") @Controller @RequestMapping("/") public class ShopMemberGrowthValueRecordController extends BaseController { @Resource private ShopMemberGrowthValueRecordService shopMemberGrowthValueRecordService; @ApiOperation(value = "新增") @PostMapping("shopMemberGrowthValueRecord/add") @RequiresPermissions("shopMember:add") @LogAnnotation(title = "会员成长值记录", action = "新增") @ResponseBody public DataResult add(@RequestBody ShopMemberGrowthValueRecordEntity shopMemberGrowthValueRecord) { // 类型:管理员修改 shopMemberGrowthValueRecord.setType(GrowthValueDetailsTypeEnum.ADMIN_UPDATE.getType()); return shopMemberGrowthValueRecordService.saveShopMemberGrowthValueRecordEntity(shopMemberGrowthValueRecord); } @ApiOperation(value = "删除") @DeleteMapping("shopMemberGrowthValueRecord/delete") @RequiresPermissions("shopMember:delete") @LogAnnotation(title = "会员成长值记录", action = "删除") @ResponseBody public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids){ return DataResult.success(shopMemberGrowthValueRecordService.removeByIds(ids)); } @ApiOperation(value = "更新") @PutMapping("shopMemberGrowthValueRecord/update") @RequiresPermissions("shopMember:update") @LogAnnotation(title = "会员成长值记录", action = "更新") @ResponseBody public DataResult update(@RequestBody ShopMemberGrowthValueRecordEntity shopMemberGrowthValueRecord){ return DataResult.success(shopMemberGrowthValueRecordService.updateById(shopMemberGrowthValueRecord)); } @ApiOperation(value = "查询分页数据") @PostMapping("shopMemberGrowthValueRecord/listByPage") @RequiresPermissions("shopMember:list") @LogAnnotation(title = "会员成长值记录", action = "查询分页数据") @DataScope @ResponseBody public DataResult findListByPage(@RequestBody ShopMemberGrowthValueRecordEntity shopMemberGrowthValueRecord){ // 查询条件 LambdaQueryWrapper<ShopMemberGrowthValueRecordEntity> queryWrapper = Wrappers.lambdaQuery(); queryWrapper .eq(ShopMemberGrowthValueRecordEntity::getMemberId, shopMemberGrowthValueRecord.getMemberId()) .like(StringUtils.isNotBlank(shopMemberGrowthValueRecord.getRemark()), ShopMemberGrowthValueRecordEntity::getRemark, shopMemberGrowthValueRecord.getRemark()) .orderByDesc(ShopMemberGrowthValueRecordEntity::getCreateTime, ShopMemberGrowthValueRecordEntity::getId); return DataResult.success(shopMemberGrowthValueRecordService.listByPage(new Page<>(shopMemberGrowthValueRecord.getPage(), shopMemberGrowthValueRecord.getLimit()), queryWrapper)); } }
package adrninistrator.test.testdatabase.rollback; import adrninistrator.test.base.TestDbRollbackBase; import adrninistrator.test.common.TestIdGen; import adrninistrator.test.testdatabase.TestDbEntityGen; import com.adrninistrator.common.constants.TestConstants; import com.adrninistrator.dao.TestTableMapper; import com.adrninistrator.dao.entity.TestTableEntity; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import static org.junit.Assert.assertEquals; /* 测试数据库操作是否回滚 类级别使用@Rollback注解,指定需要回滚 */ @Rollback public class TestDBRB_CY2 extends TestDbRollbackBase { @Autowired private TestTableMapper testTableMapper; @Test public void test() { String id = TestIdGen.genId(); TestTableEntity testTableEntity1 = TestDbEntityGen.genEntity1(id, TestConstants.FLAG1); // 执行插入 int row = testTableMapper.insert(testTableEntity1); assertEquals(1, row); } }
package com.sap.gtt.v2.sample.sof.rest.controller.service; import com.sap.gtt.v2.sample.sof.constant.Constants; import com.sap.gtt.v2.sample.sof.constant.FulfillmentProcessMilestoneEnum; import com.sap.gtt.v2.sample.sof.domain.ProcessEventDirectory; import com.sap.gtt.v2.sample.sof.domain.TrackedProcess; import com.sap.gtt.v2.sample.sof.odata.filter.FilterCondition; import com.sap.gtt.v2.sample.sof.odata.filter.FilterExpressionBuilder; import com.sap.gtt.v2.sample.sof.odata.model.DeliveryItem; import com.sap.gtt.v2.sample.sof.odata.model.SalesOrderItem; import com.sap.gtt.v2.sample.sof.rest.controller.domain.fulfillmentprocessflow.FulfillmentProcessFlow; import com.sap.gtt.v2.sample.sof.rest.controller.domain.fulfillmentprocessflow.Lane; import com.sap.gtt.v2.sample.sof.service.client.GTTCoreServiceClient; import org.apache.olingo.odata2.api.uri.expression.BinaryOperator; import org.apache.olingo.odata2.api.uri.expression.FilterExpression; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.util.UriComponentsBuilder; import java.math.BigDecimal; import java.util.*; import java.util.stream.Collectors; import static com.sap.gtt.v2.sample.sof.constant.Constants.PROCESS_EVENT_DIRECTORY_ENTITY_NAME; import static com.sap.gtt.v2.sample.sof.constant.Constants.URL_SPLITTER; import static com.sap.gtt.v2.sample.sof.service.client.GTTCoreServiceClient.EXPAND; import static com.sap.gtt.v2.sample.sof.service.client.GTTCoreServiceClient.FILTER; import static java.lang.String.format; @Service public class FulfillmentProcessFlowService { private static final String REJECTION_STATUS_COMPLETE_REJECT_CODE = "C"; private static final String PROCESS = "process"; @Autowired private GTTCoreServiceClient gttCoreServiceClient; public FulfillmentProcessFlow generateFulfillmentProcessFlow(UUID salesOrderItemId) { SalesOrderItem salesOrderItem = querySalesOrderItem(salesOrderItemId); List<Lane> lanes = initLanes(salesOrderItem); updateLanes(lanes, salesOrderItem); FulfillmentProcessFlow flow = new FulfillmentProcessFlow(); flow.setLanes(lanes); return flow; } private SalesOrderItem querySalesOrderItem(UUID salesOrderItemId) { String query = UriComponentsBuilder.fromUriString(format("/SalesOrderItem(guid'%s')", salesOrderItemId)) .queryParam(EXPAND, "scheduleLines,deliveryItems") .build().encode().toUriString(); return gttCoreServiceClient.readEntity(query, SalesOrderItem.class); } private List<Lane> initLanes(SalesOrderItem salesOrderItem) { List<Lane> lanes = new ArrayList<>(); String rejectionStatusCode = salesOrderItem.getRejectionStatusCode(); List<DeliveryItem> deliveryItems = salesOrderItem.getDeliveryItems(); if (REJECTION_STATUS_COMPLETE_REJECT_CODE.equals(rejectionStatusCode) && deliveryItems.isEmpty()) { EnumSet.allOf(FulfillmentProcessMilestoneEnum.class).stream() .filter(m -> m.getName().equals(FulfillmentProcessMilestoneEnum.SALES_ORDER_ITEM_CREATED.getName()) || m.getName().equals(FulfillmentProcessMilestoneEnum.SALES_ORDER_ITEM_REJECTED.getName())) .forEach(m -> { Lane lane = new Lane(); lane.setId(String.valueOf(m.getPosition())); lane.setName(m.getName()); lane.setPosition(m.getPosition()); lanes.add(lane); }); } else { EnumSet.allOf(FulfillmentProcessMilestoneEnum.class).stream() .filter(m -> !m.getName().equals(FulfillmentProcessMilestoneEnum.SALES_ORDER_ITEM_REJECTED.getName())) .forEach(milestone -> { Lane lane = new Lane(); lane.setId(String.valueOf(milestone.getPosition())); lane.setName(milestone.getName()); lane.setPosition(milestone.getPosition()); lanes.add(lane); }); } return lanes; } private void updateLanes(List<Lane> lanes, SalesOrderItem salesOrderItem) { lanes.forEach(lane -> updateLane(lane, salesOrderItem)); } private void updateLane(Lane lane, SalesOrderItem salesOrderItem) { String name = lane.getName(); FulfillmentProcessMilestoneEnum milestone = EnumSet.allOf(FulfillmentProcessMilestoneEnum.class).stream() .filter(m -> m.getName().equals(name)) .findFirst().orElseThrow(() -> new IllegalStateException(String.format("Unsupported milestone %s.", name))); switch (milestone) { case SALES_ORDER_ITEM_CREATED: updateMilestoneOfSalesOrderItemCreated(lane, salesOrderItem); break; case SALES_ORDER_ITEM_CONFIRMED: updateMilestoneOfSalesOrderItemConfirmed(lane, salesOrderItem); break; case DELIVERY_CREATED: updateMilestoneOfDeliveryCreated(lane, salesOrderItem); break; case DELIVERY_GOODS_ISSUED: updateMilestoneOfDeliveryGoodsIssued(lane, salesOrderItem); break; case DELIVERY_COMPLETED: updateMilestoneOfDeliveryCompleted(lane, salesOrderItem); break; case SALES_ORDER_ITEM_REJECTED: updateMilestoneOfSalesOrderItemRejected(lane, salesOrderItem); break; default: } } private void updateMilestoneOfSalesOrderItemCreated(Lane lane, SalesOrderItem salesOrderItem) { BigDecimal orderQuantity = Optional.ofNullable(salesOrderItem.getOrderQuantity()).orElse(BigDecimal.ZERO); lane.setCount(orderQuantity); lane.setTotal(orderQuantity); } private void updateMilestoneOfSalesOrderItemConfirmed(Lane lane, SalesOrderItem salesOrderItem) { String rejectionStatusCode = salesOrderItem.getRejectionStatusCode(); BigDecimal saleOrderItemOrderQuantity = Optional.ofNullable(salesOrderItem.getOrderQuantity()).orElse(BigDecimal.ZERO); List<DeliveryItem> deliveryItems = salesOrderItem.getDeliveryItems(); BigDecimal count = REJECTION_STATUS_COMPLETE_REJECT_CODE.equals(rejectionStatusCode) && !deliveryItems.isEmpty() ? deliveryItems.stream() .map(deliveryItem -> Optional.ofNullable(deliveryItem.getOrderQuantity()).orElse(BigDecimal.ZERO)) .reduce(BigDecimal.ZERO, BigDecimal::add) : salesOrderItem.getScheduleLines().stream() .map(scheduleLine -> Optional.ofNullable(scheduleLine.getConfirmedQuantity()).orElse(BigDecimal.ZERO)) .reduce(BigDecimal.ZERO, BigDecimal::add); if (REJECTION_STATUS_COMPLETE_REJECT_CODE.equals(rejectionStatusCode)) { lane.setRejectCount(saleOrderItemOrderQuantity.subtract(count)); } lane.setCount(count); lane.setTotal(saleOrderItemOrderQuantity); } private void updateMilestoneOfDeliveryCreated(Lane lane, SalesOrderItem salesOrderItem) { String rejectionStatusCode = salesOrderItem.getRejectionStatusCode(); List<DeliveryItem> deliveryItems = salesOrderItem.getDeliveryItems(); BigDecimal count = deliveryItems.stream() .map(deliveryItem -> Optional.ofNullable(deliveryItem.getOrderQuantity()).orElse(BigDecimal.ZERO)) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal orderQuantity = REJECTION_STATUS_COMPLETE_REJECT_CODE.equals(rejectionStatusCode) && !deliveryItems.isEmpty() ? count : Optional.ofNullable(salesOrderItem.getOrderQuantity()).orElse(BigDecimal.ZERO); lane.setCount(count); lane.setTotal(orderQuantity); } private void updateMilestoneOfDeliveryGoodsIssued(Lane lane, SalesOrderItem salesOrderItem) { String rejectionStatusCode = salesOrderItem.getRejectionStatusCode(); List<DeliveryItem> deliveryItems = salesOrderItem.getDeliveryItems(); BigDecimal orderQuantity = REJECTION_STATUS_COMPLETE_REJECT_CODE.equals(rejectionStatusCode) && !deliveryItems.isEmpty() ? deliveryItems.stream() .map(deliveryItem -> Optional.ofNullable(deliveryItem.getOrderQuantity()).orElse(BigDecimal.ZERO)) .reduce(BigDecimal.ZERO, BigDecimal::add) : Optional.ofNullable(salesOrderItem.getOrderQuantity()).orElse(BigDecimal.ZERO); if (deliveryItems.isEmpty()) { lane.setCount(BigDecimal.ZERO); } else { Set<String> deliveryItemTrackingIds = deliveryItems.stream().map(DeliveryItem::getTrackingId).collect(Collectors.toSet()); List<FilterExpression> expressions = new ArrayList<>(); deliveryItemTrackingIds.forEach(trackingId -> { List<FilterCondition> conditions = new ArrayList<>(); conditions.add(new FilterCondition("process/trackingId", FilterCondition.EDM_TYPE_STRING, trackingId, BinaryOperator.EQ)); conditions.add(new FilterCondition("event/eventType", FilterCondition.EDM_TYPE_STRING, Constants.GTT_MODEL_NAMESPACE + ".Delivery.GoodsIssued", BinaryOperator.EQ)); expressions.add(FilterExpressionBuilder.createFilterExpression(conditions, BinaryOperator.AND)); }); FilterExpression filter = expressions.get(0); for (int index = 1; index < expressions.size(); index++) { filter = FilterExpressionBuilder.createFilterExpression(filter, expressions.get(index), BinaryOperator.OR); } String query = UriComponentsBuilder.fromUriString(URL_SPLITTER + PROCESS_EVENT_DIRECTORY_ENTITY_NAME) .queryParam(EXPAND, PROCESS) .queryParam(FILTER, filter.getExpressionString()) .build().encode().toUriString(); List<ProcessEventDirectory> processEventDirectories = gttCoreServiceClient.readEntitySetAll(query, ProcessEventDirectory.class).getResults(); Set<String> reportedTrackingIds = processEventDirectories.stream() .map(ProcessEventDirectory::getProcess) .map(TrackedProcess::getTrackingId) .collect(Collectors.toSet()); BigDecimal count = deliveryItems.stream() .filter(deliveryItem -> reportedTrackingIds.contains(deliveryItem.getTrackingId())) .map(deliveryItem -> Optional.ofNullable(deliveryItem.getOrderQuantity()).orElse(BigDecimal.ZERO)) .reduce(BigDecimal.ZERO, BigDecimal::add); lane.setCount(count); } lane.setTotal(orderQuantity); } private void updateMilestoneOfDeliveryCompleted(Lane lane, SalesOrderItem salesOrderItem) { String rejectionStatusCode = salesOrderItem.getRejectionStatusCode(); List<DeliveryItem> deliveryItems = salesOrderItem.getDeliveryItems(); List<DeliveryItem> completedDeliveryItems = deliveryItems.stream() .filter(deliveryItem -> Constants.EXECUTION_STATUS_COMPLETED.equals(deliveryItem.getExecutionStatusCode())) .collect(Collectors.toList()); BigDecimal count = completedDeliveryItems.stream() .map(deliveryItem -> Optional.ofNullable(deliveryItem.getOrderQuantity()).orElse(BigDecimal.ZERO)) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal orderQuantity = REJECTION_STATUS_COMPLETE_REJECT_CODE.equals(rejectionStatusCode) && !deliveryItems.isEmpty() ? deliveryItems.stream() .map(deliveryItem -> Optional.ofNullable(deliveryItem.getOrderQuantity()).orElse(BigDecimal.ZERO)) .reduce(BigDecimal.ZERO, BigDecimal::add) : Optional.ofNullable(salesOrderItem.getOrderQuantity()).orElse(BigDecimal.ZERO); lane.setCount(count); lane.setTotal(orderQuantity); } private void updateMilestoneOfSalesOrderItemRejected(Lane lane, SalesOrderItem salesOrderItem) { BigDecimal saleOrderItemOrderQuantity = Optional.ofNullable(salesOrderItem.getOrderQuantity()).orElse(BigDecimal.ZERO); lane.setCount(saleOrderItemOrderQuantity); lane.setTotal(saleOrderItemOrderQuantity); } }
/** * Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. */ package com.skyeye.eve.service; import com.skyeye.common.object.InputObject; import com.skyeye.common.object.OutputObject; public interface DsFormContentService { public void queryDsFormContentList(InputObject inputObject, OutputObject outputObject) throws Exception; public void insertDsFormContentMation(InputObject inputObject, OutputObject outputObject) throws Exception; public void deleteDsFormContentMationById(InputObject inputObject, OutputObject outputObject) throws Exception; public void queryDsFormContentMationToEditById(InputObject inputObject, OutputObject outputObject) throws Exception; public void editDsFormContentMationById(InputObject inputObject, OutputObject outputObject) throws Exception; public void queryDsFormContentMationToShow(InputObject inputObject, OutputObject outputObject) throws Exception; public void queryDsFormContentDetailedMationToShow(InputObject inputObject, OutputObject outputObject) throws Exception; }
/** * */ package capsule; import deva.Bitki; import generic.Agac; /** * @author MEHMET AKIF ILYASOGULLARI * */ public class Capsule_Agac_Bitki { private Agac<Bitki> agac_bitki; /** * @param agac_bitki */ public Capsule_Agac_Bitki(Agac<Bitki> agac_bitki) { super(); this.setAgac_bitki(agac_bitki); } /** * */ public Capsule_Agac_Bitki() { this.setAgac_bitki(new Agac<Bitki>()); } public Agac<Bitki> getAgac_bitki() { return agac_bitki; } public void setAgac_bitki(Agac<Bitki> agac_bitki) { this.agac_bitki = agac_bitki; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Capsule_Agac_Bitki [agac_bitki="); builder.append(getAgac_bitki()); builder.append("]"); return builder.toString(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.file; import org.apache.camel.ContextTestSupport; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.junit.Before; import org.junit.Test; /** * Unit test for consuming the single directory only. */ public class FileConsumeSingleDirectoryOnlyTest extends ContextTestSupport { @Override @Before public void setUp() throws Exception { deleteDirectory("target/data/singledirectoryonly"); super.setUp(); } @Test public void testConsumeFileOnly() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceivedInAnyOrder("Hello World", "Bye World"); template.sendBodyAndHeader("file://target/data/singledirectoryonly/2008", "2008 Report", Exchange.FILE_NAME, "report2008.txt"); template.sendBodyAndHeader("file://target/data/singledirectoryonly", "Hello World", Exchange.FILE_NAME, "report.txt"); template.sendBodyAndHeader("file://target/data/singledirectoryonly", "Bye World", Exchange.FILE_NAME, "report2.txt"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { from("file://target/data/singledirectoryonly/?recursive=false&delete=true&initialDelay=0&delay=10") .convertBodyTo(String.class).to("mock:result"); } }; } }
package quanta.service; import static quanta.util.Util.no; import static quanta.util.Util.ok; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.mongodb.core.BulkOperations; import org.springframework.data.mongodb.core.BulkOperations.BulkMode; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Component; import com.mongodb.bulk.BulkWriteResult; import quanta.actpub.APConst; import quanta.config.ServiceBase; import quanta.exception.NodeAuthFailedException; import quanta.exception.base.RuntimeEx; import quanta.model.client.NodeProp; import quanta.model.client.PrincipalName; import quanta.mongo.MongoSession; import quanta.mongo.model.AccessControl; import quanta.mongo.model.MongoPrincipal; import quanta.mongo.model.SubNode; import quanta.request.AddPrivilegeRequest; import quanta.request.CopySharingRequest; import quanta.request.GetNodePrivilegesRequest; import quanta.request.RemovePrivilegeRequest; import quanta.request.SetCipherKeyRequest; import quanta.request.SetUnpublishedRequest; import quanta.response.AddPrivilegeResponse; import quanta.response.CopySharingResponse; import quanta.response.GetNodePrivilegesResponse; import quanta.response.RemovePrivilegeResponse; import quanta.response.SetCipherKeyResponse; import quanta.response.SetUnpublishedResponse; import quanta.util.ExUtil; import quanta.util.XString; /** * Service methods for (ACL): processing security, privileges, and Access Control List information * on nodes. */ @Component public class AclService extends ServiceBase { private static final Logger log = LoggerFactory.getLogger(AclService.class); /** * Returns the privileges that exist on the node identified in the request. */ public GetNodePrivilegesResponse getNodePrivileges(MongoSession ms, GetNodePrivilegesRequest req) { GetNodePrivilegesResponse res = new GetNodePrivilegesResponse(); String nodeId = req.getNodeId(); SubNode node = read.getNode(ms, nodeId); res.setUnpublished(node.getBool(NodeProp.UNPUBLISHED)); if (!req.isIncludeAcl() && !req.isIncludeOwners()) { throw ExUtil.wrapEx("no specific information requested for getNodePrivileges"); } if (req.isIncludeAcl()) { res.setAclEntries(auth.getAclEntries(ms, node)); } if (req.isIncludeOwners()) { List<String> owners = user.getOwnerNames(node); // log.info("Owner Count: " + owners.size()); res.setOwners(owners); } res.setSuccess(true); return res; } public CopySharingResponse copySharing(MongoSession ms, CopySharingRequest req) { CopySharingResponse res = new CopySharingResponse(); SubNode node = read.getNode(ms, req.getNodeId()); BulkOperations bops = null; /* * todo-1: It seems like maybe batching can't update a collection property? so for now I'm * disabling, and yes disabling batch mode makes this code work. */ boolean batchMode = false; Boolean unpublished = node.getBool(NodeProp.UNPUBLISHED); for (SubNode n : read.getSubGraph(ms, node, null, 0, true, false)) { if (batchMode) { // lazy instantiate if (no(bops)) { bops = ops.bulkOps(BulkMode.UNORDERED, SubNode.class); } try { auth.ownerAuth(ms, n); n.set(NodeProp.UNPUBLISHED, unpublished ? unpublished : null); Query query = new Query().addCriteria(new Criteria("id").is(n.getId())); // log.debug("Setting [" + n.getIdStr() + "] AC to " + XString.prettyPrint(node.getAc())); Update update = new Update().set(SubNode.AC, node.getAc()).set(SubNode.PROPS, n.getProps()); bops.updateOne(query, update); } catch (Exception e) { // not an error, we just can't properties on nodes we don't own, so we skip them } } else { auth.ownerAuth(ms, n); n.set(NodeProp.UNPUBLISHED, unpublished ? unpublished : null); n.setAc(node.getAc()); } } if (batchMode && ok(bops)) { BulkWriteResult results = bops.execute(); log.debug("Bulk Privileges: updated " + results.getModifiedCount() + " nodes."); } else { update.saveSession(ms); } res.setSuccess(true); return res; } /* * Adds or updates a new privilege to a node */ public AddPrivilegeResponse addPrivilege(MongoSession ms, AddPrivilegeRequest req) { AddPrivilegeResponse res = new AddPrivilegeResponse(); String nodeId = req.getNodeId(); req.setPrincipal(XString.stripIfStartsWith(req.getPrincipal(), "@")); SubNode node = read.getNode(ms, nodeId); auth.ownerAuth(ms, node); boolean success = addPrivilege(ms, null, node, req.getPrincipal(), req.getPrivileges(), res); res.setSuccess(success); return res; } /* * Adds or updates a new privilege to a node */ public SetUnpublishedResponse setUnpublished(MongoSession ms, SetUnpublishedRequest req) { SetUnpublishedResponse res = new SetUnpublishedResponse(); String nodeId = req.getNodeId(); SubNode node = read.getNode(ms, nodeId); auth.ownerAuth(ms, node); node.set(NodeProp.UNPUBLISHED, req.isUnpublished() ? true : null); res.setSuccess(true); return res; } /* * Adds or updates a new encryption key to a node */ public SetCipherKeyResponse setCipherKey(MongoSession ms, SetCipherKeyRequest req) { SetCipherKeyResponse res = new SetCipherKeyResponse(); String nodeId = req.getNodeId(); SubNode node = read.getNode(ms, nodeId); auth.ownerAuth(ms, node); String cipherKey = node.getStr(NodeProp.ENC_KEY); if (no(cipherKey)) { throw new RuntimeEx("Attempted to alter keys on a non-encrypted node."); } boolean success = setCipherKey(ms, node, req.getPrincipalNodeId(), req.getCipherKey(), res); res.setSuccess(success); return res; } public boolean setCipherKey(MongoSession ms, SubNode node, String principalNodeId, String cipherKey, SetCipherKeyResponse res) { boolean ret = false; HashMap<String, AccessControl> acl = node.getAc(); AccessControl ac = acl.get(principalNodeId); if (ok(ac)) { ac.setKey(cipherKey); node.setAc(acl); update.save(ms, node); ret = true; } return ret; } /** * Adds the privileges to the node sharing this node to principal, which will be either a userName * or 'public' (when the node is being shared to public) * * If BulkOperations is non-null we use it instead of a non-bulk operation */ public boolean addPrivilege(MongoSession ms, BulkOperations bops, SubNode node, String principal, List<String> privileges, AddPrivilegeResponse res) { if (no(principal) || no(node)) return false; principal = principal.trim(); String cipherKey = node.getStr(NodeProp.ENC_KEY); String mapKey = null; SubNode principalNode = null; boolean isPublic = false; /* If we are sharing to public, then that's the map key */ if (principal.equalsIgnoreCase(PrincipalName.PUBLIC.s())) { if (ok(cipherKey)) { throw new RuntimeEx("Cannot make an encrypted node public."); } mapKey = PrincipalName.PUBLIC.s(); isPublic = true; } /* * otherwise we're sharing to a person so we now get their userNodeId to use as map key */ else { principalNode = read.getUserNodeByUserName(auth.getAdminSession(), principal); if (no(principalNode)) { if (ok(res)) { res.setMessage("Unknown user name: " + principal); res.setSuccess(false); } return false; } mapKey = principalNode.getIdStr(); /* * If this node is encrypted we get the public key of the user being shared with to send back to the * client, which will then use it to encrypt the symmetric key to the data, and then send back up to * the server to store in this sharing entry */ if (ok(cipherKey)) { String principalPubKey = principalNode.getStr(NodeProp.USER_PREF_PUBLIC_KEY); if (no(principalPubKey)) { if (ok(res)) { res.setMessage("User doesn't have a PublicKey available: " + principal); res.setSuccess(false); return false; } } log.debug("principalPublicKey: " + principalPubKey); if (ok(res)) { res.setPrincipalPublicKey(principalPubKey); res.setPrincipalNodeId(mapKey); } } } HashMap<String, AccessControl> acl = node.getAc(); /* initialize acl to a map if it's null, or if we're sharing to public */ if (no(acl)) { acl = new HashMap<>(); } /* * Get access control entry from map, but if one is not found, we can just create one. */ AccessControl ac = acl.get(mapKey); if (no(ac)) { ac = new AccessControl(); } String prvs = ac.getPrvs(); /* * to set from 'rd' to 'rd,rw' back and forth then it's better to set prvs to an empty string here * any time we detect this is 'public' priv being set. */ if (no(prvs) || isPublic) { prvs = ""; } boolean authAdded = false; /* Scan all the privileges to be added to this principal (rd, rw, etc) */ for (String priv : privileges) { /* If this privilege is not already on ac.prvs string then append it */ if (prvs.indexOf(priv) == -1) { authAdded = true; if (prvs.length() > 0) { prvs += ","; } prvs += priv; } } if (authAdded) { ac.setPrvs(prvs); acl.put(mapKey, ac); // if bulk operation if (ok(bops)) { /* * todo-1: this needs testing because the other place I'm doing similar code elsewhere refuses to * work somehow. Seems like updating collections might not work in batching. Currently there are no * places we call this method with bops passed in, so this bops branch is not currently being used * for that reason. */ Query query = new Query().addCriteria(new Criteria("id").is(node.getId())); Update update = new Update().set(SubNode.AC, acl); bops.updateOne(query, update); } // else non-bulk else { node.setAc(acl); update.save(ms, node); } // if (!principal.equalsIgnoreCase(PrincipalName.PUBLIC.s())) { // SubNode fromUserNode = read.getNode(session, node.getOwner()); // String fromUserName = fromUserNode.getStrProp(NodeProp.USER); // SubNode toOwnerNode = read.getUserNodeByUserName(auth.getAdminSession(), principal); // /* // * todo-2: Although I am disabling these for now both of these lines of code do work perfectly: we // * can send an email notification here about node edits (first line), and the line below that // works // * fine and adds a node to the user's inbox that links to this newly shared node. // * // * I just want to think more about when exactly to trigger these notifictions. For example I may // * make these two buttons on the editor users must click called "Email Notification to Shares", // and // * "Send to Inboxes of Shares" // */ // // outboxMgr.sendEmailNotification(auth.getAdminSession(), fromUserName, toOwnerNode, node); // // outboxMgr.addInboxNotification(principal, toOwnerNode, node, "New node shared to you."); // } } return true; } public void removeAclEntry(MongoSession ms, SubNode node, String principalNodeId, String privToRemove) { /* special syntax is we remove all if asterisk specified */ if (principalNodeId.equals("*")) { node.setAc(null); update.save(ms, node); return; } HashMap<String, AccessControl> acl = node.getAc(); if (no(acl)) return; String newPrivs = ""; boolean removed = false; AccessControl ac = null; // if removing all privileges if ("*".equals(privToRemove)) { removed = true; } // else removing just some specific privileges else { ac = acl.get(principalNodeId); if (no(ac)) { log.debug("ac not found for " + principalNodeId + "\nACL DUMP: " + XString.prettyPrint(acl)); return; } String privs = ac.getPrvs(); if (no(privs)) { log.debug("privs not found for " + principalNodeId + "\nACL DUMP: " + XString.prettyPrint(acl)); return; } HashSet<String> setToRemove = XString.tokenizeToSet(privToRemove, ",", true); StringTokenizer t = new StringTokenizer(privs, ",", false); /* * build the new comma-delimited privs list by adding all that aren't in the setToRemove */ while (t.hasMoreTokens()) { String tok = t.nextToken().trim(); if (setToRemove.contains(tok)) { removed = true; continue; } if (newPrivs.length() > 0) { newPrivs += ","; } newPrivs += tok; } } if (removed) { /* * If there are no privileges left for this principal, then remove the principal entry completely * from the ACL. We don't store empty ones. */ if (newPrivs.equals("")) { acl.remove(principalNodeId); } else { ac.setPrvs(newPrivs); acl.put(principalNodeId, ac); } /* * if there are now no acls at all left set the ACL to null, so it is completely removed from the * node */ if (acl.isEmpty()) { node.setAc(null); } else { node.setAc(acl); } update.save(ms, node); } } /* * Removes the privilege specified in the request from the node specified in the request */ public RemovePrivilegeResponse removePrivilege(MongoSession ms, RemovePrivilegeRequest req) { RemovePrivilegeResponse res = new RemovePrivilegeResponse(); String nodeId = req.getNodeId(); SubNode node = read.getNode(ms, nodeId); auth.ownerAuth(ms, node); removeAclEntry(ms, node, req.getPrincipalNodeId(), req.getPrivilege()); res.setSuccess(true); return res; } public List<String> getOwnerNames(MongoSession ms, SubNode node) { Set<String> ownerSet = new HashSet<>(); /* * We walk up the tree util we get to the root, or find ownership on node, or any of it's parents */ int sanityCheck = 0; while (++sanityCheck < 100) { List<MongoPrincipal> principals = getNodePrincipals(ms, node); for (MongoPrincipal p : principals) { /* * todo-3: this is a spot that can be optimized. We should be able to send just the userNodeId back * to client, and the client should be able to deal with that (i think). depends on how much * ownership info we need to show user. ownerSet.add(p.getUserNodeId()); */ SubNode userNode = read.getNode(ms, p.getUserNodeId()); String userName = userNode.getStr(NodeProp.USER); ownerSet.add(userName); } if (principals.size() == 0) { node = read.getParent(ms, node); if (no(node)) break; } else { break; } } List<String> ownerList = new LinkedList<>(ownerSet); Collections.sort(ownerList); return ownerList; } public static List<MongoPrincipal> getNodePrincipals(MongoSession ms, SubNode node) { List<MongoPrincipal> principals = new LinkedList<>(); MongoPrincipal principal = new MongoPrincipal(); principal.setUserNodeId(node.getId()); principal.setAccessLevel("w"); principals.add(principal); return principals; } public static boolean isPublic(MongoSession ms, SubNode node) { return ok(node) && ok(node.getAc()) && node.getAc().containsKey(PrincipalName.PUBLIC.s()); } public void makePublicAppendable(MongoSession ms, SubNode node) { setKeylessPriv(ms, node, PrincipalName.PUBLIC.s(), APConst.RDWR); } // The effeciency of using this function is it won't set the node to dirty of nothing changed. public void setKeylessPriv(MongoSession ms, SubNode node, String key, String prvs) { // if no privileges exist at all just add the one we need to add if (no(node.getAc())) { node.putAc(key, new AccessControl(null, prvs)); } // otherwise first check to see if it's already added else { AccessControl ac = node.getAc().get(key); if (ok(ac) && ac.getPrvs().equals(prvs)) { // already had the correct ac, nothing to do here } // else need to add it. else { node.putAc(key, new AccessControl(null, prvs)); } } } public void failIfAdminOwned(SubNode node) { if (isAdminOwned(node)) { throw new NodeAuthFailedException(); } } public boolean isAdminOwned(SubNode node) { return node.getOwner().equals(auth.getAdminSession().getUserNodeId()); } }
package seedu.address.testutil; import static seedu.address.logic.commands.CommandTestUtil.VALID_NOTE_NAME_CS2103; import static seedu.address.logic.commands.CommandTestUtil.VALID_NOTE_TIME; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_URGENT; import seedu.address.model.item.Note; /** * A utility class containing a list of {@code Note} objects to be used in tests. */ public class TypicalNote { public static final Note FINISH_HOMEWORK = new NoteBuilder() .withName("Finish Homework") .withTime("03-2020") .withTags("noturgent") .build(); public static final Note FINISH_CS_2103 = new NoteBuilder() .withName(VALID_NOTE_NAME_CS2103) .withTime(VALID_NOTE_TIME) .withTags(VALID_TAG_URGENT) .build(); public static final Note FINISH_RESUME_2 = new NoteBuilder() .withName("Finish Resume 2") .withTime("04-2020") .withTags() .build(); }
/* * $Id: XINSCallRequestTests.java,v 1.14 2010/10/25 20:36:51 agoubard Exp $ * * See the COPYRIGHT file for redistribution and use restrictions. */ package org.xins.tests.client; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.log4j.NDC; import org.xins.client.XINSCallRequest; import org.xins.common.http.HTTPMethod; /** * Tests for class <code>XINSCallRequest</code>. * * @version $Revision: 1.14 $ $Date: 2010/10/25 20:36:51 $ * @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a> */ public class XINSCallRequestTests extends TestCase { /** * Constructs a new <code>XINSCallRequestTests</code> test suite with * the specified name. The name will be passed to the superconstructor. * * @param name * the name for this test suite. */ public XINSCallRequestTests(String name) { super(name); } /** * Returns a test suite with all test cases defined by this class. * * @return * the test suite, never <code>null</code>. */ public static Test suite() { return new TestSuite(XINSCallRequestTests.class); } /** * Tests the behaviour of the <code>XINSCallRequestTests</code> * class. * * @throws Exception * if an unexpected exception is thrown. */ public void testXINSCallRequest() throws Exception { // Test first constructor try { new XINSCallRequest(null, null); fail("XINSCallRequest(null, null) should throw an IllegalArgumentException."); } catch (IllegalArgumentException e) { // as expected } try { new XINSCallRequest(null, new HashMap<String, String>()); fail("XINSCallRequest(null, new HashMap<String, String>()) should throw an IllegalArgumentException."); } catch (IllegalArgumentException e) { // as expected } final int constructorCount = 3; XINSCallRequest[] r = new XINSCallRequest[constructorCount]; String functionName = "SomeFunction"; r[0] = new XINSCallRequest(functionName, null); r[1] = new XINSCallRequest(functionName, null, false); r[2] = new XINSCallRequest(functionName, null, false, null); for (int i = 0; i < constructorCount; i++) { assertEquals(functionName, r[i].getFunctionName()); if (r[i].describe().indexOf(functionName) < 0) { fail("XINSCallRequest.describe() should return a string that contains the function name. Function name is: \"" + functionName + "\". Description is: \"" + r[i].describe() + "\"."); } } String contextID = "f54b715f249bd02c"; NDC.push("f54b715f249bd02c"); Map<String, String> p = new HashMap<String, String>(); p.put("channel", "USR_REG_WEB_W"); p.put("lineType", "PSTN"); p.put("postCode", "1011PZ"); p.put("houseNumber", "1"); XINSCallRequest req = new XINSCallRequest("GetUpgradePlanList", p, false, HTTPMethod.POST); NDC.pop(); NDC.remove(); if (req.describe().indexOf(contextID) < 0) { fail("XINSCallRequest.describe() should return a string that contains the diagnostic context ID. Context ID is: \"" + contextID + "\". Description is: \"" + req.describe() + "\"."); } } }
package ru.nivanov; import ru.nivanov.model.UserStore; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * Created by Nikolay Ivanov on 24.10.2017. */ public class DeleteServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); String id = req.getParameter("id"); UserStore.getBase().deleteUser(id); resp.sendRedirect(String.format("%s/", req.getContextPath())); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); if (!session.getAttribute("rolename").equals("admin")) { resp.sendRedirect(String.format("%s/", req.getContextPath())); } else { req.getRequestDispatcher("/WEB-INF/views/delete.jsp").forward(req, resp); } } }
/* * Copyright 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.gradle.jvm.tasks.api; import com.google.common.collect.Lists; import org.gradle.api.Incubating; import org.gradle.api.file.FileTree; import org.gradle.api.internal.tasks.compile.ApiClassExtractor; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.PathSensitive; import org.gradle.api.tasks.PathSensitivity; import org.gradle.api.tasks.SourceTask; import org.gradle.api.tasks.TaskAction; import org.gradle.internal.ErroringAction; import org.objectweb.asm.ClassReader; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import static org.apache.commons.io.FileUtils.readFileToByteArray; import static org.gradle.internal.FileUtils.hasExtension; import static org.gradle.internal.IoActions.withResource; /** * Assembles an "API Jar" containing only the members of a library's public API. * * <p>This task and the Jar it produces are designed primarily for internal use in support * of Gradle's "compile avoidance" performance feature. The task is automatically included * in the task graph for any JVM library that declares an {@code api { ... }} * specification, and the resulting Jar will automatically be placed on the compile time * classpath of projects that depend on the library in lieu of the library's complete * so-called "Runtime Jar".</p> * * <p>Swapping the API Jar in for the Runtime Jar at compile time is what makes * "compile avoidance" possible: because the contents of the API Jar change only when * actual API changes are made, the API Jar passes Gradle's up-to-date checks, even if the * implementation in the Runtime Jar has changed. Ultimately, this means that projects * depending on the library in question will need to recompile potentially far less often. * </p> * * <p>In order to ensure that API Jars change as infrequently as possible, this task and * its supporting classes ensure that only actual public API members are included in the * API Jar, and that the methods among those members are stripped of their implementation. * Because the members included in API Jars exist only for compilation purposes, they need * no actual implementation, and for this reason, all such methods throw * {@link UnsupportedOperationException} in the unlikely event that they are present on * the classpath and invoked at runtime.</p> * * <p>The inputs to this task are Java class files which must be provided via * {@link org.gradle.api.tasks.TaskInputs}.</p> * * @since 2.10 * @see org.gradle.jvm.plugins.JvmComponentPlugin */ @Incubating @Deprecated public class ApiJar extends SourceTask { private Set<String> exportedPackages; private File outputFile; /** * {@inheritDoc} */ @Override @PathSensitive(PathSensitivity.RELATIVE) public FileTree getSource() { return super.getSource(); } @Input public Set<String> getExportedPackages() { return exportedPackages; } public void setExportedPackages(Set<String> exportedPackages) { this.exportedPackages = exportedPackages; } @OutputFile public File getOutputFile() { return outputFile; } public void setOutputFile(File outputFile) { this.outputFile = outputFile; } @TaskAction public void createApiJar() throws IOException { // Make sure all entries are always written in the same order final List<File> sourceFiles = sortedSourceFiles(); final ApiClassExtractor apiClassExtractor = new ApiClassExtractor(getExportedPackages()); withResource( new JarOutputStream(new BufferedOutputStream(new FileOutputStream(getOutputFile()), 65536)), new ErroringAction<JarOutputStream>() { @Override protected void doExecute(final JarOutputStream jos) throws Exception { writeManifest(jos); writeClasses(jos); } private void writeManifest(JarOutputStream jos) throws IOException { writeEntry(jos, "META-INF/MANIFEST.MF", "Manifest-Version: 1.0\n".getBytes()); } private void writeClasses(JarOutputStream jos) throws Exception { for (File sourceFile : sourceFiles) { if (!isClassFile(sourceFile)) { continue; } ClassReader classReader = new ClassReader(readFileToByteArray(sourceFile)); if (!apiClassExtractor.shouldExtractApiClassFrom(classReader)) { continue; } byte[] apiClassBytes = apiClassExtractor.extractApiClassFrom(classReader); if (apiClassBytes == null) { // Should be excluded continue; } String internalClassName = classReader.getClassName(); String entryPath = internalClassName + ".class"; writeEntry(jos, entryPath, apiClassBytes); } } private void writeEntry(JarOutputStream jos, String name, byte[] bytes) throws IOException { JarEntry je = new JarEntry(name); // Setting time to 0 because we need API jars to be identical independently of // the timestamps of class files je.setTime(0); je.setSize(bytes.length); jos.putNextEntry(je); jos.write(bytes); jos.closeEntry(); } } ); } private boolean isClassFile(File file) { return hasExtension(file, ".class"); } private List<File> sortedSourceFiles() { List<File> sourceFiles = Lists.newArrayList(getSource().getFiles()); Collections.sort(sourceFiles); return sourceFiles; } }
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.amplify.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * The request structure for the create webhook request. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/CreateWebhook" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateWebhookRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The unique ID for an Amplify app. * </p> */ private String appId; /** * <p> * The name for a branch that is part of an Amplify app. * </p> */ private String branchName; /** * <p> * The description for a webhook. * </p> */ private String description; /** * <p> * The unique ID for an Amplify app. * </p> * * @param appId * The unique ID for an Amplify app. */ public void setAppId(String appId) { this.appId = appId; } /** * <p> * The unique ID for an Amplify app. * </p> * * @return The unique ID for an Amplify app. */ public String getAppId() { return this.appId; } /** * <p> * The unique ID for an Amplify app. * </p> * * @param appId * The unique ID for an Amplify app. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateWebhookRequest withAppId(String appId) { setAppId(appId); return this; } /** * <p> * The name for a branch that is part of an Amplify app. * </p> * * @param branchName * The name for a branch that is part of an Amplify app. */ public void setBranchName(String branchName) { this.branchName = branchName; } /** * <p> * The name for a branch that is part of an Amplify app. * </p> * * @return The name for a branch that is part of an Amplify app. */ public String getBranchName() { return this.branchName; } /** * <p> * The name for a branch that is part of an Amplify app. * </p> * * @param branchName * The name for a branch that is part of an Amplify app. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateWebhookRequest withBranchName(String branchName) { setBranchName(branchName); return this; } /** * <p> * The description for a webhook. * </p> * * @param description * The description for a webhook. */ public void setDescription(String description) { this.description = description; } /** * <p> * The description for a webhook. * </p> * * @return The description for a webhook. */ public String getDescription() { return this.description; } /** * <p> * The description for a webhook. * </p> * * @param description * The description for a webhook. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateWebhookRequest withDescription(String description) { setDescription(description); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAppId() != null) sb.append("AppId: ").append(getAppId()).append(","); if (getBranchName() != null) sb.append("BranchName: ").append(getBranchName()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateWebhookRequest == false) return false; CreateWebhookRequest other = (CreateWebhookRequest) obj; if (other.getAppId() == null ^ this.getAppId() == null) return false; if (other.getAppId() != null && other.getAppId().equals(this.getAppId()) == false) return false; if (other.getBranchName() == null ^ this.getBranchName() == null) return false; if (other.getBranchName() != null && other.getBranchName().equals(this.getBranchName()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAppId() == null) ? 0 : getAppId().hashCode()); hashCode = prime * hashCode + ((getBranchName() == null) ? 0 : getBranchName().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); return hashCode; } @Override public CreateWebhookRequest clone() { return (CreateWebhookRequest) super.clone(); } }
/* * 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.vcs.model.v20200515; import com.aliyuncs.AcsResponse; import com.aliyuncs.vcs.transform.v20200515.UnbindCorpGroupResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class UnbindCorpGroupResponse extends AcsResponse { private String requestId; private String message; private String code; private Boolean success; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public Boolean getSuccess() { return this.success; } public void setSuccess(Boolean success) { this.success = success; } @Override public UnbindCorpGroupResponse getInstance(UnmarshallerContext context) { return UnbindCorpGroupResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
package com.revature.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FrontController extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String URI = request.getRequestURI().replace("/T2-Demo/", ""); switch(URI) { case "findAll": RequestHelper.findAllAccounts(request, response); break; default: RequestHelper.processError(request, response); break; } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String URI = request.getRequestURI().replace("/T2-Demo/", ""); switch(URI) { case "insertAccount": RequestHelper.insertAccount(request, response); break; default: RequestHelper.processError(request, response); break; } } protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String URI = request.getRequestURI().replace("/T2-Demo/", ""); switch(URI) { case "deleteAccount": RequestHelper.deleteAccount(request, response); break; default: RequestHelper.processError(request, response); break; } } protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String URI = request.getRequestURI().replace("/T2-Demo/", ""); switch(URI) { case "updateAccount": RequestHelper.updateAccount(request, response); break; case "updateAutoCommit": RequestHelper.updateAutoCommit(request,response); default: RequestHelper.processError(request, response); break; } } }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.jetbrains.protocolReader; import com.google.gson.stream.JsonReaderEx; import org.chromium.protocolReader.JsonParseMethod; import org.chromium.protocolReader.JsonParserRoot; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.*; class ParserRootImpl<R> { private final Class<R> rootClass; private final InvocationHandler invocationHandler; ParserRootImpl(Class<R> rootClass, LinkedHashMap<Class<?>, TypeHandler<?>> typeToTypeHandler) { this.rootClass = rootClass; ParseInterfaceSession session = new ParseInterfaceSession(typeToTypeHandler); session.run(rootClass); invocationHandler = new InvocationHandler(session.methodMap); } private static class ParseInterfaceSession { private final LinkedHashMap<Class<?>, TypeHandler<?>> typeToTypeHandler; private final Set<Class<?>> visitedInterfaces = new HashSet<Class<?>>(1); private final LinkedHashMap<Method, MethodDelegate> methodMap = new LinkedHashMap<Method, MethodDelegate>(); ParseInterfaceSession(LinkedHashMap<Class<?>, TypeHandler<?>> typeToTypeHandler) { this.typeToTypeHandler = typeToTypeHandler; } void run(Class<?> clazz) { parseInterfaceRecursive(clazz); } private void parseInterfaceRecursive(Class<?> clazz) throws JsonProtocolModelParseException { if (visitedInterfaces.contains(clazz)) { return; } visitedInterfaces.add(clazz); if (!clazz.isInterface()) { throw new JsonProtocolModelParseException( "Parser root type must be an interface: " + clazz); } JsonParserRoot jsonParserRoot = clazz.getAnnotation(JsonParserRoot.class); if (jsonParserRoot == null) { throw new JsonProtocolModelParseException( JsonParserRoot.class.getCanonicalName() + " annotation is expected in " + clazz); } for (Method m : clazz.getMethods()) { JsonParseMethod jsonParseMethod = m.getAnnotation(JsonParseMethod.class); if (jsonParseMethod == null) { throw new JsonProtocolModelParseException( JsonParseMethod.class.getCanonicalName() + " annotation is expected in " + clazz); } Class<?>[] exceptionTypes = m.getExceptionTypes(); if (exceptionTypes.length > 1) { throw new JsonProtocolModelParseException("Too many exception declared in " + m); } Type returnType = m.getGenericReturnType(); //noinspection SuspiciousMethodCalls TypeHandler<?> typeHandler = typeToTypeHandler.get(returnType); if (typeHandler == null) { typeHandler = InterfaceReader.createHandler(typeToTypeHandler, m.getReturnType()); if (typeHandler == null) { throw new JsonProtocolModelParseException("Unknown return type in " + m); } } Type[] arguments = m.getGenericParameterTypes(); if (arguments.length != 1) { throw new JsonProtocolModelParseException("Exactly one argument is expected in " + m); } Type argument = arguments[0]; MethodDelegate delegate; if (argument == JsonReaderEx.class) { delegate = new ParseDelegate(typeHandler); } else if (argument == Object.class) { delegate = new ParseDelegate(typeHandler); } else { throw new JsonProtocolModelParseException("Unrecognized argument type in " + m); } methodMap.put(m, delegate); } for (Type baseType : clazz.getGenericInterfaces()) { if (!(baseType instanceof Class)) { throw new JsonProtocolModelParseException("Base interface must be class in " + clazz); } Class<?> baseClass = (Class<?>) baseType; parseInterfaceRecursive(baseClass); } } } private static class InvocationHandler { private final Map<Method, MethodDelegate> map; InvocationHandler(Map<Method, MethodDelegate> map) { this.map = map; } public void writeStaticMethodJava(ClassScope scope) { TextOutput out = scope.getOutput(); for (Map.Entry<Method, MethodDelegate> en : map.entrySet()) { out.newLine(); en.getValue().writeStaticMethodJava(scope, en.getKey(), out); out.newLine(); } } } private static abstract class MethodDelegate { abstract void writeStaticMethodJava(ClassScope scope, Method key, TextOutput out); } private static class ParseDelegate extends MethodDelegate { private final TypeHandler<?> typeHandler; ParseDelegate(TypeHandler<?> typeHandler) { this.typeHandler = typeHandler; } @Override void writeStaticMethodJava(ClassScope scope, Method method, TextOutput out) { MethodHandler.writeMethodDeclarationJava(out, method, STATIC_METHOD_PARAM_NAME_LIST); out.openBlock(); out.append("return "); typeHandler.writeInstantiateCode(scope, out); out.append("(").append(STATIC_METHOD_PARAM_NAME).append(");"); out.closeBlock(); } private static final String STATIC_METHOD_PARAM_NAME = "reader"; private static final List<String> STATIC_METHOD_PARAM_NAME_LIST = Collections.singletonList(STATIC_METHOD_PARAM_NAME); } public Class<R> getType() { return rootClass; } public void writeStaticMethodJava(ClassScope rootClassScope) { invocationHandler.writeStaticMethodJava(rootClassScope); } }
package com.linkedpipes.plugin.loader.scp; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import com.linkedpipes.etl.executor.api.v1.LpException; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.Collection; /** * Used library: http://www.jcraft.com/jsch/examples/ SCP protocol: * https://blogs.oracle.com/janp/entry/how_the_scp_protocol_works */ class ScpClient implements AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(ScpClient.class); @FunctionalInterface interface ChanelConsumer { void accept(ChannelExec channel) throws Exception; } private final JSch jsch = new JSch(); private Session session = null; private String welcomeMessage = null; public void connect(String hostname, int port, String username, String password) throws Exception { session = jsch.getSession(username, hostname, port); session.setPassword(password); ignoreUnknownKey(); session.connect(); readWelcomeMessage(); } private void ignoreUnknownKey() { java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); } private void readWelcomeMessage() throws Exception { withChannelExec((channel) -> { channel.setCommand(":"); channel.connect(); InputStream inputStream = channel.getExtInputStream(); welcomeMessage = readResponse(inputStream); LOG.info("Welcome message: {}", welcomeMessage); }); } private static String readResponse(InputStream stream) throws IOException { if (stream == null) { return ""; } StringBuffer buffer = new StringBuffer(); while (true) { int value = stream.read(); if (value == 0 || value == -1) { break; } buffer.append((char) value); } return buffer.toString(); } private void withChannelExec(ChanelConsumer consumer) throws Exception { ChannelExec channel = null; try { channel = (ChannelExec) session.openChannel("exec"); consumer.accept(channel); } finally { if (channel != null) { channel.disconnect(); } } } public void createDirectory(String directory) throws Exception { String command = "[ -d " + directory + " ] || mkdir " + directory; LOG.info("createDirectory ..."); withChannelExec((channel) -> { channel.setCommand(command); executeChannel(channel); }); LOG.info("createDirectory ... done"); } private String stripWelcomeMessage(String response) { return response.substring(welcomeMessage.length()); } private void executeChannel(ChannelExec channel) throws Exception { channel.connect(); InputStream inputStream = channel.getExtInputStream(); String response = stripWelcomeMessage(readResponse(inputStream)); checkResponseStream(channel.getExitStatus(), response); } private void checkResponseStream(int code, String response) throws LpException { LOG.info("{} : {}", code, response); if (code == 0) { return; } else { throw new LpException( "Action failed, see log for more information."); } } public void clearDirectory(String directory) throws Exception { String command = "[ $(ls -A " + directory + " ) ] && rm -r " + directory + "/* || :"; LOG.info("clearDirectory ... : {}", command); withChannelExec((channel) -> { channel.setCommand(command); executeChannel(channel); }); LOG.info("clearDirectory ... done"); } public void uploadDirectories(String directory, Collection<File> directories) throws Exception { LOG.info("uploadDirectories ..."); String command = "scp -r -t -d " + directory; withChannelExec((channel) -> { try (OutputStream remoteOut = channel.getOutputStream(); InputStream remoteIn = channel.getInputStream()) { // channel.setCommand(command); channel.connect(); checkResponseStream(remoteIn); for (File file : directories) { sendDirectory(remoteOut, remoteIn, file); } } }); LOG.info("uploadDirectories ... done"); } private void sendDirectory(OutputStream remoteOut, InputStream remoteIn, File sourceDirectory) throws Exception { for (File file : sourceDirectory.listFiles()) { if (file.isDirectory()) { sendDirectory(remoteOut, remoteIn, file, file.getName()); } if (file.isFile()) { sendFile(remoteOut, remoteIn, file, file.getName()); } } } private void sendDirectory(OutputStream remoteOut, InputStream remoteIn, File sourceDirectory, String directoryName) throws IOException, LpException { LOG.debug("Sending directory: {} ... ", directoryName); // Send command. String command = "D0755 0 " + directoryName + "\n"; remoteOut.write(command.getBytes()); remoteOut.flush(); checkResponseStream(remoteIn); // Scan for files. for (final File file : sourceDirectory.listFiles()) { if (file.isDirectory()) { sendDirectory(remoteOut, remoteIn, file, file.getName()); } if (file.isFile()) { sendFile(remoteOut, remoteIn, file, file.getName()); } } remoteOut.write("E\n".getBytes()); remoteOut.flush(); checkResponseStream(remoteIn); LOG.debug("Sending directory: {} ... done", directoryName); } private void sendFile(OutputStream remoteOut, InputStream remoteIn, File sourceFile, String fileName) throws IOException, LpException { LOG.debug("Sending file: {} ... ", fileName); if (fileName.indexOf('/') > 0) { throw new IllegalArgumentException("File name '" + fileName + "'"); } // Send command for new file. final Long fileSize = sourceFile.length(); String command = "C0644 " + fileSize + " " + fileName + "\n"; remoteOut.write(command.getBytes()); remoteOut.flush(); checkResponseStream(remoteIn); // Copy file. try (FileInputStream sourceFileStream = new FileInputStream(sourceFile)) { IOUtils.copy(sourceFileStream, remoteOut); } remoteOut.flush(); // Write '\0' as the end of file. remoteOut.write(0); remoteOut.flush(); // Check status. checkResponseStream(remoteIn); LOG.debug("Sending file: {} ... done", fileName); } private void checkResponseStream(InputStream stream) throws IOException, LpException { int response = stream.read(); switch (response) { case -1: // No response from server. throw new LpException("No response from server!"); case 0: // Success. break; case 1: throw new LpException("Error: {}", readResponse(stream)); case 2: throw new LpException("Fatal error: {}", readResponse(stream)); default: throw new LpException("Invalid response: {}", response); } } @Override public void close() throws Exception { if (session != null) { session.disconnect(); } } }
/* * CommonPackage * * Copyright (c) 2022-2022 * * @author: Viet-Man Le (vietman.le@ist.tugraz.at) */ package at.tugraz.ist.ase.common; import lombok.extern.slf4j.Slf4j; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; @Slf4j public class MailService { private final String username; private final String password; private final Properties props; public MailService(String host, String port, String username, String password) { props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); this.username = username; this.password = password; } public MailService(String username, String password) { this("smtp.gmail.com", "587", username, password); } public void sendMail(String from, String to, String subject, String body) { //create the Session object Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); message.setText(body); Transport.send(message); log.info("{}Sent an email successfully [from={}, to={}]", LoggerUtils.tab, from, to); } catch (MessagingException e) { throw new RuntimeException(e); } } }
package com.lyft.android.auth0.jwt; import android.util.Base64; import com.lyft.android.auth0.jwt.exceptions.JWTDecodeException; import com.lyft.android.auth0.jwt.impl.JWTParser; import com.lyft.android.auth0.jwt.interfaces.Claim; import com.lyft.android.auth0.jwt.interfaces.DecodedJWT; import com.lyft.android.auth0.jwt.interfaces.Header; import com.lyft.android.auth0.jwt.interfaces.Payload; import java.io.Serializable; import java.util.Date; import java.util.List; import java.util.Map; import kotlin.text.Charsets; /** * The JWTDecoder class holds the decode method to parse a given JWT token into it's JWT representation. * <p> * This class is thread-safe. */ @SuppressWarnings("WeakerAccess") final class JWTDecoder implements DecodedJWT, Serializable { private static final long serialVersionUID = 1873362438023312895L; private final String[] parts; private final Header header; private final Payload payload; JWTDecoder(String jwt) throws JWTDecodeException { this(new JWTParser(), jwt); } JWTDecoder(JWTParser converter, String jwt) throws JWTDecodeException { parts = TokenUtils.splitToken(jwt); String headerJson; String payloadJson; try { headerJson = new String(Base64.decode(parts[0], Base64.DEFAULT), Charsets.UTF_8); payloadJson = new String(Base64.decode(parts[1], Base64.DEFAULT), Charsets.UTF_8); } catch (NullPointerException e) { throw new JWTDecodeException("The UTF-8 Charset isn't initialized.", e); } catch (IllegalArgumentException e) { throw new JWTDecodeException("The input is not a valid base 64 encoded string.", e); } header = converter.parseHeader(headerJson); payload = converter.parsePayload(payloadJson); } @Override public String getAlgorithm() { return header.getAlgorithm(); } @Override public String getType() { return header.getType(); } @Override public String getContentType() { return header.getContentType(); } @Override public String getKeyId() { return header.getKeyId(); } @Override public Claim getHeaderClaim(String name) { return header.getHeaderClaim(name); } @Override public String getIssuer() { return payload.getIssuer(); } @Override public String getSubject() { return payload.getSubject(); } @Override public List<String> getAudience() { return payload.getAudience(); } @Override public Date getExpiresAt() { return payload.getExpiresAt(); } @Override public Date getNotBefore() { return payload.getNotBefore(); } @Override public Date getIssuedAt() { return payload.getIssuedAt(); } @Override public String getId() { return payload.getId(); } @Override public Claim getClaim(String name) { return payload.getClaim(name); } @Override public Map<String, Claim> getClaims() { return payload.getClaims(); } @Override public String getHeader() { return parts[0]; } @Override public String getPayload() { return parts[1]; } @Override public String getSignature() { return parts[2]; } @Override public String getToken() { return String.format("%s.%s.%s", parts[0], parts[1], parts[2]); } }
/** * * Copyright 2018 iQIYI.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.iqiyi.halberd.liteapp; import android.annotation.SuppressLint; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.iqiyi.halberd.liteapp.api.LiteAppGlobalConfig; import com.iqiyi.halberd.liteapp.api.provider.LiteAppGlobalInitializer; import com.iqiyi.halberd.liteapp.api.provider.LiteAppPackageProvider; import com.iqiyi.halberd.liteapp.common.LiteAppException; import com.iqiyi.halberd.liteapp.context.LiteAppContext; import com.iqiyi.halberd.liteapp.context.LiteAppFactory; import com.iqiyi.halberd.liteapp.event.BridgeEvent; import com.iqiyi.halberd.liteapp.event.impl.EventBridgeImpl; import com.iqiyi.halberd.liteapp.manager.impl.LiteAppDetail; import com.iqiyi.halberd.liteapp.utils.ColorUtils; import com.iqiyi.halberd.liteapp.utils.DisplayUtils; import com.iqiyi.halberd.liteapp.api.provider.LiteAppErrorProvider; import com.iqiyi.halberd.liteapp.utils.LogUtils; import com.iqiyi.halberd.liteapp.view.LiteAppBaseActivity; import com.iqiyi.halberd.liteapp.view.impl.LiteAppFragment; import com.iqiyi.halberd.liteapp.view.impl.TabBarItemView; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by eggizhang@qiyi.com on 2017/7/25. * using this fragment activity */ @SuppressWarnings("deprecation") public class LiteAppFragmentActivity extends LiteAppBaseActivity{ FragmentManager fragmentManager; View fragmentLoadingView = null; //context for lite app app js executor LiteAppContext liteAppAppContext = null; List<TabBarItemView.TabBarItem> tabBarItems = new ArrayList<>(); LinearLayout tabBarView = null; TabBarItemView selectedTab; List<TabBarItemView> tabBarItemViews = new ArrayList<>(); LiteAppFragment rootFragment; View liteAppMainView; Bundle initPageData; int fragmentCount = 0; boolean saveInstanceFlag = false; boolean hasResume =false; boolean stopped = false; private static final String TAG = LiteAppFragmentActivity.class.getName(); public interface OnBackPressedListener{ void onBackPressed(); } static OnBackPressedListener onBackPressedListener; public static void setOnBackPressedListener(OnBackPressedListener listener) { onBackPressedListener = listener; } public static void clearBackPressedListener(){ onBackPressedListener=null; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { LogUtils.log(LogUtils.LOG_MINI_PROGRAM_ACTIVITY_LIFE_CYCLE,LogUtils.LIFE_ACTIVITY+LogUtils.LIFE_CREATE+LogUtils.ACTION_START); //2. starting UI setContentView(R.layout.activity_fragment_lite_app); super.onCreate(null); // // // loading intent // Intent intentForLoading = new // Intent(this, LiteAppLoadingActivity.class); // startActivity(intentForLoading); //1. check initializer LiteAppGlobalInitializer initializer = LiteAppGlobalConfig.getLiteAppInitializer(this.getApplicationContext()); if(initializer!=null){ initializer.init(this.getApplicationContext()); } fragmentLoadingView = findViewById(R.id.fragment_loading_progress); tabBarView = findViewById(R.id.app_fragment_tab_bar); DisplayUtils.tabBarHeight = tabBarView.getMeasuredHeight(); DisplayUtils.containerHeight = tabBarView.getMeasuredHeight(); ((ViewGroup)tabBarView.getParent()).removeView(tabBarView); fragmentManager = getFragmentManager(); fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { @Override public void onBackStackChanged() { Log.d(TAG,"onBackStackChanged"); if(hasResume) { if(getTopFragmentFromManager(fragmentManager)!=null) { ((LiteAppFragment) getTopFragmentFromManager(fragmentManager)).onPageResume(); } } } }); //load Intent intent = getIntent(); liteAppID = intent.getStringExtra(MINI_PROGRAM_ID); needUpdate = intent.getBooleanExtra( MINI_PROGRAM_NEED_UPDATE,true); initPageData = intent.getBundleExtra(MINI_PROGRAM_PAGE_DATA_MAP); liteAppMainView = findViewById(R.id.lite_app_main_view); try{ validateAppIDWithCache(); }catch (Exception e){ LogUtils.logError(LogUtils.LOG_MINI_PROGRAM_ERROR,"validate app fail in OnCreate()",e); coldStart(); } LogUtils.log(LogUtils.LOG_MINI_PROGRAM_ACTIVITY_LIFE_CYCLE,LogUtils.LIFE_ACTIVITY+LogUtils.LIFE_CREATE+LogUtils.ACTION_STOP); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); } @Override protected void onStart() { LogUtils.log(LogUtils.LOG_MINI_PROGRAM_ACTIVITY_LIFE_CYCLE,LogUtils.LIFE_ACTIVITY+LogUtils.LIFE_START); stopped = false; super.onStart(); } @Override protected void onStop() { stopped = true; LogUtils.log(LogUtils.LOG_MINI_PROGRAM_ACTIVITY_LIFE_CYCLE,LogUtils.LIFE_ACTIVITY+LogUtils.LIFE_STOP); super.onStop(); } protected void onSaveInstanceState(Bundle outState) { saveInstanceFlag = true; super.onSaveInstanceState(outState); } @Override protected void onResume(){ LogUtils.log(LogUtils.LOG_MINI_PROGRAM_ACTIVITY_LIFE_CYCLE, LogUtils.LIFE_ACTIVITY + LogUtils.LIFE_RESUME); super.onResume(); hasResume=true; if(getTopFragmentFromManager(fragmentManager)!=null) { ((LiteAppFragment) getTopFragmentFromManager(fragmentManager)).onPageResume(); } } @Override protected void onPause() { LogUtils.log(LogUtils.LOG_MINI_PROGRAM_ACTIVITY_LIFE_CYCLE, LogUtils.LIFE_ACTIVITY + LogUtils.LIFE_PAUSE); super.onPause(); if(getTopFragmentFromManager(fragmentManager)!=null) { ((LiteAppFragment)getTopFragmentFromManager(fragmentManager)).onPagePause(); } } protected void validateAppIDWithCache(){ if(stopped){ finish(); return; } tabBarView.removeAllViews(); if(!TextUtils.isEmpty(liteAppID)){ //1. first try cache, if cache is provided, will load view immediately boolean useCache = true; List<String> pageName = new ArrayList<>(); List<String> cachedString = new ArrayList<>(); List<String> cssPath = new ArrayList<>(); List<byte[]> cachedIconDrawable = new ArrayList<>(); liteAppDetail = LiteAppPackageProvider.getClient().prepareLiteAppIfCache(liteAppID); if(liteAppDetail!=null){ // LiteAppFrameworkManager.getInstance().setDefaultFrameworkVersion( // this,LiteAppFrameworkManager.getInstance().getLiteAppFrameworkVersion(this,liteAppID)); if(liteAppDetail.getTabBar()!=null) { for (LiteAppDetail.TabBarDetail tabBarDetail : liteAppDetail.getTabBar()) { String pageString = LiteAppPackageProvider.getClient() .getLiteAppPageBundle(liteAppID, liteAppDetail.getPageByName(tabBarDetail.getPageName()).getPath()); if (TextUtils.isEmpty(pageString)) { useCache = false; break; } pageName.add(tabBarDetail.getPageName()); cachedString.add(pageString); String pageCssPath = LiteAppPackageProvider.getClient() .getLiteAppPageBundleCssPath(liteAppID, liteAppDetail.getPageByName(tabBarDetail.getPageName()).getPath()); if (TextUtils.isEmpty(pageCssPath)) { cssPath.add(""); } else { cssPath.add(pageCssPath); } String selectIconPath = tabBarDetail.getSelectedIcon(); if (!TextUtils.isEmpty(selectIconPath)) { if(selectIconPath.startsWith("/")){ selectIconPath = selectIconPath.substring(1); } byte[] cacheByte = LiteAppPackageProvider. getClient().getLiteAppFileBytes(liteAppID, selectIconPath); if (cacheByte == null) { useCache = false; break; } cachedIconDrawable.add(cacheByte); } String unSelectIconPath = tabBarDetail.getUnselectedIcon(); if (!TextUtils.isEmpty(unSelectIconPath)) { if(unSelectIconPath.startsWith("/")){ unSelectIconPath = unSelectIconPath.substring(1); } byte[] cacheByte = LiteAppPackageProvider. getClient().getLiteAppFileBytes(liteAppID, unSelectIconPath); if (cacheByte == null) { useCache = false; break; } cachedIconDrawable.add(cacheByte); } } } else { //no tab bar String indexPage = liteAppDetail.getIndex(); String pageString = LiteAppPackageProvider.getClient().getLiteAppPageBundle( liteAppID, liteAppDetail.getPageByName(indexPage).getPath()); if (TextUtils.isEmpty(pageString)) { coldStart(); return; } cachedString.add(pageString); String pageCssPath = LiteAppPackageProvider.getClient() .getLiteAppPageBundleCssPath(liteAppID, liteAppDetail.getPageByName(indexPage).getPath()); if (TextUtils.isEmpty(pageCssPath)) { cssPath.add(""); } else { cssPath.add(pageCssPath); } } } else { useCache = false; } if(useCache) { LogUtils.log(LogUtils.LOG_MINI_PROGRAM_PAGE_LIFE_CYCLE, "using cache start lite app fragment activity"); loadTab(liteAppDetail,cachedIconDrawable); try { validateRootView(pageName, cachedString, cssPath); } catch (LiteAppException e) { LogUtils.logError(LogUtils.LOG_MINI_PROGRAM_ERROR,"base cache error",e); showRetry(); } } else { //3. zip package already downloaded, no need to validate //LiteAppLoadingTask loadTask = new LiteAppLoadingTask(); //loadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); coldStart(); } } else { coldStart(); } } @Override public void routerGoPage(String pageName,JSONObject bundle) { //router is to push new fragment into this activity Log.v(TAG,"inner router to page " + pageName); new PushFragmentTask(pageName, bundle).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } protected void loadTab(LiteAppDetail detail, List<byte[]> images){ try { if (detail == null) { return; } List<LiteAppDetail.TabBarDetail> tabBarDetails = detail.getTabBar(); if (tabBarDetails != null) { int index = 0; for (LiteAppDetail.TabBarDetail tabBarDetail : tabBarDetails) { TabBarItemView.TabBarItem item = new TabBarItemView.TabBarItem(); item.textBarText = tabBarDetail.getTitle(); if(!TextUtils.isEmpty(tabBarDetail.getSelectedColor())) { item.selectedTextColor = ColorUtils.parseColor( tabBarDetail.getSelectedColor()); } else { item.selectedTextColor = Color.parseColor("#9E9E9E"); } if(!TextUtils.isEmpty(tabBarDetail.getUnselectedColor())) { item.unselectedTextColor = ColorUtils.parseColor( tabBarDetail.getUnselectedColor()); } else { item.unselectedTextColor = Color.parseColor("#9E9E9E"); } item.textBarText = tabBarDetail.getTitle(); if (!TextUtils.isEmpty(tabBarDetail.getSelectedIcon())) { if(index < images.size()){ ByteArrayInputStream is = new ByteArrayInputStream(images.get(index)); index = index + 1; item.selectedDrawable = new BitmapDrawable(getResources(), is); }else { coldStart(); } } if (!TextUtils.isEmpty(tabBarDetail.getUnselectedIcon())) { if (index < images.size()) { ByteArrayInputStream is = new ByteArrayInputStream(images.get(index)); index = index + 1; item.unselectedDrawable = new BitmapDrawable(getResources(), is); } else { coldStart(); } } tabBarItems.add(item); } } }catch (Exception e){ LogUtils.logError(LogUtils.LOG_MINI_PROGRAM_ERROR,"failed to load fragment stream",e); } } /**using this method to start lite app from code, either from short cut or package not yet ready */ public void coldStart(){ Log.v(TAG,"cold start lite app fragment activity"); runOnUiThread(new Runnable() { @SuppressLint("StaticFieldLeak") @Override public void run() { new LiteAppLoadingTask(liteAppID){ @Override protected void onPostExecute(LiteAppDetail detail) { super.onPostExecute(detail); if(detail == null){ showRetry(); } else { LiteAppPackageProvider.getClient().cleanMemoryCache(); validateAppIDWithCache(); needUpdate=false; } } }.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR); } }); } public void showRetry(){ runOnUiThread(new Runnable() { @Override public void run() { fragmentLoadingView.setVisibility(View.VISIBLE); LiteAppErrorProvider.error(getString(R.string.load_interface_error)); } }); } @SuppressLint("ResourceType") protected void validateRootView(List<String> pageName, List<String> tabScripts, List<String> css) throws LiteAppException { if(tabBarItems.size() > 0) { invalidTab(); } else { tabBarView.setVisibility(View.GONE); } JSONObject bundle = new JSONObject(); if(initPageData!=null) { try { for (String key : initPageData.keySet()) { bundle.put(key, initPageData.get(key)); } bundle.put("displayWidth", DisplayUtils.getWidth(getApplicationContext())); bundle.put("displayHeight", DisplayUtils.getNoTabBarHeight(getApplicationContext())); bundle.put("packageid", liteAppID); } catch (JSONException e) { LogUtils.logError(LogUtils.LOG_MINI_PROGRAM_ERROR, "failed to get screen width height", e); } } LiteAppFragment fragment = LiteAppFragment. requireInstance(LiteAppFragmentActivity.this, liteAppID, pageName, tabScripts,css, bundle); rootFragment = fragment; rootFragment.setOnPageChangeListener(new LiteAppFragment.OnPageChangeListener() { @Override public void OnPageChanged(int index) { selectedTab.toggleSelect(false); tabBarItemViews.get(index).toggleSelect(true); selectedTab = tabBarItemViews.get(index); } }); rootFragment.setTabView(tabBarView); String tag = MINI_PROGRAM_ID + "/root/" + String.valueOf(fragmentCount); fragmentCount = fragmentCount +1; //pop up back stacks if activity is restored FragmentTransaction transaction = fragmentManager.beginTransaction(); if (fragmentManager.getBackStackEntryCount() > 0){ transaction.replace(R.id.lite_app_container_fragment, fragment, tag); } else { transaction.add(R.id.lite_app_container_fragment, fragment, tag); } LogUtils.log(LogUtils.LOG_MINI_PROGRAM_FRAGMENT_LIFE_CYCLE,LogUtils.LIFE_FRAGMENT+LogUtils.FRAGMENT_PUSH); transaction.setTransition(FragmentTransaction.TRANSIT_NONE); transaction.addToBackStack(tag); transaction.commit(); stopLoading(); liteAppMainView.setVisibility(View.VISIBLE); //after load ,if need update update in back ground if(needUpdate){ @SuppressLint("StaticFieldLeak") LiteAppLoadingTask task = new LiteAppLoadingTask(liteAppID){ @Override protected void onPostExecute(LiteAppDetail detail) { if (detail==null){ LogUtils.log(LogUtils.LOG_MINI_PROGRAM_CACHE, LogUtils.CACHE_NETWORK + LogUtils.CACHE_CHECK_UPDATE + LogUtils.COMMON_FAIL); } else { needUpdate = false; LogUtils.log(LogUtils.LOG_MINI_PROGRAM_CACHE, LogUtils.CACHE_NETWORK + LogUtils.CACHE_CHECK_UPDATE + LogUtils.COMMON_SUCCESS); } super.onPostExecute(detail); } }; task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } public void invalidTab(){ tabBarView.removeAllViews(); tabBarItemViews.clear(); int index = 0; for(TabBarItemView.TabBarItem item : tabBarItems){ final TabBarItemView tab = getLayoutInflater() .inflate(R.layout.widget_tab_bar_item,tabBarView, false) .findViewById(R.id.tab_bar_item_view); tabBarView.addView(tab); tabBarItemViews.add(tab); tab.setTabBarItem(item); int currentIndex = index++; tab.setTag(currentIndex); tab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(selectedTab!=null){ selectedTab.toggleSelect(false); } if(!tab.isSelected()){ tab.toggleSelect(true); tabSwitchCurrentFragment((int)v.getTag()); selectedTab = tab; } } }); if(selectedTab ==null){ selectedTab = tab; tab.toggleSelect(true); } } } public void tabSwitchCurrentFragment(int selectIndex){ rootFragment.setPage(selectIndex); } boolean popping = false; @Override public void onBackPressed() { if(onBackPressedListener!=null){ onBackPressedListener.onBackPressed(); return; } if(fragmentManager.getBackStackEntryCount() <= 1){ Fragment topFragment = getTopFragmentFromManager(fragmentManager); if(topFragment!=null){ ((LiteAppFragment)topFragment).onPagePause(); } //root view back ,finish activity if(getIntent().getBooleanExtra(MINI_PROGRAM_NEW_TASK,false)){ moveTaskToBack(true); } else { //avoid memory leaks fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); finish(); } } else { popFragmentAnimate(); } } public void stopLoading(){ fragmentLoadingView.setVisibility(View.GONE); } @Override protected void onDestroy() { LogUtils.log(LogUtils.LOG_MINI_PROGRAM_ACTIVITY_LIFE_CYCLE,LogUtils.LIFE_ACTIVITY+LogUtils.LIFE_DESTROY+LogUtils.ACTION_START); if(liteAppAppContext!=null) { LiteAppFactory.disposeLiteAppContext(liteAppAppContext); } rootFragment = null; //avoid memory leaks setContentView(new View(this)); super.onDestroy(); LiteAppPackageProvider.getClient().cleanMemoryCache(); LogUtils.log(LogUtils.LOG_MINI_PROGRAM_ACTIVITY_LIFE_CYCLE,LogUtils.LIFE_ACTIVITY+LogUtils.LIFE_DESTROY+LogUtils.ACTION_STOP); } @SuppressLint("StaticFieldLeak") private class PushFragmentTask extends AsyncTask<Void,Void,Void>{ String pageName; JSONObject bundle; String script= ""; String cssPath = ""; PushFragmentTask(String path, JSONObject bundle){ this.pageName = path; this.bundle = bundle; } @Override protected Void doInBackground(Void... params) { script = LiteAppPackageProvider.getClient().getLiteAppPageBundle(liteAppID , liteAppDetail.getPageByName(pageName).getPath()); cssPath = LiteAppPackageProvider.getClient().getLiteAppPageBundleCssPath( liteAppID, liteAppDetail.getPageByName(pageName).getPath()); runOnUiThread(new Runnable() { @SuppressLint("ResourceType") @Override public void run() { stopLoading(); if(bundle == null){ bundle = new JSONObject(); } try { bundle.put("displayWidth", DisplayUtils.getWidth(getApplicationContext())); bundle.put("displayHeight", DisplayUtils.getNoTabBarHeight(getApplicationContext())); bundle.put("packageid", liteAppID); } catch (JSONException e) { LogUtils.logError(LogUtils.LOG_MINI_PROGRAM_ERROR,"failed to get screen width height",e); } final LiteAppFragment fragment; try { fragment = LiteAppFragment. requireInstance(LiteAppFragmentActivity.this, liteAppID, pageName, script, cssPath, bundle); final FragmentTransaction transaction = fragmentManager.beginTransaction(); String newFragmentTag = MINI_PROGRAM_ID + "/" + pageName + "/" + fragmentCount; fragmentCount = fragmentCount +1; transaction.add(R.id.lite_app_container_fragment, fragment,newFragmentTag); LogUtils.log(LogUtils.LOG_MINI_PROGRAM_FRAGMENT_LIFE_CYCLE,LogUtils.LIFE_FRAGMENT+LogUtils.FRAGMENT_PUSH); String oldFragmentTag = fragmentManager.getBackStackEntryAt( fragmentManager.getBackStackEntryCount() - 1).getName(); transaction.hide(fragmentManager.findFragmentByTag(oldFragmentTag)); transaction.show(fragment); transaction.addToBackStack(newFragmentTag); ((LiteAppFragment)fragmentManager.findFragmentByTag(oldFragmentTag)).onPagePause(); fragment.setPreFragment(fragmentManager.findFragmentByTag(oldFragmentTag)); liteAppMainView.postDelayed(new Runnable() { @Override public void run() { transaction.commit(); titleBarShowBackButton(); } },150); } catch (LiteAppException e) { LogUtils.logError(LogUtils.LOG_MINI_PROGRAM_ERROR,"base cache error",e); } } }); return null; } } public void popFragmentAnimate(){ if(popping){ return; } popping = true; LogUtils.log(LogUtils.LOG_MINI_PROGRAM_FRAGMENT_LIFE_CYCLE,LogUtils.LIFE_FRAGMENT+LogUtils.FRAGMENT_POP); Fragment top = getTopFragmentFromManager(fragmentManager); Fragment second = getSecondStackFragmentFromManager(fragmentManager); if(top !=null && second !=null) { if(top.getView()!=null&& second.getView()!=null) { top.getView().startAnimation(LiteAppFragment.destroyOutAnimation); second.getView().startAnimation(LiteAppFragment.destroyInAnimation); } ((LiteAppFragment) getTopFragmentFromManager(fragmentManager)).onPagePause(); getWindow().getDecorView().postDelayed(new Runnable() { @Override public void run() { //after transaction animation popping = false; fragmentManager.popBackStack(); } }, 300); } if(fragmentManager.getBackStackEntryCount() <= 2){ //root view back ,finish activity titleBarShowCloseButton(); } } public static Fragment getTopFragmentFromManager(FragmentManager manager){ if(manager!=null) { int count = manager.getBackStackEntryCount(); if (count>0){ String fragmentTag = manager.getBackStackEntryAt(count - 1).getName(); return manager.findFragmentByTag(fragmentTag); } } return null; } public static Fragment getSecondStackFragmentFromManager(FragmentManager manager){ if(manager!=null) { int count = manager.getBackStackEntryCount(); if (count>1){ String fragmentTag = manager.getBackStackEntryAt(count - 2).getName(); return manager.findFragmentByTag(fragmentTag); } } return null; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); BridgeEvent event = new BridgeEvent(); event.setType("onPageResult_js"); event.setIntercepted(false); event.setLocal(false); HashMap<String,Object> params=new HashMap<>(); params.put("requestCode",requestCode); params.put("resultCode",resultCode); Bundle b=null; if(data!=null){ b=data.getExtras(); } if (b!=null){ Map<String,Object> dataForJs=new HashMap<>(); Set<String> keys=b.keySet(); for (String key : keys) { dataForJs.put(key, b.get(key)); } params.put("data",dataForJs); } event.setData(new JSONObject(params).toString()); EventBridgeImpl.getInstance().triggerEvent(event); } }
/* * Copyright (c) 2011-2014, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.alg.feature.detect.interest; import boofcv.abst.feature.detect.interest.ConfigSiftDetector; import boofcv.factory.feature.detect.interest.FactoryInterestPointAlgs; import boofcv.gui.ListDisplayPanel; import boofcv.gui.feature.VisualizeFeatures; import boofcv.gui.image.ShowImages; import boofcv.gui.image.VisualizeImageData; import boofcv.io.image.ConvertBufferedImage; import boofcv.io.image.UtilImageIO; import boofcv.struct.BoofDefaults; import boofcv.struct.image.ImageFloat32; import java.awt.image.BufferedImage; /** * @author Peter Abeles */ public class DebugSiftDetectorApp { public static void main( String args[] ) { BufferedImage input = UtilImageIO.loadImage("../data/evaluation/sunflowers.png"); // BufferedImage input = UtilImageIO.loadImage("../data/evaluation/shapes01.png"); ImageFloat32 gray = ConvertBufferedImage.convertFromSingle(input, null, ImageFloat32.class); SiftDetector alg = FactoryInterestPointAlgs.siftDetector(new ConfigSiftDetector(3,10,150,5)); SiftImageScaleSpace imageSS = new SiftImageScaleSpace(1.6f, 5, 4, false); imageSS.constructPyramid(gray); imageSS.computeFeatureIntensity(); alg.process(imageSS); System.out.println("total features found: "+alg.getFoundPoints().size()); VisualizeFeatures.drawScalePoints(input.createGraphics(), alg.getFoundPoints().toList(), BoofDefaults.SCALE_SPACE_CANONICAL_RADIUS); ListDisplayPanel dog = new ListDisplayPanel(); for( int i = 0; i < alg.ss.dog.length; i++ ) { int scale = i % (alg.ss.numScales-1); int octave = i / (alg.ss.numScales-1); BufferedImage img = VisualizeImageData.colorizeSign(alg.ss.dog[i],null,-1); dog.addImage(img,octave+" "+scale); } ListDisplayPanel ss = new ListDisplayPanel(); for( int i = 0; i < alg.ss.scale.length; i++ ) { int scale = i % alg.ss.numScales; int octave = i / alg.ss.numScales; BufferedImage img = VisualizeImageData.grayMagnitude(alg.ss.scale[i],null,255); ss.addImage(img,octave+" "+scale); } ShowImages.showWindow(dog, "Octave DOG"); ShowImages.showWindow(ss, "Octave Scales"); ShowImages.showWindow(input, "Found Features"); System.out.println("Done"); } }
package com.titaniumproductionco.db.generator; import com.titaniumproductionco.db.services.LoginService; import com.titaniumproductionco.db.services.Role; public class UserGenerator { private int uid; private int argID; private Role role; public UserGenerator(Role r, int argID) { role = r; this.argID = argID; } public String[] generate(int id, DataGenerator gen) { uid = id; byte[] salt = LoginService.newSalt(); String saltString = LoginService.bytesToString(salt); String hashPass = LoginService.hashPassword(salt, "boss".toCharArray()); String roleName = role.NAME; String username = Dictionary.randomPerson(gen.rand()); return new String[] { id + "", username, saltString, hashPass, roleName }; } public String[] generateArg(Role targetRole) { if (role == targetRole) { return new String[] { uid + "", argID + "" }; } return null; } }
/* * Copyright 2018 Smart Society Services B.V. * * 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 */ package org.opensmartgridplatform.domain.core.valueobjects.smartmetering; import java.io.Serializable; public class GetMbusEncryptionKeyStatusByChannelResponseData extends ActionResponse implements Serializable { private static final long serialVersionUID = 3636769765482239443L; private final EncryptionKeyStatusType encryptionKeyStatus; private final short channel; private final String gatewayDeviceIdentification; public GetMbusEncryptionKeyStatusByChannelResponseData( final String gatewayDeviceIdentification, final EncryptionKeyStatusType encryptionKeyStatus, final short channel) { this.encryptionKeyStatus = encryptionKeyStatus; this.channel = channel; this.gatewayDeviceIdentification = gatewayDeviceIdentification; } public EncryptionKeyStatusType getEncryptionKeyStatus() { return this.encryptionKeyStatus; } public short getChannel() { return this.channel; } public String getGatewayDeviceIdentification() { return this.gatewayDeviceIdentification; } }
package com.anysoftkeyboard.saywhat; import android.content.Context; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import com.f2prateek.rx.preferences2.Preference; import com.menny.android.anysoftkeyboard.AnyApplication; import com.menny.android.anysoftkeyboard.R; public class TimedNoticeHelper { public interface NextTimeProvider { long getNextTimeOffset(int timesShown); } private final Preference<String> mDataHolder; private final Preference<Integer> mTimesShownHolder; private final NextTimeProvider mNextTimeInMilliSecondsProvider; private long mNextTimeToShow; public TimedNoticeHelper( @NonNull Context context, @StringRes int prefKey, long timeBetweenShows) { this(context, prefKey, timesShown -> timeBetweenShows); } public TimedNoticeHelper( @NonNull Context context, @StringRes int prefKey, @NonNull NextTimeProvider timeProvider) { mNextTimeInMilliSecondsProvider = timeProvider; final String prefKeyTime = context.getString(prefKey); final String prefKeyShown = context.getString(prefKey) + "_SHOWN_TIMES"; mDataHolder = AnyApplication.prefs(context) .getString( prefKeyTime, R.string.settings_default_notice_never_before_seen_value); mTimesShownHolder = AnyApplication.prefs(context) .getInteger( prefKeyShown, R.integer.settings_default_notice_never_before_seen_times_value); mNextTimeToShow = Long.parseLong(mDataHolder.get()); } public boolean shouldShow() { return SystemClock.elapsedRealtime() >= mNextTimeToShow; } public void markAsShown() { final int timesShown = mTimesShownHolder.get(); mTimesShownHolder.set(timesShown + 1); mNextTimeToShow = SystemClock.elapsedRealtime() + mNextTimeInMilliSecondsProvider.getNextTimeOffset(timesShown); mDataHolder.set(Long.toString(mNextTimeToShow)); } }
package ru.job4j.tictactoe.model.menu.usecase; import org.junit.Test; import ru.job4j.tictactoe.model.menu.entities.Node; import ru.job4j.tictactoe.model.menu.entities.NodeImpl; import static org.junit.Assert.*; public class MenuImplTest { @Test public void findById() { Node node = new NodeImpl("011", "AI", "1"); Menu menu = new MenuImpl( new NodeImpl("0", "GAME MENU", "0", new NodeImpl[]{ new NodeImpl("01", "First move", "1", new Node[]{ node, }), }) ); assertEquals(node, menu.findById("011")); assertNull(menu.findById("012")); } }
/* * Copyright 2014-2015 Open Networking Laboratory * * 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.onosproject.net.packet.impl; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.Service; import org.onosproject.core.ApplicationId; import org.onosproject.core.CoreService; import org.onosproject.net.Device; import org.onosproject.net.device.DeviceEvent; import org.onosproject.net.device.DeviceListener; import org.onosproject.net.device.DeviceService; import org.onosproject.net.flow.DefaultTrafficTreatment; import org.onosproject.net.flow.FlowRuleService; import org.onosproject.net.flow.TrafficSelector; import org.onosproject.net.flowobjective.DefaultForwardingObjective; import org.onosproject.net.flowobjective.FlowObjectiveService; import org.onosproject.net.flowobjective.ForwardingObjective; import org.onosproject.net.flowobjective.Objective; import org.onosproject.net.flowobjective.ObjectiveContext; import org.onosproject.net.flowobjective.ObjectiveError; import org.onosproject.net.packet.DefaultPacketRequest; import org.onosproject.net.packet.OutboundPacket; import org.onosproject.net.packet.PacketContext; import org.onosproject.net.packet.PacketEvent; import org.onosproject.net.packet.PacketPriority; import org.onosproject.net.packet.PacketProcessor; import org.onosproject.net.packet.PacketProcessorEntry; import org.onosproject.net.packet.PacketProvider; import org.onosproject.net.packet.PacketProviderRegistry; import org.onosproject.net.packet.PacketProviderService; import org.onosproject.net.packet.PacketRequest; import org.onosproject.net.packet.PacketService; import org.onosproject.net.packet.PacketStore; import org.onosproject.net.packet.PacketStoreDelegate; import org.onosproject.net.provider.AbstractProviderRegistry; import org.onosproject.net.provider.AbstractProviderService; import org.slf4j.Logger; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static com.google.common.base.Preconditions.checkNotNull; import static org.onlab.util.Tools.groupedThreads; import static org.onosproject.security.AppGuard.checkPermission; import static org.onosproject.security.AppPermission.Type.*; import static org.slf4j.LoggerFactory.getLogger; /** * Provides a basic implementation of the packet SB &amp; NB APIs. */ @Component(immediate = true) @Service public class PacketManager extends AbstractProviderRegistry<PacketProvider, PacketProviderService> implements PacketService, PacketProviderRegistry { private final Logger log = getLogger(getClass()); private static final String TABLE_TYPE_MSG = "Table Type cannot be null. For requesting packets without " + "table hints, use other methods in the packetService API"; private final PacketStoreDelegate delegate = new InternalStoreDelegate(); @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private CoreService coreService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private DeviceService deviceService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private FlowRuleService flowService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private PacketStore store; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private FlowObjectiveService objectiveService; private ExecutorService eventHandlingExecutor; private final DeviceListener deviceListener = new InternalDeviceListener(); private final List<ProcessorEntry> processors = Lists.newCopyOnWriteArrayList(); private ApplicationId appId; @Activate public void activate() { eventHandlingExecutor = Executors.newSingleThreadExecutor( groupedThreads("onos/net/packet", "event-handler")); appId = coreService.getAppId(CoreService.CORE_APP_NAME); store.setDelegate(delegate); deviceService.addListener(deviceListener); store.existingRequests().forEach(this::pushToAllDevices); log.info("Started"); } @Deactivate public void deactivate() { store.unsetDelegate(delegate); deviceService.removeListener(deviceListener); eventHandlingExecutor.shutdown(); log.info("Stopped"); } @Override public void addProcessor(PacketProcessor processor, int priority) { checkPermission(PACKET_EVENT); checkNotNull(processor, "Processor cannot be null"); ProcessorEntry entry = new ProcessorEntry(processor, priority); // Insert the new processor according to its priority. int i = 0; for (; i < processors.size(); i++) { if (priority < processors.get(i).priority()) { break; } } processors.add(i, entry); } @Override public void removeProcessor(PacketProcessor processor) { checkPermission(PACKET_EVENT); checkNotNull(processor, "Processor cannot be null"); // Remove the processor entry. for (int i = 0; i < processors.size(); i++) { if (processors.get(i).processor() == processor) { processors.remove(i); break; } } } @Override public List<PacketProcessorEntry> getProcessors() { return ImmutableList.copyOf(processors); } @Override public void requestPackets(TrafficSelector selector, PacketPriority priority, ApplicationId appId) { checkPermission(PACKET_READ); checkNotNull(selector, "Selector cannot be null"); checkNotNull(appId, "Application ID cannot be null"); PacketRequest request = new DefaultPacketRequest(selector, priority, appId); store.requestPackets(request); } @Override public void cancelPackets(TrafficSelector selector, PacketPriority priority, ApplicationId appId) { checkPermission(PACKET_READ); checkNotNull(selector, "Selector cannot be null"); checkNotNull(appId, "Application ID cannot be null"); PacketRequest request = new DefaultPacketRequest(selector, priority, appId); store.cancelPackets(request); } @Override public List<PacketRequest> getRequests() { return store.existingRequests(); } /** * Pushes all rules to the specified device. * * @param device device on which to install packet request flows */ private void pushRulesToDevice(Device device) { log.debug("Pushing packet requests to device {}", device.id()); for (PacketRequest request : store.existingRequests()) { pushRule(device, request); } } /** * Pushes a packet request flow rule to all devices. * * @param request the packet request */ private void pushToAllDevices(PacketRequest request) { log.debug("Pushing packet request {} to all devices", request); for (Device device : deviceService.getDevices()) { pushRule(device, request); } } /** * Removes packet request flow rule from all devices. * * @param request the packet request */ private void removeFromAllDevices(PacketRequest request) { deviceService.getAvailableDevices().forEach(d -> removeRule(d, request)); } /** * Pushes packet intercept flow rules to the device. * * @param device the device to push the rules to * @param request the packet request */ private void pushRule(Device device, PacketRequest request) { if (!device.type().equals(Device.Type.SWITCH)) { return; } ForwardingObjective forwarding = createBuilder(request) .add(new ObjectiveContext() { @Override public void onError(Objective objective, ObjectiveError error) { log.warn("Failed to install packet request {} to {}: {}", request, device.id(), error); } }); objectiveService.forward(device.id(), forwarding); } /** * Removes packet intercept flow rules from the device. * * @param device the device to remove the rules deom * @param request the packet request */ private void removeRule(Device device, PacketRequest request) { if (!device.type().equals(Device.Type.SWITCH)) { return; } ForwardingObjective forwarding = createBuilder(request) .remove(new ObjectiveContext() { @Override public void onError(Objective objective, ObjectiveError error) { log.warn("Failed to withdraw packet request {} from {}: {}", request, device.id(), error); } }); objectiveService.forward(device.id(), forwarding); } private DefaultForwardingObjective.Builder createBuilder(PacketRequest request) { return DefaultForwardingObjective.builder() .withPriority(request.priority().priorityValue()) .withSelector(request.selector()) .fromApp(appId) .withFlag(ForwardingObjective.Flag.VERSATILE) .withTreatment(DefaultTrafficTreatment.builder().punt().build()) .makePermanent(); } @Override public void emit(OutboundPacket packet) { checkPermission(PACKET_WRITE); checkNotNull(packet, "Packet cannot be null"); store.emit(packet); } private void localEmit(OutboundPacket packet) { Device device = deviceService.getDevice(packet.sendThrough()); if (device == null) { return; } PacketProvider packetProvider = getProvider(device.providerId()); if (packetProvider != null) { packetProvider.emit(packet); } } @Override protected PacketProviderService createProviderService(PacketProvider provider) { return new InternalPacketProviderService(provider); } /** * Personalized packet provider service issued to the supplied provider. */ private class InternalPacketProviderService extends AbstractProviderService<PacketProvider> implements PacketProviderService { protected InternalPacketProviderService(PacketProvider provider) { super(provider); } @Override public void processPacket(PacketContext context) { // TODO filter packets sent to processors based on registrations for (ProcessorEntry entry : processors) { try { long start = System.nanoTime(); entry.processor().process(context); entry.addNanos(System.nanoTime() - start); } catch (Exception e) { log.warn("Packet processor {} threw an exception", entry.processor(), e); } } } } /** * Internal callback from the packet store. */ private class InternalStoreDelegate implements PacketStoreDelegate { @Override public void notify(PacketEvent event) { localEmit(event.subject()); } @Override public void requestPackets(PacketRequest request) { pushToAllDevices(request); } @Override public void cancelPackets(PacketRequest request) { removeFromAllDevices(request); } } /** * Internal listener for device service events. */ private class InternalDeviceListener implements DeviceListener { @Override public void event(DeviceEvent event) { eventHandlingExecutor.execute(() -> { try { Device device = event.subject(); switch (event.type()) { case DEVICE_ADDED: case DEVICE_AVAILABILITY_CHANGED: if (deviceService.isAvailable(event.subject().id())) { pushRulesToDevice(device); } break; default: break; } } catch (Exception e) { log.warn("Failed to process {}", event, e); } }); } } /** * Entity for tracking stats for a packet processor. */ private class ProcessorEntry implements PacketProcessorEntry { private final PacketProcessor processor; private final int priority; private long invocations = 0; private long nanos = 0; public ProcessorEntry(PacketProcessor processor, int priority) { this.processor = processor; this.priority = priority; } @Override public PacketProcessor processor() { return processor; } @Override public int priority() { return priority; } @Override public long invocations() { return invocations; } @Override public long totalNanos() { return nanos; } @Override public long averageNanos() { return invocations > 0 ? nanos / invocations : 0; } void addNanos(long nanos) { this.nanos += nanos; this.invocations++; } } }
package br.org.generation.lojagames.model; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity @Table(name = "tb_categorias") public class CategoriaModel { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long idCategoria; @NotBlank(message="Tipo. Não pode ficar vazio!") @Size(min=3, message="Tipo. Tamanho mínimo 3") private String tipoJogo; @Enumerated(value=EnumType.STRING) private PlataformaEnum plataforma; @OneToMany(mappedBy = "categoria", cascade = CascadeType.ALL) @JsonIgnoreProperties("categoria") private List<ProdutoModel> produto; public Long getIdCategoria() { return idCategoria; } public void setIdCategoria(Long idCategoria) { this.idCategoria = idCategoria; } public String getTipoJogo() { return tipoJogo; } public void setTipoJogo(String tipoJogo) { this.tipoJogo = tipoJogo; } public PlataformaEnum getPlataforma() { return plataforma; } public void setPlataforma(PlataformaEnum plataforma) { this.plataforma = plataforma; } public List<ProdutoModel> getProduto() { return produto; } public void setProduto(List<ProdutoModel> produto) { this.produto = produto; } }
/* * Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata * * Portions of this software were developed by the Unidata Program at the * University Corporation for Atmospheric Research. * * Access and use of this software shall impose the following obligations * and understandings on the user. The user is granted the right, without * any fee or cost, to use, copy, modify, alter, enhance and distribute * this software, and any derivative works thereof, and its supporting * documentation for any purpose whatsoever, provided that this entire * notice appears in all copies of the software, derivative works and * supporting documentation. Further, UCAR requests that the user credit * UCAR/Unidata in any publications that result from the use of this * software or in any product that includes this software. The names UCAR * and/or Unidata, however, may not be used in any advertising or publicity * to endorse or promote any products or commercial entity unless specific * written permission is obtained from UCAR/Unidata. The user also * understands that UCAR/Unidata is not obligated to provide the user with * any support, consulting, training or assistance of any kind with regard * to the use, operation and performance of this software nor to provide * the user with any updates, revisions, new versions or "bug fixes." * * THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE. */ package ucar.ma2; /** * DO NOT USE * @author caron * @since Nov 15, 2008 */ public class ArrayRagged extends Array { protected ArrayRagged(int[] shape) { super(shape); } public Class getElementType() { return null; //To change body of implemented methods use File | Settings | File Templates. } /** * DO NOT USE, throws UnsupportedOperationException */ protected Array createView(Index index) { if (index.getSize() == getSize()) return this; throw new UnsupportedOperationException(); } public Object getStorage() { return null; //To change body of implemented methods use File | Settings | File Templates. }// used to create Array from java array protected void copyFrom1DJavaArray(IndexIterator iter, Object javaArray) { //To change body of implemented methods use File | Settings | File Templates. } protected void copyTo1DJavaArray(IndexIterator iter, Object javaArray) { //To change body of implemented methods use File | Settings | File Templates. } ///////////////////////////////////////////////////////////////////////////////////////////////////// /** * DO NOT USE, throws UnsupportedOperationException */ public Array copy() { throw new UnsupportedOperationException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public double getDouble(Index i) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public void setDouble(Index i, double value) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public float getFloat(Index i) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public void setFloat(Index i, float value) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public long getLong(Index i) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public void setLong(Index i, long value) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public int getInt(Index i) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public void setInt(Index i, int value) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public short getShort(Index i) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public void setShort(Index i, short value) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public byte getByte(Index i) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public void setByte(Index i, byte value) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public boolean getBoolean(Index i) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public void setBoolean(Index i, boolean value) { throw new ForbiddenConversionException(); } public Object getObject(Index ima) { return null; //To change body of implemented methods use File | Settings | File Templates. } public void setObject(Index ima, Object value) { //To change body of implemented methods use File | Settings | File Templates. } /** * DO NOT USE, throw ForbiddenConversionException */ public char getChar(Index i) { throw new ForbiddenConversionException(); } /** * DO NOT USE, throw ForbiddenConversionException */ public void setChar(Index i, char value) { throw new ForbiddenConversionException(); } // trusted, assumes that individual dimension lengths have been checked // package private : mostly for iterators public double getDouble(int index) { throw new ForbiddenConversionException(); } public void setDouble(int index, double value) { throw new ForbiddenConversionException(); } public float getFloat(int index) { throw new ForbiddenConversionException(); } public void setFloat(int index, float value) { throw new ForbiddenConversionException(); } public long getLong(int index) { throw new ForbiddenConversionException(); } public void setLong(int index, long value) { throw new ForbiddenConversionException(); } public int getInt(int index) { throw new ForbiddenConversionException(); } public void setInt(int index, int value) { throw new ForbiddenConversionException(); } public short getShort(int index) { throw new ForbiddenConversionException(); } public void setShort(int index, short value) { throw new ForbiddenConversionException(); } public byte getByte(int index) { throw new ForbiddenConversionException(); } public void setByte(int index, byte value) { throw new ForbiddenConversionException(); } public char getChar(int index) { throw new ForbiddenConversionException(); } public void setChar(int index, char value) { throw new ForbiddenConversionException(); } public boolean getBoolean(int index) { throw new ForbiddenConversionException(); } public void setBoolean(int index, boolean value) { throw new ForbiddenConversionException(); } public Object getObject(int elem) { return null; //To change body of implemented methods use File | Settings | File Templates. } public void setObject(int elem, Object value) { //To change body of implemented methods use File | Settings | File Templates. } }
package uk.gov.hmcts.reform.managecase.service.noc; import com.fasterxml.jackson.databind.JsonNode; import com.microsoft.applicationinsights.boot.dependencies.apachecommons.lang3.ArrayUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.idam.client.models.UserInfo; import uk.gov.hmcts.reform.managecase.api.errorhandling.noc.NoCException; import uk.gov.hmcts.reform.managecase.client.datastore.CaseDetails; import uk.gov.hmcts.reform.managecase.client.datastore.model.CaseViewResource; import uk.gov.hmcts.reform.managecase.client.definitionstore.model.ChallengeQuestion; import uk.gov.hmcts.reform.managecase.client.definitionstore.model.ChallengeQuestionsResult; import uk.gov.hmcts.reform.managecase.domain.NoCRequestDetails; import uk.gov.hmcts.reform.managecase.domain.OrganisationPolicy; import uk.gov.hmcts.reform.managecase.repository.DataStoreRepository; import uk.gov.hmcts.reform.managecase.repository.DefinitionStoreRepository; import uk.gov.hmcts.reform.managecase.repository.PrdRepository; import uk.gov.hmcts.reform.managecase.security.SecurityUtils; import uk.gov.hmcts.reform.managecase.util.JacksonUtils; import java.util.List; import static java.util.stream.Collectors.toList; import static uk.gov.hmcts.reform.managecase.api.errorhandling.noc.NoCValidationError.CHANGE_REQUEST; import static uk.gov.hmcts.reform.managecase.api.errorhandling.noc.NoCValidationError.INSUFFICIENT_PRIVILEGE; import static uk.gov.hmcts.reform.managecase.api.errorhandling.noc.NoCValidationError.MULTIPLE_NOC_REQUEST_EVENTS; import static uk.gov.hmcts.reform.managecase.api.errorhandling.noc.NoCValidationError.NOC_EVENT_NOT_AVAILABLE; import static uk.gov.hmcts.reform.managecase.api.errorhandling.noc.NoCValidationError.NOC_REQUEST_ONGOING; import static uk.gov.hmcts.reform.managecase.api.errorhandling.noc.NoCValidationError.NO_ORG_POLICY_WITH_ROLE; @Service public class NoticeOfChangeQuestions { public static final String PUI_ROLE = "pui-caa"; private static final String CHALLENGE_QUESTION_ID = "NoCChallenge"; private final DataStoreRepository dataStoreRepository; private final DefinitionStoreRepository definitionStoreRepository; private final PrdRepository prdRepository; private final JacksonUtils jacksonUtils; private final SecurityUtils securityUtils; @Autowired public NoticeOfChangeQuestions(@Qualifier("defaultDataStoreRepository") DataStoreRepository dataStoreRepository, DefinitionStoreRepository definitionStoreRepository, PrdRepository prdRepository, JacksonUtils jacksonUtils, SecurityUtils securityUtils) { this.dataStoreRepository = dataStoreRepository; this.definitionStoreRepository = definitionStoreRepository; this.prdRepository = prdRepository; this.jacksonUtils = jacksonUtils; this.securityUtils = securityUtils; } public ChallengeQuestionsResult getChallengeQuestions(String caseId) { ChallengeQuestionsResult challengeQuestionsResult = challengeQuestions(caseId).getChallengeQuestionsResult(); List<ChallengeQuestion> challengeQuestionsResponse = challengeQuestionsResult.getQuestions().stream() .map(challengeQuestion -> challengeQuestion.cloneWithoutAnswers(challengeQuestion)) .collect(toList()); return ChallengeQuestionsResult.builder().questions(challengeQuestionsResponse).build(); } public NoCRequestDetails challengeQuestions(String caseId) { CaseViewResource caseViewResource = dataStoreRepository.findCaseByCaseId(caseId); checkForCaseEvents(caseViewResource); CaseDetails caseDetails = dataStoreRepository.findCaseByCaseIdAsSystemUserUsingExternalApi(caseId); checkCaseFields(caseDetails); validateUserRoles(caseDetails.getJurisdiction(), getUserInfo()); ChallengeQuestionsResult challengeQuestionsResult = definitionStoreRepository.challengeQuestions(caseDetails.getCaseTypeId(), CHALLENGE_QUESTION_ID); List<OrganisationPolicy> organisationPolicies = findPolicies(caseDetails); checkOrgPoliciesForRoles(challengeQuestionsResult, organisationPolicies); return NoCRequestDetails.builder() .caseViewResource(caseViewResource) .challengeQuestionsResult(challengeQuestionsResult) .caseDetails(caseDetails) .build(); } private void checkOrgPoliciesForRoles(ChallengeQuestionsResult challengeQuestionsResult, List<OrganisationPolicy> organisationPolicies) { if (organisationPolicies.isEmpty()) { throw new NoCException(NO_ORG_POLICY_WITH_ROLE); } challengeQuestionsResult.getQuestions().forEach(challengeQuestion -> { boolean missingRole = challengeQuestion.getAnswers().stream() .anyMatch(answer -> !isRoleInOrganisationPolicies(organisationPolicies, answer.getCaseRoleId())); if (missingRole) { throw new NoCException(NO_ORG_POLICY_WITH_ROLE); } }); } private boolean isRoleInOrganisationPolicies(List<OrganisationPolicy> organisationPolicies, String role) { return organisationPolicies.stream() .anyMatch(organisationPolicy -> organisationPolicy.getOrgPolicyCaseAssignedRole().equals(role)); } private void validateUserRoles(String jurisdiction, UserInfo userInfo) { List<String> roles = userInfo.getRoles(); if (!roles.contains(PUI_ROLE) && !isActingAsSolicitor(roles, jurisdiction)) { throw new NoCException(INSUFFICIENT_PRIVILEGE); } } private boolean isActingAsSolicitor(List<String> roles, String jurisdiction) { return securityUtils.hasSolicitorAndJurisdictionRoles(roles, jurisdiction); } private UserInfo getUserInfo() { return securityUtils.getUserInfo(); } private void checkCaseFields(CaseDetails caseDetails) { if (caseDetails.findCorNodes().size() > 1) { throw new NoCException(CHANGE_REQUEST); } if (caseDetails.hasCaseRoleId()) { throw new NoCException(NOC_REQUEST_ONGOING); } } private void checkForCaseEvents(CaseViewResource caseViewResource) { if (caseViewResource.getCaseViewActionableEvents() == null || ArrayUtils.isEmpty(caseViewResource.getCaseViewActionableEvents())) { throw new NoCException(NOC_EVENT_NOT_AVAILABLE); } else if (caseViewResource.getCaseViewActionableEvents().length != 1) { throw new NoCException(MULTIPLE_NOC_REQUEST_EVENTS); } } private List<OrganisationPolicy> findPolicies(CaseDetails caseDetails) { List<JsonNode> policyNodes = caseDetails.findOrganisationPolicyNodes(); return policyNodes.stream() .map(node -> jacksonUtils.convertValue(node, OrganisationPolicy.class)) .collect(toList()); } }
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.codeguruprofiler.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * The structure representing the removePermissionResponse. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/RemovePermission" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class RemovePermissionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The resource-based policy. * </p> */ private String policy; /** * <p> * A unique identifier for the current revision of the policy. * </p> */ private String revisionId; /** * <p> * The resource-based policy. * </p> * * @param policy * The resource-based policy. */ public void setPolicy(String policy) { this.policy = policy; } /** * <p> * The resource-based policy. * </p> * * @return The resource-based policy. */ public String getPolicy() { return this.policy; } /** * <p> * The resource-based policy. * </p> * * @param policy * The resource-based policy. * @return Returns a reference to this object so that method calls can be chained together. */ public RemovePermissionResult withPolicy(String policy) { setPolicy(policy); return this; } /** * <p> * A unique identifier for the current revision of the policy. * </p> * * @param revisionId * A unique identifier for the current revision of the policy. */ public void setRevisionId(String revisionId) { this.revisionId = revisionId; } /** * <p> * A unique identifier for the current revision of the policy. * </p> * * @return A unique identifier for the current revision of the policy. */ public String getRevisionId() { return this.revisionId; } /** * <p> * A unique identifier for the current revision of the policy. * </p> * * @param revisionId * A unique identifier for the current revision of the policy. * @return Returns a reference to this object so that method calls can be chained together. */ public RemovePermissionResult withRevisionId(String revisionId) { setRevisionId(revisionId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getPolicy() != null) sb.append("Policy: ").append(getPolicy()).append(","); if (getRevisionId() != null) sb.append("RevisionId: ").append(getRevisionId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RemovePermissionResult == false) return false; RemovePermissionResult other = (RemovePermissionResult) obj; if (other.getPolicy() == null ^ this.getPolicy() == null) return false; if (other.getPolicy() != null && other.getPolicy().equals(this.getPolicy()) == false) return false; if (other.getRevisionId() == null ^ this.getRevisionId() == null) return false; if (other.getRevisionId() != null && other.getRevisionId().equals(this.getRevisionId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getPolicy() == null) ? 0 : getPolicy().hashCode()); hashCode = prime * hashCode + ((getRevisionId() == null) ? 0 : getRevisionId().hashCode()); return hashCode; } @Override public RemovePermissionResult clone() { try { return (RemovePermissionResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
package com.googlecode.objectify.test.util; import com.google.cloud.datastore.testing.LocalDatastoreHelper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext.Namespace; /** * Sets up and tears down the Local Datastore emulator, defaults to strong consistency */ @RequiredArgsConstructor @Slf4j public class LocalDatastoreExtension implements BeforeAllCallback, BeforeEachCallback { private final double consistency; public LocalDatastoreExtension() { this(1.0); } @Override public void beforeAll(final ExtensionContext context) throws Exception { if (getHelper(context) == null) { log.info("Creating new LocalDatastoreHelper"); final LocalDatastoreHelper helper = LocalDatastoreHelper.create(consistency); context.getRoot().getStore(Namespace.GLOBAL).put(LocalDatastoreHelper.class, helper); helper.start(); } } @Override public void beforeEach(final ExtensionContext context) throws Exception { final LocalDatastoreHelper helper = getHelper(context); helper.reset(); } /** Get the helper created in beforeAll; it should be global so there will one per test run */ public static LocalDatastoreHelper getHelper(final ExtensionContext context) { return context.getRoot().getStore(Namespace.GLOBAL).get(LocalDatastoreHelper.class, LocalDatastoreHelper.class); } }
/* * Copyright 2013-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.aws.autoconfigure.jdbc; import com.amazonaws.services.rds.AmazonRDS; import com.amazonaws.services.rds.AmazonRDSClient; import com.amazonaws.services.rds.model.DBInstance; import com.amazonaws.services.rds.model.DescribeDBInstancesRequest; import com.amazonaws.services.rds.model.DescribeDBInstancesResult; import com.amazonaws.services.rds.model.Endpoint; import org.junit.After; import org.junit.Test; import org.mockito.Mockito; import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.cloud.aws.jdbc.rds.AmazonRdsDataSourceFactoryBean; import org.springframework.cloud.aws.jdbc.rds.AmazonRdsReadReplicaAwareDataSourceFactoryBean; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import javax.sql.DataSource; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; public class AmazonRdsDatabaseAutoConfigurationTest { private AnnotationConfigApplicationContext context; @After public void tearDown() throws Exception { if (this.context != null) { this.context.close(); } } @Test public void configureBean_withDefaultClientSpecifiedAndNoReadReplica_configuresFactoryBeanWithoutReadReplica() throws Exception { //Arrange this.context = new AnnotationConfigApplicationContext(); this.context.register(ApplicationConfigurationWithoutReadReplica.class); this.context.register(AmazonRdsDatabaseAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "cloud.aws.rds.test.password:secret"); //Act this.context.refresh(); //Assert assertNotNull(this.context.getBean(DataSource.class)); assertNotNull(this.context.getBean(AmazonRdsDataSourceFactoryBean.class)); } @Test public void configureBean_withCustomDataBaseName_configuresFactoryBeanWithCustomDatabaseName() throws Exception { //Arrange this.context = new AnnotationConfigApplicationContext(); this.context.register(ApplicationConfigurationWithoutReadReplica.class); this.context.register(AmazonRdsDatabaseAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "cloud.aws.rds.test.password:secret", "cloud.aws.rds.test.databaseName:fooDb"); //Act this.context.refresh(); //Assert DataSource dataSource = this.context.getBean(DataSource.class); assertNotNull(dataSource); assertNotNull(this.context.getBean(AmazonRdsDataSourceFactoryBean.class)); assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource); assertTrue(((org.apache.tomcat.jdbc.pool.DataSource) dataSource).getUrl().endsWith("fooDb")); } @Test public void configureBean_withDefaultClientSpecifiedAndNoReadReplicaAndMultipleDatabases_configuresBothDatabases() throws Exception { //Arrange this.context = new AnnotationConfigApplicationContext(); this.context.register(ApplicationConfigurationWithMultipleDatabases.class); this.context.register(AmazonRdsDatabaseAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "cloud.aws.rds.test.password:secret","cloud.aws.rds.anotherOne.password:verySecret"); //Act this.context.refresh(); //Assert assertNotNull(this.context.getBean("test",DataSource.class)); assertNotNull(this.context.getBean("&test",AmazonRdsDataSourceFactoryBean.class)); assertNotNull(this.context.getBean("anotherOne",DataSource.class)); assertNotNull(this.context.getBean("&anotherOne",AmazonRdsDataSourceFactoryBean.class)); } @Test public void configureBean_withDefaultClientSpecifiedAndReadReplica_configuresFactoryBeanWithReadReplicaEnabled() throws Exception { //Arrange this.context = new AnnotationConfigApplicationContext(); this.context.register(ApplicationConfigurationWithReadReplica.class); this.context.register(AmazonRdsDatabaseAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "cloud.aws.rds.test.password:secret", "cloud.aws.rds.test.readReplicaSupport:true"); //Act this.context.refresh(); //Assert assertNotNull(this.context.getBean(DataSource.class)); assertNotNull(this.context.getBean(AmazonRdsReadReplicaAwareDataSourceFactoryBean.class)); } public static class ApplicationConfigurationWithoutReadReplica { @Bean public AmazonRDSClient amazonRDS() { AmazonRDSClient client = Mockito.mock(AmazonRDSClient.class); when(client.describeDBInstances(new DescribeDBInstancesRequest().withDBInstanceIdentifier("test"))).thenReturn( new DescribeDBInstancesResult(). withDBInstances(new DBInstance(). withDBInstanceStatus("available"). withDBName("test"). withDBInstanceIdentifier("test"). withEngine("mysql"). withMasterUsername("admin"). withEndpoint(new Endpoint(). withAddress("localhost"). withPort(3306) ).withReadReplicaDBInstanceIdentifiers("read1") ) ); return client; } } public static class ApplicationConfigurationWithMultipleDatabases { @Bean public AmazonRDS amazonRDS() { AmazonRDSClient client = Mockito.mock(AmazonRDSClient.class); when(client.describeDBInstances(new DescribeDBInstancesRequest().withDBInstanceIdentifier("test"))).thenReturn( new DescribeDBInstancesResult(). withDBInstances(new DBInstance(). withDBInstanceStatus("available"). withDBName("test"). withDBInstanceIdentifier("test"). withEngine("mysql"). withMasterUsername("admin"). withEndpoint(new Endpoint(). withAddress("localhost"). withPort(3306) ) ) ); when(client.describeDBInstances(new DescribeDBInstancesRequest().withDBInstanceIdentifier("anotherOne"))).thenReturn( new DescribeDBInstancesResult(). withDBInstances(new DBInstance(). withDBInstanceStatus("available"). withDBName("test"). withDBInstanceIdentifier("anotherOne"). withEngine("mysql"). withMasterUsername("admin"). withEndpoint(new Endpoint(). withAddress("localhost"). withPort(3306) ) ) ); return client; } } public static class ApplicationConfigurationWithReadReplica { @Bean public AmazonRDS amazonRDS() { AmazonRDSClient client = Mockito.mock(AmazonRDSClient.class); when(client.describeDBInstances(new DescribeDBInstancesRequest().withDBInstanceIdentifier("test"))).thenReturn( new DescribeDBInstancesResult(). withDBInstances(new DBInstance(). withDBInstanceStatus("available"). withDBName("test"). withDBInstanceIdentifier("test"). withEngine("mysql"). withMasterUsername("admin"). withEndpoint(new Endpoint(). withAddress("localhost"). withPort(3306) ).withReadReplicaDBInstanceIdentifiers("read1") ) ); when(client.describeDBInstances(new DescribeDBInstancesRequest().withDBInstanceIdentifier("read1"))).thenReturn( new DescribeDBInstancesResult(). withDBInstances(new DBInstance(). withDBInstanceStatus("available"). withDBName("read1"). withDBInstanceIdentifier("read1"). withEngine("mysql"). withMasterUsername("admin"). withEndpoint(new Endpoint(). withAddress("localhost"). withPort(3306) ) ) ); return client; } } }
package icbm.classic.client.models; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraftforge.fml.relauncher.Side;import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class MFaSheDiRail1 extends ModelBase { // fields ModelRenderer Shape11; ModelRenderer Shape12; ModelRenderer Shape13; ModelRenderer Shape14; ModelRenderer Shape15; ModelRenderer Shape16; ModelRenderer Shape20; ModelRenderer Shape22; ModelRenderer Shape23; ModelRenderer Shape24; ModelRenderer Shape25; ModelRenderer Shape28; ModelRenderer Shape29; public MFaSheDiRail1() { textureWidth = 128; textureHeight = 128; Shape11 = new ModelRenderer(this, 35, 52); Shape11.addBox(0F, 0F, 0F, 1, 41, 4); Shape11.setRotationPoint(-16F, -23F, -2F); Shape11.setTextureSize(128, 128); Shape11.mirror = true; setRotation(Shape11, 0F, -0.7853982F, 0F); Shape12 = new ModelRenderer(this, 46, 52); Shape12.addBox(0F, 0F, 0F, 3, 19, 2); Shape12.setRotationPoint(-18F, -1F, -3F); Shape12.setTextureSize(128, 128); Shape12.mirror = true; setRotation(Shape12, 0F, -0.7853982F, 0F); Shape13 = new ModelRenderer(this, 0, 20); Shape13.addBox(0F, 0F, 0F, 2, 12, 2); Shape13.setRotationPoint(-16F, 12F, -1F); Shape13.setTextureSize(128, 128); Shape13.mirror = true; setRotation(Shape13, 0F, -0.7853982F, 0F); Shape14 = new ModelRenderer(this, 0, 10); Shape14.addBox(0F, 0F, 0F, 2, 4, 1); Shape14.setRotationPoint(-16F, -27F, -2F); Shape14.setTextureSize(128, 128); Shape14.mirror = true; setRotation(Shape14, 0F, -0.7853982F, 0F); Shape15 = new ModelRenderer(this, 0, 0); Shape15.addBox(0F, 0F, 0F, 16, 1, 8); Shape15.setRotationPoint(-24F, 23F, 0F); Shape15.setTextureSize(128, 128); Shape15.mirror = true; setRotation(Shape15, 0F, 0F, 0F); Shape16 = new ModelRenderer(this, 57, 52); Shape16.addBox(0F, 0F, 0F, 11, 6, 6); Shape16.setRotationPoint(-20F, 18F, -8F); Shape16.setTextureSize(128, 128); Shape16.mirror = true; setRotation(Shape16, 0F, -0.7853982F, 0F); Shape20 = new ModelRenderer(this, 0, 10); Shape20.addBox(0F, 0F, 0F, 2, 4, 1); Shape20.setRotationPoint(-18F, -27F, 0F); Shape20.setTextureSize(128, 128); Shape20.mirror = true; setRotation(Shape20, 0F, -0.7853982F, 0F); Shape22 = new ModelRenderer(this, 8, 10); Shape22.addBox(0F, 0F, 0F, 9, 1, 1); Shape22.setRotationPoint(-17F, 5F, -1F); Shape22.setTextureSize(128, 128); Shape22.mirror = true; setRotation(Shape22, 0F, 0F, 0F); Shape23 = new ModelRenderer(this, 8, 10); Shape23.addBox(0F, 0F, 0F, 9, 1, 1); Shape23.setRotationPoint(-17F, -10F, -1F); Shape23.setTextureSize(128, 128); Shape23.mirror = true; setRotation(Shape23, 0F, 0F, 0F); Shape24 = new ModelRenderer(this, 15, 20); Shape24.addBox(0F, 0F, 0F, 6, 1, 1); Shape24.setRotationPoint(-21F, 5F, 6F); Shape24.setTextureSize(128, 128); Shape24.mirror = true; setRotation(Shape24, 0F, 1.134464F, 0F); Shape25 = new ModelRenderer(this, 15, 20); Shape25.addBox(0F, 0F, 0F, 6, 1, 1); Shape25.setRotationPoint(-20F, 5F, 6F); Shape25.setTextureSize(128, 128); Shape25.mirror = true; setRotation(Shape25, 0F, -1.047198F, 0F); Shape28 = new ModelRenderer(this, 15, 19); Shape28.addBox(0F, 0F, 0F, 6, 1, 1); Shape28.setRotationPoint(-20F, -10F, 6F); Shape28.setTextureSize(128, 128); Shape28.mirror = true; setRotation(Shape28, 0F, -1.047198F, 0F); Shape29 = new ModelRenderer(this, 15, 19); Shape29.addBox(0F, 0F, 0F, 6, 1, 1); Shape29.setRotationPoint(-21F, -10F, 6F); Shape29.setTextureSize(128, 128); Shape29.mirror = true; setRotation(Shape29, 0F, 1.047198F, 0F); } @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { super.render(entity, f, f1, f2, f3, f4, f5); this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); Shape11.render(f5); Shape12.render(f5); Shape13.render(f5); Shape14.render(f5); Shape15.render(f5); Shape16.render(f5); Shape20.render(f5); Shape22.render(f5); Shape23.render(f5); Shape24.render(f5); Shape25.render(f5); Shape28.render(f5); Shape29.render(f5); } public void render(float f5) { Shape11.render(f5); Shape12.render(f5); Shape13.render(f5); Shape14.render(f5); Shape15.render(f5); Shape16.render(f5); Shape20.render(f5); Shape22.render(f5); Shape23.render(f5); Shape24.render(f5); Shape25.render(f5); Shape28.render(f5); Shape29.render(f5); } private void setRotation(ModelRenderer model, float x, float y, float z) { model.rotateAngleX = x; model.rotateAngleY = y; model.rotateAngleZ = z; } }
//给你一个整数数组 nums 。 // // 如果一组数字 (i,j) 满足 nums[i] == nums[j] 且 i < j ,就可以认为这是一组 好数对 。 // // 返回好数对的数目。 // // // // 示例 1: // // 输入:nums = [1,2,3,1,1,3] //输出:4 //解释:有 4 组好数对,分别是 (0,3), (0,4), (3,4), (2,5) ,下标从 0 开始 // // // 示例 2: // // 输入:nums = [1,1,1,1] //输出:6 //解释:数组中的每组数字都是好数对 // // 示例 3: // // 输入:nums = [1,2,3] //输出:0 // // // // // 提示: // // // 1 <= nums.length <= 100 // 1 <= nums[i] <= 100 // // Related Topics 数组 哈希表 数学 // 👍 46 👎 0 package com.db117.example.leetcode.solution15; /** * 1512.好数对的数目.number-of-good-pairs * * @author db117 * @since 2020-12-22 18:01:56 **/ public class Solution1512 { public static void main(String[] args) { Solution solution = new Solution1512().new Solution(); System.out.println(solution.numIdenticalPairs(new int[]{ 1, 2, 3 })); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int numIdenticalPairs(int[] nums) { int[] temp = new int[101]; // 统计出现的次数 for (int num : nums) { temp[num]++; } int ans = 0; for (int i : temp) { if (i > 1) { // 有多个额算组合数 ans += helper(i - 1); } } return ans; } // 1+2+...n private int helper(int n) { if (n % 2 == 0) { return (1 + n) * (n / 2); } return helper(n - 1) + n; } } //leetcode submit region end(Prohibit modification and deletion) }
package org.robolectric.internal.bytecode; import static org.objectweb.asm.Type.ARRAY; import static org.objectweb.asm.Type.OBJECT; import static org.objectweb.asm.Type.VOID; import java.util.ListIterator; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.commons.Method; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.TypeInsnNode; public class OldClassInstrumentor extends ClassInstrumentor { private static final Type PLAN_TYPE = Type.getType(ClassHandler.Plan.class); static final Type THROWABLE_TYPE = Type.getType(Throwable.class); static final Type ROBOLECTRIC_INTERNALS_TYPE = Type.getType(RobolectricInternals.class); private static final Method INITIALIZING_METHOD = new Method("initializing", "(Ljava/lang/Object;)Ljava/lang/Object;"); private static final Method METHOD_INVOKED_METHOD = new Method( "methodInvoked", "(Ljava/lang/String;ZLjava/lang/Class;)L" + PLAN_TYPE.getInternalName() + ";"); private static final Method PLAN_RUN_METHOD = new Method("run", OBJECT_TYPE, new Type[] {OBJECT_TYPE, Type.getType(Object[].class)}); static final Method HANDLE_EXCEPTION_METHOD = new Method("cleanStackTrace", THROWABLE_TYPE, new Type[] {THROWABLE_TYPE}); private static final String DIRECT_OBJECT_MARKER_TYPE_DESC = Type.getObjectType(DirectObjectMarker.class.getName().replace('.', '/')).getDescriptor(); public OldClassInstrumentor(ClassInstrumentor.Decorator decorator) { super(decorator); } /** * Generates code like this: * * <pre> * public ThisClass(DirectObjectMarker dom, ThisClass domInstance) { * super(dom, domInstance); * __robo_data__ = domInstance; * } * </pre> */ @Override protected void addDirectCallConstructor(MutableClass mutableClass) { MethodNode directCallConstructor = new MethodNode( Opcodes.ACC_PUBLIC, "<init>", "(" + DIRECT_OBJECT_MARKER_TYPE_DESC + mutableClass.classType.getDescriptor() + ")V", null, null); RobolectricGeneratorAdapter generator = new RobolectricGeneratorAdapter(directCallConstructor); generator.loadThis(); String superName = mutableClass.classNode.superName; if (superName.equals("java/lang/Object")) { generator.visitMethodInsn(Opcodes.INVOKESPECIAL, superName, "<init>", "()V", false); } else { generator.loadArgs(); generator.visitMethodInsn( Opcodes.INVOKESPECIAL, superName, "<init>", "(" + DIRECT_OBJECT_MARKER_TYPE_DESC + "L" + superName + ";)V", false); } generator.loadThis(); generator.loadArg(1); generator.putField( mutableClass.classType, ShadowConstants.CLASS_HANDLER_DATA_FIELD_NAME, OBJECT_TYPE); generator.returnValue(); mutableClass.addMethod(directCallConstructor); } @Override protected void writeCallToInitializing( MutableClass mutableClass, RobolectricGeneratorAdapter generator) { generator.invokeStatic(ROBOLECTRIC_INTERNALS_TYPE, INITIALIZING_METHOD); } @Override protected void generateClassHandlerCall( MutableClass mutableClass, MethodNode originalMethod, String originalMethodName, RobolectricGeneratorAdapter generator) { generateCallToClassHandler(mutableClass, originalMethod, originalMethodName, generator); } /** * Generates code like this: * * <pre> * // decorator-specific code... * * Plan plan = RobolectricInternals.methodInvoked( * "pkg/ThisClass/thisMethod(Ljava/lang/String;Z)V", isStatic, ThisClass.class); * if (plan != null) { * try { * return plan.run(this, args); * } catch (Throwable t) { * throw RobolectricInternals.cleanStackTrace(t); * } * } else { * return $$robo$$thisMethod(*args); * } * </pre> */ private void generateCallToClassHandler( MutableClass mutableClass, MethodNode originalMethod, String originalMethodName, RobolectricGeneratorAdapter generator) { decorator.decorateMethodPreClassHandler( mutableClass, originalMethod, originalMethodName, generator); int planLocalVar = generator.newLocal(PLAN_TYPE); int exceptionLocalVar = generator.newLocal(THROWABLE_TYPE); Label directCall = new Label(); Label doReturn = new Label(); // prepare for call to classHandler.methodInvoked(String signature, boolean isStatic) generator.push( mutableClass.classType.getInternalName() + "/" + originalMethodName + originalMethod.desc); generator.push(generator.isStatic()); generator.push(mutableClass.classType); // my class generator.invokeStatic(ROBOLECTRIC_INTERNALS_TYPE, METHOD_INVOKED_METHOD); generator.storeLocal(planLocalVar); generator.loadLocal(planLocalVar); // plan generator.ifNull(directCall); // prepare for call to plan.run(Object instance, Object[] params) TryCatch tryCatchForHandler = generator.tryStart(THROWABLE_TYPE); generator.loadLocal(planLocalVar); // plan generator.loadThisOrNull(); // instance generator.loadArgArray(); // params generator.invokeInterface(PLAN_TYPE, PLAN_RUN_METHOD); Type returnType = generator.getReturnType(); int sort = returnType.getSort(); switch (sort) { case VOID: generator.pop(); break; case OBJECT: /* falls through */ case ARRAY: generator.checkCast(returnType); break; default: int unboxLocalVar = generator.newLocal(OBJECT_TYPE); generator.storeLocal(unboxLocalVar); generator.loadLocal(unboxLocalVar); Label notNull = generator.newLabel(); Label afterward = generator.newLabel(); generator.ifNonNull(notNull); generator.pushDefaultReturnValueToStack(returnType); // return zero, false, whatever generator.goTo(afterward); generator.mark(notNull); generator.loadLocal(unboxLocalVar); generator.unbox(returnType); generator.mark(afterward); break; } tryCatchForHandler.end(); generator.goTo(doReturn); // catch(Throwable) tryCatchForHandler.handler(); generator.storeLocal(exceptionLocalVar); generator.loadLocal(exceptionLocalVar); generator.invokeStatic(ROBOLECTRIC_INTERNALS_TYPE, HANDLE_EXCEPTION_METHOD); generator.throwException(); if (!originalMethod.name.equals("<init>")) { generator.mark(directCall); TryCatch tryCatchForDirect = generator.tryStart(THROWABLE_TYPE); generator.invokeMethod( mutableClass.classType.getInternalName(), originalMethod.name, originalMethod.desc); tryCatchForDirect.end(); generator.returnValue(); // catch(Throwable) tryCatchForDirect.handler(); generator.storeLocal(exceptionLocalVar); generator.loadLocal(exceptionLocalVar); generator.invokeStatic(ROBOLECTRIC_INTERNALS_TYPE, HANDLE_EXCEPTION_METHOD); generator.throwException(); } generator.mark(doReturn); generator.returnValue(); } /** * Decides to call through the appropriate method to intercept the method with an INVOKEVIRTUAL * Opcode, depending if the invokedynamic bytecode instruction is available (Java 7+). */ @Override protected void interceptInvokeVirtualMethod( MutableClass mutableClass, ListIterator<AbstractInsnNode> instructions, MethodInsnNode targetMethod) { interceptInvokeVirtualMethodWithoutInvokeDynamic(mutableClass, instructions, targetMethod); } /** * Intercepts the method without using the invokedynamic bytecode instruction. Should be called * through interceptInvokeVirtualMethod, not directly. */ private void interceptInvokeVirtualMethodWithoutInvokeDynamic( MutableClass mutableClass, ListIterator<AbstractInsnNode> instructions, MethodInsnNode targetMethod) { boolean isStatic = targetMethod.getOpcode() == Opcodes.INVOKESTATIC; instructions.remove(); // remove the method invocation Type[] argumentTypes = Type.getArgumentTypes(targetMethod.desc); instructions.add(new LdcInsnNode(argumentTypes.length)); instructions.add(new TypeInsnNode(Opcodes.ANEWARRAY, "java/lang/Object")); // first, move any arguments into an Object[] in reverse order for (int i = argumentTypes.length - 1; i >= 0; i--) { Type type = argumentTypes[i]; int argWidth = type.getSize(); if (argWidth == 1) { // A B C [] instructions.add(new InsnNode(Opcodes.DUP_X1)); // A B [] C [] instructions.add(new InsnNode(Opcodes.SWAP)); // A B [] [] C instructions.add(new LdcInsnNode(i)); // A B [] [] C 2 instructions.add(new InsnNode(Opcodes.SWAP)); // A B [] [] 2 C box(type, instructions); // A B [] [] 2 (C) instructions.add(new InsnNode(Opcodes.AASTORE)); // A B [(C)] } else if (argWidth == 2) { // A B _C_ [] instructions.add(new InsnNode(Opcodes.DUP_X2)); // A B [] _C_ [] instructions.add(new InsnNode(Opcodes.DUP_X2)); // A B [] [] _C_ [] instructions.add(new InsnNode(Opcodes.POP)); // A B [] [] _C_ box(type, instructions); // A B [] [] (C) instructions.add(new LdcInsnNode(i)); // A B [] [] (C) 2 instructions.add(new InsnNode(Opcodes.SWAP)); // A B [] [] 2 (C) instructions.add(new InsnNode(Opcodes.AASTORE)); // A B [(C)] } } if (isStatic) { // [] instructions.add(new InsnNode(Opcodes.ACONST_NULL)); // [] null instructions.add(new InsnNode(Opcodes.SWAP)); // null [] } // instance [] instructions.add( new LdcInsnNode( targetMethod.owner + "/" + targetMethod.name + targetMethod.desc)); // target method signature // instance [] signature instructions.add(new InsnNode(Opcodes.DUP_X2)); // signature instance [] signature instructions.add(new InsnNode(Opcodes.POP)); // signature instance [] instructions.add(new LdcInsnNode(mutableClass.classType)); // signature instance [] class instructions.add( new MethodInsnNode( Opcodes.INVOKESTATIC, Type.getType(RobolectricInternals.class).getInternalName(), "intercept", "(Ljava/lang/String;Ljava/lang/Object;[Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;", false)); final Type returnType = Type.getReturnType(targetMethod.desc); switch (returnType.getSort()) { case ARRAY: /* falls through */ case OBJECT: String remappedType = mutableClass.config.mappedTypeName(returnType.getInternalName()); instructions.add(new TypeInsnNode(Opcodes.CHECKCAST, remappedType)); break; case VOID: instructions.add(new InsnNode(Opcodes.POP)); break; case Type.LONG: instructions.add(new TypeInsnNode(Opcodes.CHECKCAST, Type.getInternalName(Long.class))); instructions.add( new MethodInsnNode( Opcodes.INVOKEVIRTUAL, Type.getInternalName(Long.class), "longValue", Type.getMethodDescriptor(Type.LONG_TYPE), false)); break; case Type.FLOAT: instructions.add(new TypeInsnNode(Opcodes.CHECKCAST, Type.getInternalName(Float.class))); instructions.add( new MethodInsnNode( Opcodes.INVOKEVIRTUAL, Type.getInternalName(Float.class), "floatValue", Type.getMethodDescriptor(Type.FLOAT_TYPE), false)); break; case Type.DOUBLE: instructions.add(new TypeInsnNode(Opcodes.CHECKCAST, Type.getInternalName(Double.class))); instructions.add( new MethodInsnNode( Opcodes.INVOKEVIRTUAL, Type.getInternalName(Double.class), "doubleValue", Type.getMethodDescriptor(Type.DOUBLE_TYPE), false)); break; case Type.BOOLEAN: instructions.add(new TypeInsnNode(Opcodes.CHECKCAST, Type.getInternalName(Boolean.class))); instructions.add( new MethodInsnNode( Opcodes.INVOKEVIRTUAL, Type.getInternalName(Boolean.class), "booleanValue", Type.getMethodDescriptor(Type.BOOLEAN_TYPE), false)); break; case Type.INT: instructions.add(new TypeInsnNode(Opcodes.CHECKCAST, Type.getInternalName(Integer.class))); instructions.add( new MethodInsnNode( Opcodes.INVOKEVIRTUAL, Type.getInternalName(Integer.class), "intValue", Type.getMethodDescriptor(Type.INT_TYPE), false)); break; case Type.SHORT: instructions.add(new TypeInsnNode(Opcodes.CHECKCAST, Type.getInternalName(Short.class))); instructions.add( new MethodInsnNode( Opcodes.INVOKEVIRTUAL, Type.getInternalName(Short.class), "shortValue", Type.getMethodDescriptor(Type.SHORT_TYPE), false)); break; case Type.BYTE: instructions.add(new TypeInsnNode(Opcodes.CHECKCAST, Type.getInternalName(Byte.class))); instructions.add( new MethodInsnNode( Opcodes.INVOKEVIRTUAL, Type.getInternalName(Byte.class), "byteValue", Type.getMethodDescriptor(Type.BYTE_TYPE), false)); break; default: throw new RuntimeException( "Not implemented: " + getClass().getName() + " cannot intercept methods with return type " + returnType.getClassName()); } } static void box(final Type type, ListIterator<AbstractInsnNode> instructions) { if (type.getSort() == OBJECT || type.getSort() == ARRAY) { return; } if (Type.VOID_TYPE.equals(type)) { instructions.add(new InsnNode(Opcodes.ACONST_NULL)); } else { Type boxed = getBoxedType(type); instructions.add(new TypeInsnNode(Opcodes.NEW, boxed.getInternalName())); if (type.getSize() == 2) { // Pp -> Ppo -> oPpo -> ooPpo -> ooPp -> o instructions.add(new InsnNode(Opcodes.DUP_X2)); instructions.add(new InsnNode(Opcodes.DUP_X2)); instructions.add(new InsnNode(Opcodes.POP)); } else { // p -> po -> opo -> oop -> o instructions.add(new InsnNode(Opcodes.DUP_X1)); instructions.add(new InsnNode(Opcodes.SWAP)); } instructions.add( new MethodInsnNode( Opcodes.INVOKESPECIAL, boxed.getInternalName(), "<init>", "(" + type.getDescriptor() + ")V", false)); } } private static Type getBoxedType(final Type type) { switch (type.getSort()) { case Type.BYTE: return Type.getObjectType("java/lang/Byte"); case Type.BOOLEAN: return Type.getObjectType("java/lang/Boolean"); case Type.SHORT: return Type.getObjectType("java/lang/Short"); case Type.CHAR: return Type.getObjectType("java/lang/Character"); case Type.INT: return Type.getObjectType("java/lang/Integer"); case Type.FLOAT: return Type.getObjectType("java/lang/Float"); case Type.LONG: return Type.getObjectType("java/lang/Long"); case Type.DOUBLE: return Type.getObjectType("java/lang/Double"); default: // no boxing required return type; } } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator.aggregation; import com.facebook.presto.common.type.Type; import io.airlift.slice.Slices; import java.util.concurrent.ThreadLocalRandom; import static com.facebook.presto.common.type.DoubleType.DOUBLE; import static com.facebook.presto.sql.analyzer.TypeSignatureProvider.fromTypes; import static com.facebook.presto.type.IpAddressType.IPADDRESS; public class TestApproximateCountDistinctIpAddress extends AbstractTestApproximateCountDistinct { @Override public InternalAggregationFunction getAggregationFunction() { return functionManager.getAggregateFunctionImplementation( functionManager.lookupFunction("approx_distinct", fromTypes(IPADDRESS, DOUBLE))); } @Override public Type getValueType() { return IPADDRESS; } @Override public Object randomValue() { byte[] bytes = new byte[16]; ThreadLocalRandom.current().nextBytes(bytes); return Slices.wrappedBuffer(bytes); } }
/* * MIT License * * Copyright (c) 2017 * * 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.kenticocloud.delivery; import org.apache.http.*; import org.apache.http.entity.InputStreamEntity; import org.apache.http.localserver.LocalServerTestBase; import org.junit.Assert; import org.junit.Test; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.List; public class DocsExamplesTest extends LocalServerTestBase { @Test public void testRetrievingContentInSpecificLanguage() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "items/on_roasts"), (request, response, context) -> response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("DocsExamplesRetrievingContentInSpecificLanguage.json") ) )); HttpHost httpHost = this.start(); DeliveryClient client = new DeliveryClient(projectId); //modify default baseurl to point to test server, this is private so using reflection String testServerUri = httpHost.toURI() + "/%s"; Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions"); deliveryOptionsField.setAccessible(true); ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri); List<NameValuePair> params = DeliveryParameterBuilder.params().language("es-ES").build(); ArticleItem item = client.getItem("on_roasts", ArticleItem.class, params); Assert.assertNotNull(item); } @Test public void testListContentItems() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "items"), (request, response, context) -> response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("DocsExamplesListContentItems.json") ) )); HttpHost httpHost = this.start(); DeliveryClient client = new DeliveryClient(projectId); //modify default baseurl to point to test server, this is private so using reflection String testServerUri = httpHost.toURI() + "/%s"; Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions"); deliveryOptionsField.setAccessible(true); ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri); List<NameValuePair> params = DeliveryParameterBuilder.params() .filterEquals("system.type", "article") .projection("title", "summary", "post_date", "teaser_image") .filterContains("elements.personas", "coffee_lover") .orderByDesc("elements.post_date") .modularContentDepth(0) .page(null, 3) .build(); List<ArticleItem> items = client.getItems(ArticleItem.class); Assert.assertNotNull(items); } @Test public void testViewContentItem() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "items/on_roasts"), (request, response, context) -> response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleContentItem.json") ) )); HttpHost httpHost = this.start(); DeliveryClient client = new DeliveryClient(projectId); //modify default baseurl to point to test server, this is private so using reflection String testServerUri = httpHost.toURI() + "/%s"; Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions"); deliveryOptionsField.setAccessible(true); ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri); List<NameValuePair> params = DeliveryParameterBuilder.params().projection("title", "summary", "post_date", "teaser_image", "related_articles").build(); ArticleItem item = client.getItem("on_roasts", ArticleItem.class, params); Assert.assertNotNull(item); } @Test public void testListContentTypes() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "types"), (request, response, context) -> response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleContentTypeList.json") ) )); HttpHost httpHost = this.start(); DeliveryClient client = new DeliveryClient(projectId); //modify default baseurl to point to test server, this is private so using reflection String testServerUri = httpHost.toURI() + "/%s"; Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions"); deliveryOptionsField.setAccessible(true); ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri); List<NameValuePair> params = DeliveryParameterBuilder.params().page(null, 3).build(); ContentTypesListingResponse types = client.getTypes(params); Assert.assertNotNull(types); } @Test public void testViewContentType() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "types/coffee"), (request, response, context) -> response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleContentType.json") ) )); HttpHost httpHost = this.start(); DeliveryClient client = new DeliveryClient(projectId); //modify default baseurl to point to test server, this is private so using reflection String testServerUri = httpHost.toURI() + "/%s"; Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions"); deliveryOptionsField.setAccessible(true); ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri); ContentType type = client.getType("coffee"); Assert.assertNotNull(type); } @Test public void testViewContentTypeElement() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "types/coffee/elements/processing"), (request, response, context) -> response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleContentTypeElementResponse.json") ) )); HttpHost httpHost = this.start(); DeliveryClient client = new DeliveryClient(projectId); //modify default baseurl to point to test server, this is private so using reflection String testServerUri = httpHost.toURI() + "/%s"; Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions"); deliveryOptionsField.setAccessible(true); ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri); Element element = client.getContentTypeElement("coffee", "processing"); Assert.assertNotNull(element); Assert.assertEquals("processing", element.getCodeName()); Assert.assertTrue(element instanceof MultipleChoiceElement); } @Test public void testListTaxonomyGroups() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "taxonomies"), (request, response, context) -> response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleTaxonomyGroupListingResponse.json") ) )); HttpHost httpHost = this.start(); DeliveryClient client = new DeliveryClient(projectId); //modify default baseurl to point to test server, this is private so using reflection String testServerUri = httpHost.toURI() + "/%s"; Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions"); deliveryOptionsField.setAccessible(true); ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri); List<NameValuePair> params = DeliveryParameterBuilder.params().page(null, 3).build(); TaxonomyGroupListingResponse response = client.getTaxonomyGroups(params); Assert.assertNotNull(response); Assert.assertEquals(3, response.taxonomies.size()); } @Test public void testViewTaxonomyGroup() throws Exception { String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c"; this.serverBootstrap.registerHandler( String.format("/%s/%s", projectId, "taxonomies/personas"), (request, response, context) -> response.setEntity( new InputStreamEntity( this.getClass().getResourceAsStream("SampleTaxonomyGroup.json") ) )); HttpHost httpHost = this.start(); DeliveryClient client = new DeliveryClient(projectId); //modify default baseurl to point to test server, this is private so using reflection String testServerUri = httpHost.toURI() + "/%s"; Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions"); deliveryOptionsField.setAccessible(true); ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri); TaxonomyGroup taxonomyGroup = client.getTaxonomyGroup("personas"); Assert.assertNotNull(taxonomyGroup); } @Test public void testNotificationSignatures() throws Exception { String message = "The quick brown fox jumps over the lazy dog."; String secret = "3mlfw0i7LGSI+/n/cFd3I9cnLLr4e0ttUzKxwMqZTVU="; String expectedBase64EncodedHmac = "Nog+y3tWzKYVNWTj6UNnf50tdMqrCQ9LxdLyxibn7Lw="; String actualHmac = generateHash(message, secret); Assert.assertEquals(expectedBase64EncodedHmac, actualHmac); } public static String generateHash(String message, String secret) throws Exception { Mac sha256Hmac = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); sha256Hmac.init(secretKeySpec); return Base64.getEncoder().encodeToString(sha256Hmac.doFinal(message.getBytes(StandardCharsets.UTF_8))); } }