text
stringlengths
7
1.01M
/* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans; import org.springframework.core.ResolvableType; import org.springframework.core.convert.Property; import org.springframework.core.convert.TypeDescriptor; import org.springframework.util.Assert; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.*; /** * Default {@link BeanWrapper} implementation that should be sufficient * for all typical use cases. Caches introspection results for efficiency. * <p> * <p>Note: Auto-registers default property editors from the * {@code org.springframework.beans.propertyeditors} package, which apply * in addition to the JDK's standard PropertyEditors. Applications can call * the {@link #registerCustomEditor(Class, java.beans.PropertyEditor)} method * to register an editor for a particular instance (i.e. they are not shared * across the application). See the base class * {@link PropertyEditorRegistrySupport} for details. * <p> * <p><b>NOTE: As of Spring 2.5, this is - for almost all purposes - an * internal class.</b> It is just public in order to allow for access from * other framework packages. For standard application access purposes, use the * {@link PropertyAccessorFactory#forBeanPropertyAccess} factory method instead. * * @author Rod Johnson * @author Juergen Hoeller * @author Rob Harrop * @author Stephane Nicoll * @see #registerCustomEditor * @see #setPropertyValues * @see #setPropertyValue * @see #getPropertyValue * @see #getPropertyType * @see BeanWrapper * @see PropertyEditorRegistrySupport * @since 15 April 2001 */ //可以根据需求,将集合与数组的值转换到对应目标对象的集合和数组. //自定义的属性编辑器通过属性编辑器的setValue,setAsText方法实现上述的转换功能。 public class BeanWrapperImpl extends AbstractNestablePropertyAccessor implements BeanWrapper { /** * Cached introspections results for this object, to prevent encountering * the cost of JavaBeans introspection every time. */ private CachedIntrospectionResults cachedIntrospectionResults; /** * The security context used for invoking the property methods */ private AccessControlContext acc; /** * Create new empty BeanWrapperImpl. Wrapped instance needs to be set afterwards. * Registers default editors. * * @see #setWrappedInstance */ public BeanWrapperImpl() { this(true); } /** * Create new empty BeanWrapperImpl. Wrapped instance needs to be set afterwards. * * @param registerDefaultEditors whether to register default editors * (can be suppressed if the BeanWrapper won't need any type conversion) * @see #setWrappedInstance */ public BeanWrapperImpl(boolean registerDefaultEditors) { super(registerDefaultEditors); } /** * Create new BeanWrapperImpl for the given object. * * @param object object wrapped by this BeanWrapper */ public BeanWrapperImpl(Object object) { super(object); } /** * Create new BeanWrapperImpl, wrapping a new instance of the specified class. * * @param clazz class to instantiate and wrap */ public BeanWrapperImpl(Class<?> clazz) { super(clazz); } /** * Create new BeanWrapperImpl for the given object, * registering a nested path that the object is in. * * @param object object wrapped by this BeanWrapper * @param nestedPath the nested path of the object * @param rootObject the root object at the top of the path */ public BeanWrapperImpl(Object object, String nestedPath, Object rootObject) { super(object, nestedPath, rootObject); } /** * Create new BeanWrapperImpl for the given object, * registering a nested path that the object is in. * * @param object object wrapped by this BeanWrapper * @param nestedPath the nested path of the object * @param superBw the containing BeanWrapper (must not be {@code null}) */ private BeanWrapperImpl(Object object, String nestedPath, BeanWrapperImpl superBw) { super(object, nestedPath, superBw); setSecurityContext(superBw.acc); } @Override public void setWrappedInstance(Object object, String nestedPath, Object rootObject) { super.setWrappedInstance(object, nestedPath, rootObject); setIntrospectionClass(getWrappedInstance().getClass()); } /** * Set the security context used during the invocation of the wrapped instance methods. * Can be null. */ public void setSecurityContext(AccessControlContext acc) { this.acc = acc; } /** * Return the security context used during the invocation of the wrapped instance methods. * Can be null. */ public AccessControlContext getSecurityContext() { return this.acc; } /** * Set the class to introspect. * Needs to be called when the target object changes. * * @param clazz the class to introspect */ protected void setIntrospectionClass(Class<?> clazz) { if (this.cachedIntrospectionResults != null && !clazz.equals(this.cachedIntrospectionResults.getBeanClass())) { this.cachedIntrospectionResults = null; } } /** * Obtain a lazily initializted CachedIntrospectionResults instance * for the wrapped object. */ private CachedIntrospectionResults getCachedIntrospectionResults() { Assert.state(getWrappedInstance() != null, "BeanWrapper does not hold a bean instance"); if (this.cachedIntrospectionResults == null) { this.cachedIntrospectionResults = CachedIntrospectionResults.forClass(getWrappedClass()); } return this.cachedIntrospectionResults; } /** * Convert the given value for the specified property to the latter's type. * <p>This method is only intended for optimizations in a BeanFactory. * Use the {@code convertIfNecessary} methods for programmatic conversion. * * @param value the value to convert * @param propertyName the target property * (note that nested or indexed properties are not supported here) * @return the new value, possibly the result of type conversion * @throws TypeMismatchException if type conversion failed */ public Object convertForProperty(Object value, String propertyName) throws TypeMismatchException { CachedIntrospectionResults cachedIntrospectionResults = getCachedIntrospectionResults(); PropertyDescriptor pd = cachedIntrospectionResults.getPropertyDescriptor(propertyName); if (pd == null) { throw new InvalidPropertyException(getRootClass(), getNestedPath() + propertyName, "No property '" + propertyName + "' found"); } TypeDescriptor td = cachedIntrospectionResults.getTypeDescriptor(pd); if (td == null) { td = cachedIntrospectionResults.addTypeDescriptor(pd, new TypeDescriptor(property(pd))); } return convertForProperty(propertyName, null, value, td); } private Property property(PropertyDescriptor pd) { GenericTypeAwarePropertyDescriptor typeAware = (GenericTypeAwarePropertyDescriptor) pd; return new Property(typeAware.getBeanClass(), typeAware.getReadMethod(), typeAware.getWriteMethod(), typeAware.getName()); } @Override protected BeanPropertyHandler getLocalPropertyHandler(String propertyName) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(propertyName); if (pd != null) { return new BeanPropertyHandler(pd); } return null; } @Override protected BeanWrapperImpl newNestedPropertyAccessor(Object object, String nestedPath) { return new BeanWrapperImpl(object, nestedPath, this); } @Override protected NotWritablePropertyException createNotWritablePropertyException(String propertyName) { PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass()); throw new NotWritablePropertyException( getRootClass(), getNestedPath() + propertyName, matches.buildErrorMessage(), matches.getPossibleMatches()); } @Override public PropertyDescriptor[] getPropertyDescriptors() { return getCachedIntrospectionResults().getPropertyDescriptors(); } @Override public PropertyDescriptor getPropertyDescriptor(String propertyName) throws InvalidPropertyException { BeanPropertyHandler propertyHandler = getLocalPropertyHandler(propertyName); if (propertyHandler == null) { throw new InvalidPropertyException(getRootClass(), getNestedPath() + propertyName, "No property '" + propertyName + "' found"); } return propertyHandler.pd; } private class BeanPropertyHandler extends PropertyHandler { private final PropertyDescriptor pd; public BeanPropertyHandler(PropertyDescriptor pd) { super(pd.getPropertyType(), pd.getReadMethod() != null, pd.getWriteMethod() != null); this.pd = pd; } @Override public ResolvableType getResolvableType() { return ResolvableType.forMethodReturnType(this.pd.getReadMethod()); } @Override public TypeDescriptor toTypeDescriptor() { return new TypeDescriptor(property(this.pd)); } @Override public TypeDescriptor nested(int level) { return TypeDescriptor.nested(property(pd), level); } @Override public Object getValue() throws Exception { final Method readMethod = this.pd.getReadMethod(); if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { readMethod.setAccessible(true); return null; } }); } else { readMethod.setAccessible(true); } } if (System.getSecurityManager() != null) { try { return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { return readMethod.invoke(getWrappedInstance(), (Object[]) null); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { return readMethod.invoke(getWrappedInstance(), (Object[]) null); } } //使用反射为属性设置解析后的属性值 /** * 反射 */ @Override public void setValue(final Object object, Object valueToApply) throws Exception { final Method writeMethod = (this.pd instanceof GenericTypeAwarePropertyDescriptor ? ((GenericTypeAwarePropertyDescriptor) this.pd).getWriteMethodForActualAccess() : this.pd.getWriteMethod()); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { writeMethod.setAccessible(true); return null; } }); } else { writeMethod.setAccessible(true); } } final Object value = valueToApply; if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { writeMethod.invoke(object, value); return null; } }, acc); } catch (PrivilegedActionException ex) { throw ex.getException(); } } else { writeMethod.invoke(getWrappedInstance(), value); } } } }
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terracotta.dynamic_config.server.api; /** * @author Mathieu Carbou */ @FunctionalInterface public interface EventRegistration { /** * Unregister a listener */ void unregister(); }
// Copyright 2008 Google Inc. All Rights Reserved. package org.clearsilver.jni; import org.clearsilver.ClearsilverFactory; import org.clearsilver.CsTest; /** * Unittests specifically for JniCs * * @author Sergio Marti (smarti@google.com) */ public class JniCsTest extends CsTest { @Override protected ClearsilverFactory newClearsilverFactory() { return new JniClearsilverFactory(); } }
package org.jetbrains.plugins.scala.lang.formatting.settings; import com.intellij.application.options.codeStyle.CommenterForm; import com.intellij.openapi.util.Disposer; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.scala.ScalaLanguage; import javax.swing.*; import java.awt.*; /** * User: Dmitry.Naydanov * Date: 09.07.14. */ public final class OtherCodeStylePanel extends ScalaCodeStylePanelBase { private JCheckBox enforceFunctionalSyntaxForCheckBox; private JPanel contentPanel; private JCheckBox replaceWithUnicodeSymbolCheckBox; private JCheckBox replaceWithUnicodeSymbolCheckBox1; private JCheckBox replaceInForGeneratorCheckBox; private JCheckBox replaceLambdaWithGreekLetter; private JCheckBox alternateIndentationForParamsCheckBox; private JSpinner alternateIndentationForParamsSpinner; private JPanel alternateParamIndentPanel; private JLabel spacesLabel; private JPanel myCommenterPanel; private JCheckBox reformatOnCompileCheckBox; private CommenterForm myCommenterForm = new CommenterForm(ScalaLanguage.INSTANCE); private TrailingCommaPanel trailingCommaPanel = new TrailingCommaPanel(getSettings()); private JPanel trailingCommaInnerPanel; protected OtherCodeStylePanel(@NotNull CodeStyleSettings settings) { super(settings); $$$setupUI$$$(); alternateIndentationForParamsSpinner.setModel(new SpinnerNumberModel(4, 1, null, 1)); resetImpl(settings); } @Override public void dispose() { super.dispose(); Disposer.dispose(trailingCommaPanel); } @Override public void apply(CodeStyleSettings settings) { if (!isModified(settings)) return; ScalaCodeStyleSettings scalaCodeStyleSettings = settings.getCustomSettings(ScalaCodeStyleSettings.class); scalaCodeStyleSettings.ENFORCE_FUNCTIONAL_SYNTAX_FOR_UNIT = enforceFunctionalSyntaxForCheckBox.isSelected(); scalaCodeStyleSettings.REPLACE_CASE_ARROW_WITH_UNICODE_CHAR = replaceWithUnicodeSymbolCheckBox.isSelected(); scalaCodeStyleSettings.REPLACE_MAP_ARROW_WITH_UNICODE_CHAR = replaceWithUnicodeSymbolCheckBox1.isSelected(); scalaCodeStyleSettings.REPLACE_FOR_GENERATOR_ARROW_WITH_UNICODE_CHAR = replaceInForGeneratorCheckBox.isSelected(); scalaCodeStyleSettings.REPLACE_LAMBDA_WITH_GREEK_LETTER = replaceLambdaWithGreekLetter.isSelected(); scalaCodeStyleSettings.USE_ALTERNATE_CONTINUATION_INDENT_FOR_PARAMS = alternateIndentationForParamsCheckBox.isSelected(); scalaCodeStyleSettings.ALTERNATE_CONTINUATION_INDENT_FOR_PARAMS = (Integer) alternateIndentationForParamsSpinner.getValue(); scalaCodeStyleSettings.REFORMAT_ON_COMPILE = reformatOnCompileCheckBox.isSelected(); myCommenterForm.apply(settings); trailingCommaPanel.apply(settings); } @Override public boolean isModified(CodeStyleSettings settings) { ScalaCodeStyleSettings ss = settings.getCustomSettings(ScalaCodeStyleSettings.class); if (ss.ENFORCE_FUNCTIONAL_SYNTAX_FOR_UNIT != enforceFunctionalSyntaxForCheckBox.isSelected()) return true; if (ss.REPLACE_CASE_ARROW_WITH_UNICODE_CHAR != replaceWithUnicodeSymbolCheckBox.isSelected()) return true; if (ss.REPLACE_MAP_ARROW_WITH_UNICODE_CHAR != replaceWithUnicodeSymbolCheckBox1.isSelected()) return true; if (ss.REPLACE_FOR_GENERATOR_ARROW_WITH_UNICODE_CHAR != replaceInForGeneratorCheckBox.isSelected()) return true; if (ss.REPLACE_LAMBDA_WITH_GREEK_LETTER != replaceLambdaWithGreekLetter.isSelected()) return true; if (ss.USE_ALTERNATE_CONTINUATION_INDENT_FOR_PARAMS != alternateIndentationForParamsCheckBox.isSelected()) return true; if (ss.ALTERNATE_CONTINUATION_INDENT_FOR_PARAMS != (Integer) alternateIndentationForParamsSpinner.getValue()) return true; if (ss.REFORMAT_ON_COMPILE != reformatOnCompileCheckBox.isSelected()) return true; return (myCommenterForm.isModified(settings) || trailingCommaPanel.isModified(settings)); } @Nullable @Override public JComponent getPanel() { return contentPanel; } @Override protected void resetImpl(CodeStyleSettings settings) { ScalaCodeStyleSettings scalaCodeStyleSettings = settings.getCustomSettings(ScalaCodeStyleSettings.class); enforceFunctionalSyntaxForCheckBox.setSelected(scalaCodeStyleSettings.ENFORCE_FUNCTIONAL_SYNTAX_FOR_UNIT); replaceWithUnicodeSymbolCheckBox.setSelected(scalaCodeStyleSettings.REPLACE_CASE_ARROW_WITH_UNICODE_CHAR); replaceWithUnicodeSymbolCheckBox1.setSelected(scalaCodeStyleSettings.REPLACE_MAP_ARROW_WITH_UNICODE_CHAR); replaceInForGeneratorCheckBox.setSelected(scalaCodeStyleSettings.REPLACE_FOR_GENERATOR_ARROW_WITH_UNICODE_CHAR); replaceLambdaWithGreekLetter.setSelected(scalaCodeStyleSettings.REPLACE_LAMBDA_WITH_GREEK_LETTER); alternateIndentationForParamsCheckBox.setSelected(scalaCodeStyleSettings.USE_ALTERNATE_CONTINUATION_INDENT_FOR_PARAMS); alternateIndentationForParamsSpinner.setValue(scalaCodeStyleSettings.ALTERNATE_CONTINUATION_INDENT_FOR_PARAMS); reformatOnCompileCheckBox.setSelected(scalaCodeStyleSettings.REFORMAT_ON_COMPILE); myCommenterForm.reset(settings); trailingCommaPanel.resetImpl(settings); } private void createUIComponents() { myCommenterPanel = myCommenterForm.getCommenterPanel(); trailingCommaInnerPanel = trailingCommaPanel.getPanel(); } public void toggleExternalFormatter(boolean useExternalFormatter) { alternateIndentationForParamsCheckBox.setVisible(!useExternalFormatter); alternateIndentationForParamsSpinner.setVisible(!useExternalFormatter); spacesLabel.setVisible(!useExternalFormatter); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { createUIComponents(); final JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1)); contentPanel = new JPanel(); contentPanel.setLayout(new GridLayoutManager(11, 2, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(contentPanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); contentPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10), null)); enforceFunctionalSyntaxForCheckBox = new JCheckBox(); enforceFunctionalSyntaxForCheckBox.setText("Enforce functional syntax for methods with Unit return type"); contentPanel.add(enforceFunctionalSyntaxForCheckBox, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer1 = new Spacer(); contentPanel.add(spacer1, new GridConstraints(10, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); replaceWithUnicodeSymbolCheckBox = new JCheckBox(); replaceWithUnicodeSymbolCheckBox.setText("Replace '=>' with unicode symbol"); contentPanel.add(replaceWithUnicodeSymbolCheckBox, new GridConstraints(2, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); replaceWithUnicodeSymbolCheckBox1 = new JCheckBox(); replaceWithUnicodeSymbolCheckBox1.setText("Replace '->' with unicode symbol"); contentPanel.add(replaceWithUnicodeSymbolCheckBox1, new GridConstraints(3, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); replaceInForGeneratorCheckBox = new JCheckBox(); replaceInForGeneratorCheckBox.setText("Replace '<-' in \"for\" generator with unicode symbol"); contentPanel.add(replaceInForGeneratorCheckBox, new GridConstraints(4, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); replaceLambdaWithGreekLetter = new JCheckBox(); replaceLambdaWithGreekLetter.setSelected(false); replaceLambdaWithGreekLetter.setText("Kind Projector: Replace 'Lambda' with unicode symbol"); contentPanel.add(replaceLambdaWithGreekLetter, new GridConstraints(5, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); alternateParamIndentPanel = new JPanel(); alternateParamIndentPanel.setLayout(new GridLayoutManager(1, 4, new Insets(0, 0, 0, 0), -1, -1)); contentPanel.add(alternateParamIndentPanel, new GridConstraints(6, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); alternateIndentationForParamsCheckBox = new JCheckBox(); alternateIndentationForParamsCheckBox.setText("Alternate indentation for constructor args and parameter declarations:"); alternateIndentationForParamsCheckBox.setVerticalAlignment(1); alternateParamIndentPanel.add(alternateIndentationForParamsCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); alternateIndentationForParamsSpinner = new JSpinner(); alternateParamIndentPanel.add(alternateIndentationForParamsSpinner, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, new Dimension(1, -1), new Dimension(2, -1), null, 1, false)); spacesLabel = new JLabel(); spacesLabel.setText("spaces"); spacesLabel.setVerticalAlignment(1); alternateParamIndentPanel.add(spacesLabel, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer2 = new Spacer(); alternateParamIndentPanel.add(spacer2, new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); contentPanel.add(myCommenterPanel, new GridConstraints(7, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); reformatOnCompileCheckBox = new JCheckBox(); reformatOnCompileCheckBox.setText("Reformat on compile"); contentPanel.add(reformatOnCompileCheckBox, new GridConstraints(1, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); contentPanel.add(trailingCommaInnerPanel, new GridConstraints(8, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); } }
/* * Copyright 2018 JDCLOUD.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. * * Transcode * 视频转码任务相关接口 * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ package com.jdcloud.sdk.service.vod.model; import java.util.List; import java.util.ArrayList; import com.jdcloud.sdk.service.vod.model.SubmittedTranscodeTask; import com.jdcloud.sdk.service.JdcloudResult; /** * 批量提交转码作业 */ public class BatchSubmitTranscodeJobsResult extends JdcloudResult implements java.io.Serializable { private static final long serialVersionUID = 1L; /** * tasks */ private List<SubmittedTranscodeTask> tasks; /** * get tasks * * @return */ public List<SubmittedTranscodeTask> getTasks() { return tasks; } /** * set tasks * * @param tasks */ public void setTasks(List<SubmittedTranscodeTask> tasks) { this.tasks = tasks; } /** * set tasks * * @param tasks */ public BatchSubmitTranscodeJobsResult tasks(List<SubmittedTranscodeTask> tasks) { this.tasks = tasks; return this; } /** * add item to tasks * * @param task */ public void addTask(SubmittedTranscodeTask task) { if (this.tasks == null) { this.tasks = new ArrayList<>(); } this.tasks.add(task); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.skywalking.oap.server.core.analysis.generated.serviceinstancejvmgc; import java.util.*; import lombok.*; import org.apache.skywalking.oap.server.core.Const; import org.apache.skywalking.oap.server.core.alarm.*; import org.apache.skywalking.oap.server.core.analysis.indicator.*; import org.apache.skywalking.oap.server.core.analysis.indicator.annotation.IndicatorType; import org.apache.skywalking.oap.server.core.remote.annotation.StreamData; import org.apache.skywalking.oap.server.core.remote.grpc.proto.RemoteData; import org.apache.skywalking.oap.server.core.source.Scope; import org.apache.skywalking.oap.server.core.storage.StorageBuilder; import org.apache.skywalking.oap.server.core.storage.annotation.*; /** * This class is auto generated. Please don't change this class manually. * * @author Observability Analysis Language code generator */ @IndicatorType @StreamData @StorageEntity(name = "instance_jvm_old_gc_count", builder = InstanceJvmOldGcCountIndicator.Builder.class) public class InstanceJvmOldGcCountIndicator extends SumIndicator implements AlarmSupported { @Setter @Getter @Column(columnName = "entity_id") @IDColumn private String entityId; @Setter @Getter @Column(columnName = "service_instance_id") private int serviceInstanceId; @Override public String id() { String splitJointId = String.valueOf(getTimeBucket()); splitJointId += Const.ID_SPLIT + entityId; return splitJointId; } @Override public int hashCode() { int result = 17; result = 31 * result + entityId.hashCode(); result = 31 * result + (int)getTimeBucket(); return result; } @Override public int remoteHashCode() { int result = 17; result = 31 * result + entityId.hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; InstanceJvmOldGcCountIndicator indicator = (InstanceJvmOldGcCountIndicator)obj; if (entityId != indicator.entityId) return false; if (getTimeBucket() != indicator.getTimeBucket()) return false; return true; } @Override public RemoteData.Builder serialize() { RemoteData.Builder remoteBuilder = RemoteData.newBuilder(); remoteBuilder.setDataStrings(0, getEntityId()); remoteBuilder.setDataLongs(0, getValue()); remoteBuilder.setDataLongs(1, getTimeBucket()); remoteBuilder.setDataIntegers(0, getServiceInstanceId()); return remoteBuilder; } @Override public void deserialize(RemoteData remoteData) { setEntityId(remoteData.getDataStrings(0)); setValue(remoteData.getDataLongs(0)); setTimeBucket(remoteData.getDataLongs(1)); setServiceInstanceId(remoteData.getDataIntegers(0)); } @Override public AlarmMeta getAlarmMeta() { return new AlarmMeta("instance_jvm_old_gc_count", Scope.ServiceInstanceJVMGC, entityId); } @Override public Indicator toHour() { InstanceJvmOldGcCountIndicator indicator = new InstanceJvmOldGcCountIndicator(); indicator.setTimeBucket(toTimeBucketInHour()); indicator.setEntityId(this.getEntityId()); indicator.setServiceInstanceId(this.getServiceInstanceId()); indicator.setValue(this.getValue()); return indicator; } @Override public Indicator toDay() { InstanceJvmOldGcCountIndicator indicator = new InstanceJvmOldGcCountIndicator(); indicator.setTimeBucket(toTimeBucketInDay()); indicator.setEntityId(this.getEntityId()); indicator.setServiceInstanceId(this.getServiceInstanceId()); indicator.setValue(this.getValue()); return indicator; } @Override public Indicator toMonth() { InstanceJvmOldGcCountIndicator indicator = new InstanceJvmOldGcCountIndicator(); indicator.setTimeBucket(toTimeBucketInMonth()); indicator.setEntityId(this.getEntityId()); indicator.setServiceInstanceId(this.getServiceInstanceId()); indicator.setValue(this.getValue()); return indicator; } public static class Builder implements StorageBuilder<InstanceJvmOldGcCountIndicator> { @Override public Map<String, Object> data2Map(InstanceJvmOldGcCountIndicator storageData) { Map<String, Object> map = new HashMap<>(); map.put("entity_id", storageData.getEntityId()); map.put("service_instance_id", storageData.getServiceInstanceId()); map.put("value", storageData.getValue()); map.put("time_bucket", storageData.getTimeBucket()); return map; } @Override public InstanceJvmOldGcCountIndicator map2Data(Map<String, Object> dbMap) { InstanceJvmOldGcCountIndicator indicator = new InstanceJvmOldGcCountIndicator(); indicator.setEntityId((String)dbMap.get("entity_id")); indicator.setServiceInstanceId(((Number)dbMap.get("service_instance_id")).intValue()); indicator.setValue(((Number)dbMap.get("value")).longValue()); indicator.setTimeBucket(((Number)dbMap.get("time_bucket")).longValue()); return indicator; } } }
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.support; import java.beans.PropertyEditor; import java.lang.reflect.Method; import org.springframework.beans.PropertyEditorRegistry; import org.springframework.beans.SimpleTypeConverter; import org.springframework.beans.TypeConverter; import org.springframework.beans.TypeMismatchException; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.MethodInvoker; import org.springframework.util.ReflectionUtils; /** * Subclass of {@link MethodInvoker} that tries to convert the given * arguments for the actual target method via a {@link TypeConverter}. * * <p>Supports flexible argument conversions, in particular for * invoking a specific overloaded method. * * @author Juergen Hoeller * @since 1.1 * @see org.springframework.beans.BeanWrapperImpl#convertIfNecessary */ public class ArgumentConvertingMethodInvoker extends MethodInvoker { @Nullable private TypeConverter typeConverter; private boolean useDefaultConverter = true; /** * Set a TypeConverter to use for argument type conversion. * <p>Default is a {@link org.springframework.beans.SimpleTypeConverter}. * Can be overridden with any TypeConverter implementation, typically * a pre-configured SimpleTypeConverter or a BeanWrapperImpl instance. * @see org.springframework.beans.SimpleTypeConverter * @see org.springframework.beans.BeanWrapperImpl */ public void setTypeConverter(@Nullable TypeConverter typeConverter) { this.typeConverter = typeConverter; this.useDefaultConverter = (typeConverter == null); } /** * Return the TypeConverter used for argument type conversion. * <p>Can be cast to {@link org.springframework.beans.PropertyEditorRegistry} * if direct access to the underlying PropertyEditors is desired * (provided that the present TypeConverter actually implements the * PropertyEditorRegistry interface). */ @Nullable public TypeConverter getTypeConverter() { if (this.typeConverter == null && this.useDefaultConverter) { this.typeConverter = getDefaultTypeConverter(); } return this.typeConverter; } /** * Obtain the default TypeConverter for this method invoker. * <p>Called if no explicit TypeConverter has been specified. * The default implementation builds a * {@link org.springframework.beans.SimpleTypeConverter}. * Can be overridden in subclasses. */ protected TypeConverter getDefaultTypeConverter() { return new SimpleTypeConverter(); } /** * Register the given custom property editor for all properties of the given type. * <p>Typically used in conjunction with the default * {@link org.springframework.beans.SimpleTypeConverter}; will work with any * TypeConverter that implements the PropertyEditorRegistry interface as well. * @param requiredType type of the property * @param propertyEditor editor to register * @see #setTypeConverter * @see org.springframework.beans.PropertyEditorRegistry#registerCustomEditor */ public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) { TypeConverter converter = getTypeConverter(); if (!(converter instanceof PropertyEditorRegistry)) { throw new IllegalStateException( "TypeConverter does not implement PropertyEditorRegistry interface: " + converter); } ((PropertyEditorRegistry) converter).registerCustomEditor(requiredType, propertyEditor); } /** * This implementation looks for a method with matching parameter types. * @see #doFindMatchingMethod */ @Override protected Method findMatchingMethod() { Method matchingMethod = super.findMatchingMethod(); // Second pass: look for method where arguments can be converted to parameter types. if (matchingMethod == null) { // Interpret argument array as individual method arguments. matchingMethod = doFindMatchingMethod(getArguments()); } if (matchingMethod == null) { // Interpret argument array as single method argument of array type. matchingMethod = doFindMatchingMethod(new Object[] {getArguments()}); } return matchingMethod; } /** * Actually find a method with matching parameter type, i.e. where each * argument value is assignable to the corresponding parameter type. * @param arguments the argument values to match against method parameters * @return a matching method, or {@code null} if none */ @Nullable protected Method doFindMatchingMethod(Object[] arguments) { TypeConverter converter = getTypeConverter(); if (converter != null) { String targetMethod = getTargetMethod(); Method matchingMethod = null; int argCount = arguments.length; Class<?> targetClass = getTargetClass(); Assert.state(targetClass != null, "No target class set"); Method[] candidates = ReflectionUtils.getAllDeclaredMethods(targetClass); int minTypeDiffWeight = Integer.MAX_VALUE; Object[] argumentsToUse = null; for (Method candidate : candidates) { if (candidate.getName().equals(targetMethod)) { // Check if the inspected method has the correct number of parameters. Class<?>[] paramTypes = candidate.getParameterTypes(); if (paramTypes.length == argCount) { Object[] convertedArguments = new Object[argCount]; boolean match = true; for (int j = 0; j < argCount && match; j++) { // Verify that the supplied argument is assignable to the method parameter. try { convertedArguments[j] = converter.convertIfNecessary(arguments[j], paramTypes[j]); } catch (TypeMismatchException ex) { // Ignore -> simply doesn't match. match = false; } } if (match) { int typeDiffWeight = getTypeDifferenceWeight(paramTypes, convertedArguments); if (typeDiffWeight < minTypeDiffWeight) { minTypeDiffWeight = typeDiffWeight; matchingMethod = candidate; argumentsToUse = convertedArguments; } } } } } if (matchingMethod != null) { setArguments(argumentsToUse); return matchingMethod; } } return null; } }
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package com.pivotal.gemfirexd.internal.engine.distributed.message; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import com.gemstone.gemfire.DataSerializer; import com.gemstone.gemfire.GemFireCheckedException; import com.gemstone.gemfire.cache.Operation; import com.gemstone.gemfire.distributed.DistributedMember; import com.gemstone.gemfire.distributed.internal.DistributionManager; import com.gemstone.gemfire.internal.InternalDataSerializer; import com.gemstone.gemfire.internal.cache.ForceReattemptException; import com.gemstone.gemfire.internal.cache.LocalRegion; import com.gemstone.gemfire.internal.cache.PartitionedRegion; import com.gemstone.gemfire.internal.cache.PartitionedRegionHelper; import com.gemstone.gemfire.internal.cache.TXStateInterface; import com.gemstone.gemfire.internal.cache.Token; import com.gemstone.gemfire.internal.cache.TransactionMessage; import com.gemstone.gemfire.internal.cache.locks.LockingPolicy; import com.gemstone.gemfire.internal.i18n.LocalizedStrings; import com.gemstone.gnu.trove.THashSet; import com.pivotal.gemfirexd.internal.engine.Misc; import com.pivotal.gemfirexd.internal.engine.GfxdConstants; import com.pivotal.gemfirexd.internal.engine.access.index.GfxdIndexManager.ContainsKeyExecutorMessage; import com.pivotal.gemfirexd.internal.engine.distributed.GfxdListResultCollector; import com.pivotal.gemfirexd.internal.engine.distributed.utils.GemFireXDUtils; import com.pivotal.gemfirexd.internal.engine.store.CompactCompositeKey; import com.pivotal.gemfirexd.internal.engine.store.CompactCompositeRegionKey; import com.pivotal.gemfirexd.internal.engine.store.CompositeRegionKey; import com.pivotal.gemfirexd.internal.engine.store.GemFireContainer.BulkKeyLookupResult; import com.pivotal.gemfirexd.internal.iapi.error.StandardException; import com.pivotal.gemfirexd.internal.iapi.sql.conn.LanguageConnectionContext; import com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor; import com.pivotal.gemfirexd.internal.impl.sql.execute.xplain.XPLAINUtil; import com.pivotal.gemfirexd.internal.shared.common.sanity.SanityManager; /** * Class that checks existence of an array of (FK) keys in a given FK * refContainer (PK based global index or the PR if local PK index) * * @author shirishd * */ public class ContainsKeyBulkExecutorMessage extends RegionExecutorMessage<Object> { /** array of FKs whose existence is to be checked */ protected Object[] inKeys; protected Object[] inRoutingObjects; protected String regionPath; protected PartitionedRegion pr; protected int prId; protected DistributedMember member; /** map of keys to be processed for the current node to bucket ids * for the current node */ HashMap<Object, Integer> keysToBucketIds; protected static final short IS_PARTITIONED_TABLE = RegionExecutorMessage.UNRESERVED_FLAGS_START; public ContainsKeyBulkExecutorMessage() { super(true); this.inKeys = null; this.inRoutingObjects = null; this.regionPath = null; this.pr = null; this.keysToBucketIds = null; } @SuppressWarnings("unchecked") public ContainsKeyBulkExecutorMessage(final LocalRegion region, Object[] keys, Object[] routingObjects, final TXStateInterface tx, final LanguageConnectionContext lcc) { super(new GfxdListResultCollector(null, true), region, new THashSet( Arrays.asList(routingObjects)) /*routingObjects*/, tx, getTimeStatsSettings(lcc)); this.inKeys = keys; this.inRoutingObjects = routingObjects; this.regionPath = region.getFullPath(); if (region.getPartitionAttributes() != null) { this.pr = (PartitionedRegion)region; this.prId = this.pr.getPRId(); } } public ContainsKeyBulkExecutorMessage(ContainsKeyBulkExecutorMessage other) { super(other); this.inKeys = other.inKeys; this.inRoutingObjects = other.inRoutingObjects; this.pr = other.pr; this.prId = other.prId; this.regionPath = region.getFullPath(); this.routingObjects = other.routingObjects; this.membersToBucketIds = other.membersToBucketIds; this.keysToBucketIds = other.keysToBucketIds; this.member = other.member; } @Override protected ContainsKeyBulkExecutorMessage clone() { return new ContainsKeyBulkExecutorMessage(this); } @Override protected void execute() throws GemFireCheckedException { boolean doLog = DistributionManager.VERBOSE | GemFireXDUtils.TraceQuery; final boolean isPR = this.pr != null; final TXStateInterface tx = getTXState(); Object key; int bucketId = 0; boolean containsKey; if (this.keysToBucketIds == null) { populateKeysToBucketIdsMap(this.bucketBitSet); } if (doLog) { SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_QUERYDISTRIB, "ContainsKeyBulkExecutorMessage#execute: region=" + this.regionPath + " keysToBucketIds map for the current member= " + keysToBucketIds); } for (Map.Entry<Object, Integer> entry : this.keysToBucketIds.entrySet()) { key = entry.getKey(); bucketId = entry.getValue(); if (key instanceof CompactCompositeRegionKey) { ((CompactCompositeRegionKey)key).setRegionContext(this.region); } containsKey = ContainsKeyExecutorMessage.existsKey(this.region, isPR, bucketId, key, tx, null /* callbackArg */); // send only failed lookups if (!containsKey) { final BulkKeyLookupResult oneResult = new BulkKeyLookupResult(key, containsKey); sendResult(oneResult); } } // send last result final BulkKeyLookupResult finalResult = new BulkKeyLookupResult( Token.INVALID, true); lastResult(finalResult); } @Override protected final void processMessage(DistributionManager dm) throws GemFireCheckedException { if (this.region == null) { if (this.prId >= 0) { // PR case this.pr = PartitionedRegion.getPRFromId(this.prId); if (this.pr == null) { throw new ForceReattemptException( LocalizedStrings.PartitionMessage_0_COULD_NOT_FIND_PARTITIONED_REGION_WITH_ID_1 .toLocalizedString(new Object[] { Misc.getGemFireCache().getMyId(), Integer.valueOf(this.prId) })); } this.region = this.pr; this.regionPath = region.getFullPath(); } else { this.region = Misc.getGemFireCache().getRegionByPathForProcessing( this.regionPath); if (this.region == null) { throw new ForceReattemptException( LocalizedStrings.Region_CLOSED_OR_DESTROYED .toLocalizedString(this.regionPath)); } } } super.processMessage(dm); } protected String getID() { return getShortClassName(); } @Override protected short computeCompressedShort(short flags) { flags = super.computeCompressedShort(flags); if (this.prId >= 0) { flags |= IS_PARTITIONED_TABLE; } return flags; } @Override public void toData(DataOutput out) throws IOException { final long beginTime = this.timeStatsEnabled ? XPLAINUtil .recordTiming(ser_deser_time == 0 ? ser_deser_time = -1 /*record*/ : -2 /*ignore nested call*/) : 0; super.toData(out); // InternalDataSerializer.writeObject(this.inKeys, out); // InternalDataSerializer.writeObject(this.inRoutingObjects, out); InternalDataSerializer.writeObject(this.keysToBucketIds, out); // write the region ID or path if (this.prId >= 0) { InternalDataSerializer.writeUnsignedVL(this.prId, out); } else { DataSerializer.writeString(this.regionPath, out); } if (beginTime != 0) { this.ser_deser_time = XPLAINUtil.recordTiming(beginTime); } } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { ser_deser_time = this.timeStatsEnabled ? (ser_deser_time == 0 ? -1 /*record*/ : -2/*ignore nested call*/) : 0; super.fromData(in); // this.inKeys = InternalDataSerializer.readObject(in); // this.inRoutingObjects = InternalDataSerializer.readObject(in); this.keysToBucketIds = InternalDataSerializer.readObject(in); if ((flags & IS_PARTITIONED_TABLE) != 0) { this.prId = (int)InternalDataSerializer.readUnsignedVL(in); } else { this.regionPath = DataSerializer.readString(in); } if (this.timeStatsEnabled && ser_deser_time == -1) { this.ser_deser_time = XPLAINUtil.recordStdTiming(getTimestamp()); } } public long estimateMemoryUsage() throws StandardException { long memory = 0; for (Map.Entry<Object, Integer> m : this.keysToBucketIds.entrySet()) { Object o = m.getKey(); if (o instanceof CompactCompositeRegionKey) { memory += ((CompactCompositeRegionKey) o).estimateMemoryUsage(); } else if (o instanceof CompactCompositeKey) { memory += ((CompactCompositeKey) o).estimateMemoryUsage(); } else if (o instanceof CompositeRegionKey) { memory += ((CompositeRegionKey) o).estimateMemoryUsage(); } else if (o instanceof DataValueDescriptor) { memory += ((DataValueDescriptor) o).estimateMemoryUsage(); } } return memory; } /** * Set the keys to buckets ids for this member */ @Override protected void setArgsForMember(DistributedMember member, Set<DistributedMember> messageAwareMembers) { this.member = member; final BitSetSet bucketBitSet = (BitSetSet) membersToBucketIds .get(this.member); // bucketBitSet could be null in the case of self (message sending data // node) the map is populated in execute() in that case if (bucketBitSet != null) { this.populateKeysToBucketIdsMap(bucketBitSet); } } private void populateKeysToBucketIdsMap(final BitSetSet bucketBitSet) { // final boolean isPR = (this.region !=null && region.getPartitionAttributes() != null); this.keysToBucketIds = new HashMap<Object, Integer>(); int bucketId = 0; for (int j = 0; j < inKeys.length; j++) { if (inKeys[j] != null) { // if (isPR) { if (inRoutingObjects != null) { bucketId = PartitionedRegionHelper.getHashKey(this.pr, inRoutingObjects[j]); } else { if (inKeys[j] instanceof CompactCompositeRegionKey) { ((CompactCompositeRegionKey) inKeys[j]) .setRegionContext(this.region); } bucketId = PartitionedRegionHelper.getHashKey(this.pr, Operation.GET, inKeys[j], null, null /* callbackArg */); } // } if (bucketBitSet.containsInt(bucketId)) { this.keysToBucketIds.put(inKeys[j], bucketId); } } } } @Override public boolean withSecondaries() { return false; } @Override public byte getGfxdID() { return CONTAINSKEY_BULK_EXECUTOR_MSG; } @Override public boolean optimizeForWrite() { return false; } /** * @see TransactionMessage#canStartRemoteTransaction() */ @Override public final boolean canStartRemoteTransaction() { return true; } /** * @see TransactionMessage#useTransactionProxy() */ @Override public boolean useTransactionProxy() { // use TX proxy to enable batching of read locks return getLockingPolicy().readOnlyCanStartTX(); } @Override protected boolean requiresTXFlushAfterExecution() { // to flush any batched read locks return getLockingPolicy().readOnlyCanStartTX(); } @Override public boolean isHA() { return true; } @Override protected void setIgnoreReplicateIfSetOperators(boolean ignoreReplicate) { // do nothing } @Override public final int getMessageProcessorType() { // Make this serial so that it will be processed in the p2p msg reader // which gives it better performance. // don't use SERIAL_EXECUTOR if we may have to wait for a pending TX // else if may deadlock as the p2p msg reader thread will be blocked // don't use SERIAL_EXECUTOR for RepeatableRead isolation level else // it can block P2P reader thread thus blocking any possible commits // which could have released the SH lock this thread is waiting on return this.pendingTXId == null && getLockingPolicy() == LockingPolicy.NONE ? DistributionManager.SERIAL_EXECUTOR : DistributionManager.PARTITIONED_REGION_EXECUTOR; } }
package com.github.charlemaznable.varystest.proxy; import com.github.charlemaznable.core.net.common.Mapping; import com.github.charlemaznable.core.net.common.Parameter; import com.github.charlemaznable.core.net.common.PathVar; import com.github.charlemaznable.core.net.common.RequestMethod; import com.github.charlemaznable.varys.impl.ProxyWechatCorp; import static com.github.charlemaznable.core.net.common.HttpMethod.POST; @ProxyWechatCorp public interface ProxyWechatCorpDemo { @Mapping("/{codeName}/wechatCorp") String wechatCorp(@PathVar("codeName") String codeName, @Parameter("a") String a); @RequestMethod(POST) @Mapping("/{codeName}/wechatCorpParam/{testParam}") String wechatCorpParam(@PathVar("codeName") String codeName, @PathVar("testParam") String testParam, @Parameter("a") String a); }
package br.com.pos.unicamp.vrep.actuators; public class Motors { private final Motor leftMotor; private final Motor rightMotor; public Motors() { leftMotor = new Motor("Pioneer_p3dx_leftMotor"); rightMotor = new Motor("Pioneer_p3dx_rightMotor"); } public void setVelocity(final float motorLeftVelocity, final float motorRightVelocity) { leftMotor.setTargetVelocity(motorLeftVelocity); rightMotor.setTargetVelocity(motorRightVelocity); } public Motor getLeftMotor() { return leftMotor; } public Motor getRightMotor() { return rightMotor; } }
// Copyright (C) 2013 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.google.gerrit.server.account; import com.google.common.base.Strings; import com.google.gerrit.extensions.client.AccountFieldName; import com.google.gerrit.extensions.restapi.AuthException; import com.google.gerrit.extensions.restapi.DefaultInput; import com.google.gerrit.extensions.restapi.MethodNotAllowedException; import com.google.gerrit.extensions.restapi.ResourceNotFoundException; import com.google.gerrit.extensions.restapi.Response; import com.google.gerrit.extensions.restapi.RestModifyView; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.account.PutName.Input; import com.google.gerrit.server.permissions.GlobalPermission; import com.google.gerrit.server.permissions.PermissionBackend; import com.google.gerrit.server.permissions.PermissionBackendException; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import java.io.IOException; import org.eclipse.jgit.errors.ConfigInvalidException; @Singleton public class PutName implements RestModifyView<AccountResource, Input> { public static class Input { @DefaultInput public String name; } private final Provider<CurrentUser> self; private final Realm realm; private final PermissionBackend permissionBackend; private final Provider<ReviewDb> dbProvider; private final AccountsUpdate.Server accountsUpdate; @Inject PutName( Provider<CurrentUser> self, Realm realm, PermissionBackend permissionBackend, Provider<ReviewDb> dbProvider, AccountsUpdate.Server accountsUpdate) { this.self = self; this.realm = realm; this.permissionBackend = permissionBackend; this.dbProvider = dbProvider; this.accountsUpdate = accountsUpdate; } @Override public Response<String> apply(AccountResource rsrc, Input input) throws AuthException, MethodNotAllowedException, ResourceNotFoundException, OrmException, IOException, PermissionBackendException, ConfigInvalidException { if (self.get() != rsrc.getUser()) { permissionBackend.user(self).check(GlobalPermission.MODIFY_ACCOUNT); } return apply(rsrc.getUser(), input); } public Response<String> apply(IdentifiedUser user, Input input) throws MethodNotAllowedException, ResourceNotFoundException, OrmException, IOException, ConfigInvalidException { if (input == null) { input = new Input(); } if (!realm.allowsEdit(AccountFieldName.FULL_NAME)) { throw new MethodNotAllowedException("realm does not allow editing name"); } String newName = input.name; Account account = accountsUpdate .create() .update(dbProvider.get(), user.getAccountId(), a -> a.setFullName(newName)); if (account == null) { throw new ResourceNotFoundException("account not found"); } return Strings.isNullOrEmpty(account.getFullName()) ? Response.none() : Response.ok(account.getFullName()); } }
import java.util.HashMap; import java.util.Map; /** * * 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 * * 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 * *   * * 示例: * * 给定 nums = [2, 7, 11, 15], target = 9 * * 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] * * 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * * */ class Solution { public int[] twoSum(int[] nums, int target) { /** * 暴力法 枚举枚举每一对整数 时间复杂度O(n^2) 空间复杂度时间复杂度O(1) * * 是否能使用 * * O(n) 空间复杂度 时间复杂度O(n)实现呢? * */ if (nums == null) return null; Map<Integer, Integer> map = new HashMap(); for (int i = 0; i < nums.length; i++) { Integer idx = map.get(target - nums[i]); if (idx != null) return new int[] { idx, i }; map.put(nums[i], i); } return null; } }
package com.revature.util; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class ConnFactory { private static ConnFactory cf; private ConnFactory() { super(); } public static synchronized ConnFactory getInstance() { if(cf == null) { cf = new ConnFactory(); } return cf; } public Connection getConnection() { Connection conn = null; Properties prop = new Properties(); try { prop.load(new FileReader("database.properties")); conn = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password")); } catch (SQLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return conn; } }
/** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.example.fireeats; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Html; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.firebase.ui.auth.AuthUI; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.example.fireeats.adapter.RestaurantAdapter; import com.google.firebase.example.fireeats.viewmodel.MainActivityViewModel; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.Query; import java.util.Collections; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends AppCompatActivity implements FilterDialogFragment.FilterListener, RestaurantAdapter.OnRestaurantSelectedListener { private static final String TAG = "MainActivity"; private static final int RC_SIGN_IN = 9001; private static final int LIMIT = 50; @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.text_current_search) TextView mCurrentSearchView; @BindView(R.id.text_current_sort_by) TextView mCurrentSortByView; @BindView(R.id.recycler_restaurants) RecyclerView mRestaurantsRecycler; @BindView(R.id.view_empty) ViewGroup mEmptyView;; private FirebaseFirestore mFirestore; private Query mQuery; private FilterDialogFragment mFilterDialog; private RestaurantAdapter mAdapter; private MainActivityViewModel mViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); setSupportActionBar(mToolbar); // View model mViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class); // Enable Firestore logging FirebaseFirestore.setLoggingEnabled(true); // Initialize Firestore and the main RecyclerView initFirestore(); initRecyclerView(); // Filter Dialog mFilterDialog = new FilterDialogFragment(); } private void initFirestore() { // TODO(developer): Implement } private void initRecyclerView() { if (mQuery == null) { Log.w(TAG, "No query, not initializing RecyclerView"); } mAdapter = new RestaurantAdapter(mQuery, this) { @Override protected void onDataChanged() { // Show/hide content if the query returns empty. if (getItemCount() == 0) { mRestaurantsRecycler.setVisibility(View.GONE); mEmptyView.setVisibility(View.VISIBLE); } else { mRestaurantsRecycler.setVisibility(View.VISIBLE); mEmptyView.setVisibility(View.GONE); } } @Override protected void onError(FirebaseFirestoreException e) { // Show a snackbar on errors Snackbar.make(findViewById(android.R.id.content), "Error: check logs for info.", Snackbar.LENGTH_LONG).show(); } }; mRestaurantsRecycler.setLayoutManager(new LinearLayoutManager(this)); mRestaurantsRecycler.setAdapter(mAdapter); } @Override public void onStart() { super.onStart(); // Start sign in if necessary if (shouldStartSignIn()) { startSignIn(); return; } // Apply filters onFilter(mViewModel.getFilters()); // Start listening for Firestore updates if (mAdapter != null) { mAdapter.startListening(); } } @Override public void onStop() { super.onStop(); if (mAdapter != null) { mAdapter.stopListening(); } } private void onAddItemsClicked() { // TODO(developer): Add random restaurants showTodoToast(); } @Override public void onFilter(Filters filters) { // TODO(developer): Construct new query showTodoToast(); // Set header mCurrentSearchView.setText(Html.fromHtml(filters.getSearchDescription(this))); mCurrentSortByView.setText(filters.getOrderDescription(this)); // Save filters mViewModel.setFilters(filters); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_add_items: onAddItemsClicked(); break; case R.id.menu_sign_out: AuthUI.getInstance().signOut(this); startSignIn(); break; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { mViewModel.setIsSigningIn(false); if (resultCode != RESULT_OK && shouldStartSignIn()) { startSignIn(); } } } @OnClick(R.id.filter_bar) public void onFilterClicked() { // Show the dialog containing filter options mFilterDialog.show(getSupportFragmentManager(), FilterDialogFragment.TAG); } @OnClick(R.id.button_clear_filter) public void onClearFilterClicked() { mFilterDialog.resetFilters(); onFilter(Filters.getDefault()); } @Override public void onRestaurantSelected(DocumentSnapshot restaurant) { // Go to the details page for the selected restaurant Intent intent = new Intent(this, RestaurantDetailActivity.class); intent.putExtra(RestaurantDetailActivity.KEY_RESTAURANT_ID, restaurant.getId()); startActivity(intent); } private boolean shouldStartSignIn() { return (!mViewModel.getIsSigningIn() && FirebaseAuth.getInstance().getCurrentUser() == null); } private void startSignIn() { // Sign in with FirebaseUI Intent intent = AuthUI.getInstance().createSignInIntentBuilder() .setAvailableProviders(Collections.singletonList( new AuthUI.IdpConfig.EmailBuilder().build())) .setIsSmartLockEnabled(false) .build(); startActivityForResult(intent, RC_SIGN_IN); mViewModel.setIsSigningIn(true); } private void showTodoToast() { Toast.makeText(this, "TODO: Implement", Toast.LENGTH_SHORT).show(); } }
package com.test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import com.test.service.UniqueCharacterService; @SpringBootTest public class UniqueCharacterServiceTest { @Autowired private UniqueCharacterService uniqueCharacterService; @Test public void shouldBeAbleToCheckIfAStringIsComposedOfUniqueCharacters() { boolean result = uniqueCharacterService.isUniqueChars("abc"); assertTrue(result); result = uniqueCharacterService.isUniqueChars("aba"); assertFalse(result); } }
/* * 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.nifi.web.search; import org.apache.nifi.web.api.dto.search.ComponentSearchResultDTO; import org.apache.nifi.web.search.attributematchers.AttributeMatcher; import org.apache.nifi.web.search.query.SearchQuery; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.function.Function; public class AttributeBasedComponentMatcher<T> implements ComponentMatcher<T> { private final List<AttributeMatcher<T>> attributeMatchers = new ArrayList<>(); private final Function<T, String> getComponentIdentifier; private final Function<T, String> getComponentName; public AttributeBasedComponentMatcher( final List<AttributeMatcher<T>> attributeMatchers, final Function<T, String> getComponentIdentifier, final Function<T, String> getComponentName) { this.getComponentIdentifier = getComponentIdentifier; this.getComponentName = getComponentName; this.attributeMatchers.addAll(attributeMatchers); } @Override public final Optional<ComponentSearchResultDTO> match(final T component, final SearchQuery query) { final List<String> matches = new LinkedList<>(); attributeMatchers.forEach(matcher -> matcher.match(component, query, matches)); return matches.isEmpty() ? Optional.empty() : Optional.of(generateResult(component, matches)); } private ComponentSearchResultDTO generateResult(final T component, final List<String> matches) { final ComponentSearchResultDTO result = new ComponentSearchResultDTO(); result.setId(getComponentIdentifier.apply(component)); result.setName(getComponentName.apply(component)); result.setMatches(matches); return result; } }
/* * Copyright 2019 ConsenSys AG. * * 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 tech.pegasys.ethsigner.jsonrpcproxy.model.response; import static java.util.Collections.emptyList; import tech.pegasys.ethsigner.core.jsonrpc.response.JsonRpcError; import tech.pegasys.ethsigner.core.jsonrpc.response.JsonRpcErrorResponse; import java.util.Map.Entry; import io.netty.handler.codec.http.HttpResponseStatus; import io.vertx.core.json.Json; public class EthResponseFactory { private static final Iterable<Entry<String, String>> NO_HEADERS = emptyList(); private static final int DEFAULT_ID = 77; public EthSignerResponse ethSigner(final Object id, final JsonRpcError error) { return new EthSignerResponse( NO_HEADERS, new JsonRpcErrorResponse(id, error), HttpResponseStatus.BAD_REQUEST); } public EthSignerResponse ethSigner(final JsonRpcError error) { return new EthSignerResponse( NO_HEADERS, new JsonRpcErrorResponse(DEFAULT_ID, error), HttpResponseStatus.BAD_REQUEST); } public EthSignerResponse ethSigner(final JsonRpcError error, final HttpResponseStatus code) { return new EthSignerResponse(NO_HEADERS, new JsonRpcErrorResponse(DEFAULT_ID, error), code); } public EthSignerResponse ethSigner( final Iterable<Entry<String, String>> headers, final String body) { return new EthSignerResponse(headers, body, HttpResponseStatus.OK); } public EthSignerResponse ethSigner(final String body) { return new EthSignerResponse(NO_HEADERS, body, HttpResponseStatus.OK); } public EthSignerResponse ethSigner(final String body, final HttpResponseStatus statusCode) { return new EthSignerResponse(NO_HEADERS, body, statusCode); } public EthNodeResponse ethNode(final Iterable<Entry<String, String>> headers, final String body) { return new EthNodeResponse(headers, body, HttpResponseStatus.OK); } public EthNodeResponse ethNode( final Iterable<Entry<String, String>> headers, final String body, final HttpResponseStatus statusCode) { return new EthNodeResponse(headers, body, statusCode); } public EthNodeResponse ethNode(final String body) { return new EthNodeResponse(NO_HEADERS, body, HttpResponseStatus.OK); } public EthNodeResponse ethNode(final String body, final HttpResponseStatus code) { return new EthNodeResponse(NO_HEADERS, body, code); } public EthNodeResponse ethNode(final JsonRpcError error) { final JsonRpcErrorResponse errorResponse = new JsonRpcErrorResponse(DEFAULT_ID, error); return new EthNodeResponse(NO_HEADERS, Json.encode(errorResponse), HttpResponseStatus.OK); } }
package com.rayo.core; import com.voxeo.exceptions.VException; public class CallException extends VException { public CallException() { super(); } public CallException(String s, Object... args) { super(s, args); } public CallException(String message, Throwable cause) { super(message, cause); } public CallException(String message) { super(message); } public CallException(Throwable cause) { super(cause); } }
package com.hedera.services.sigs.metadata.lookups; /*- * ‌ * Hedera Services Node * ​ * Copyright (C) 2018 - 2021 Hedera Hashgraph, LLC * ​ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ‍ */ import com.hedera.services.sigs.metadata.TopicSigningMetadata; import com.hederahashgraph.api.proto.java.TopicID; /** * Defines a simple type that is able to recover metadata about signing activity associated with a given HCS topic. */ public interface TopicSigMetaLookup { SafeLookupResult<TopicSigningMetadata> safeLookup(TopicID id); }
package be.teletask.onvif; import be.teletask.onvif.listeners.OnvifResponseListener; import be.teletask.onvif.models.OnvifDevice; import be.teletask.onvif.models.OnvifServices; import be.teletask.onvif.parsers.*; import be.teletask.onvif.requests.*; import be.teletask.onvif.responses.OnvifResponse; import com.burgstaller.okhttp.AuthenticationCacheInterceptor; import com.burgstaller.okhttp.CachingAuthenticatorDecorator; import com.burgstaller.okhttp.digest.CachingAuthenticator; import com.burgstaller.okhttp.digest.Credentials; import com.burgstaller.okhttp.digest.DigestAuthenticator; import okhttp3.*; import okio.Buffer; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; /** * Created by Tomas Verhelst on 03/09/2018. * Copyright (c) 2018 TELETASK BVBA. All rights reserved. */ public class OnvifExecutor { //Constants public static final String TAG = OnvifExecutor.class.getSimpleName(); //Attributes private OkHttpClient client; private MediaType reqBodyType; private RequestBody reqBody; private Credentials credentials; private OnvifResponseListener onvifResponseListener; //Constructors OnvifExecutor(OnvifResponseListener onvifResponseListener) { this.onvifResponseListener = onvifResponseListener; credentials = new Credentials("username", "password"); DigestAuthenticator authenticator = new DigestAuthenticator(credentials); Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>(); client = new OkHttpClient.Builder() .connectTimeout(10000, TimeUnit.SECONDS) .writeTimeout(100, TimeUnit.SECONDS) .readTimeout(10000, TimeUnit.SECONDS) .authenticator(new CachingAuthenticatorDecorator(authenticator, authCache)) .addInterceptor(new AuthenticationCacheInterceptor(authCache)) .build(); reqBodyType = MediaType.parse("application/soap+xml; charset=utf-8;"); } //Methods /** * Sends a request to the Onvif-compatible device. * * @param device * @param request */ void sendRequest(OnvifDevice device, OnvifRequest request) { credentials.setUserName(device.getUsername()); credentials.setPassword(device.getPassword()); reqBody = RequestBody.create(OnvifXMLBuilder.getSoapHeader() + request.getXml() + OnvifXMLBuilder.getEnvelopeEnd(), reqBodyType); performXmlRequest(device, request, buildOnvifRequest(device, request)); } /** * Clears up the resources. */ void clear() { onvifResponseListener = null; } //Properties public void setOnvifResponseListener(OnvifResponseListener onvifResponseListener) { this.onvifResponseListener = onvifResponseListener; } private void performXmlRequest(OnvifDevice device, OnvifRequest request, Request xmlRequest) { if (xmlRequest == null) return; client.newCall(xmlRequest) .enqueue(new Callback() { @Override public void onResponse(Call call, Response xmlResponse) throws IOException { OnvifResponse response = new OnvifResponse(request); ResponseBody xmlBody = xmlResponse.body(); if (xmlResponse.code() == 200 && xmlBody != null) { response.setSuccess(true); response.setXml(xmlBody.string()); parseResponse(device, response); return; } String errorMessage = ""; if (xmlBody != null) errorMessage = xmlBody.string(); onvifResponseListener.onError(device, xmlResponse.code(), errorMessage); } @Override public void onFailure(Call call, IOException e) { onvifResponseListener.onError(device, -1, e.getMessage()); } }); } private void parseResponse(OnvifDevice device, OnvifResponse response) { switch (response.request().getType()) { case GET_SERVICES: // call this to initialise service paths (device/media/ptz..) OnvifServices path = new GetServicesParser().parse(response); device.setPath(path); ((GetServicesRequest) response.request()).getListener().onServicesReceived(device, path); break; case GET_DEVICE_INFORMATION: ((GetDeviceInformationRequest) response.request()).getListener().onDeviceInformationReceived(device, new GetDeviceInformationParser().parse(response)); break; case GET_MEDIA_PROFILES: ((GetMediaProfilesRequest) response.request()).getListener().onMediaProfilesReceived(device, new GetMediaProfilesParser().parse(response)); break; case GET_STREAM_URI: GetMediaStreamRequest streamRequest = (GetMediaStreamRequest) response.request(); streamRequest.getListener().onMediaStreamURIReceived(device, streamRequest.getMediaProfile(), new GetMediaStreamParser().parse(response)); break; case GET_SNAPSHOT_URI: GetSnapshotUriRequest getSnapshotUriRequest = (GetSnapshotUriRequest) response.request(); getSnapshotUriRequest.getListener().onSnapshotURIReceived(device, getSnapshotUriRequest.getMediaProfile(), new GetSnapshotUriParser().parse(response)); break; case GET_STATUS: GetStatusRequest getStatusRequest = (GetStatusRequest) response.request(); getStatusRequest.getListener().onStatusReceived(device, getStatusRequest.getMediaProfile(), new GetStatusParser().parse(response)); break; case GET_PRESETS: GetPresetsRequest getPresetsRequest = (GetPresetsRequest) response.request(); getPresetsRequest.getListener().onPresetsReceived(device, getPresetsRequest.getMediaProfile(), new GetPresetsParser().parse(response)); break; case SET_PRESET: SetPresetRequest setPresetRequest = (SetPresetRequest) response.request(); setPresetRequest.getListener().onPresetReceived(device, setPresetRequest.getMediaProfile(), new SetPresetParser().parse(response)); break; default: onvifResponseListener.onResponse(device, response); break; } } private Request buildOnvifRequest(OnvifDevice device, OnvifRequest request) { return new Request.Builder() .url(getUrlForRequest(device, request)) .addHeader("Content-Type", "text/xml; charset=utf-8") .post(reqBody) .build(); } private String getUrlForRequest(OnvifDevice device, OnvifRequest request) { return device.getHostName() + getPathForRequest(device, request); } private String getPathForRequest(OnvifDevice device, OnvifRequest request) { switch (request.getType()) { case GET_SERVICES: case GET_DEVICE_INFORMATION: return device.getPath().getDevicePath(); case GET_MEDIA_PROFILES: case GET_STREAM_URI: case GET_SNAPSHOT_URI: return device.getPath().getMediaPath(); case ABSOLUTE_MOVE: case GET_STATUS: case GOTO_HOME_POSITION: case GOTO_PRESET: case GET_PRESETS: case SET_PRESET: case REMOVE_PRESET: return device.getPath().getPtzPath(); default: return device.getPath().getServicesPath(); } } private String bodyToString(Request request) { try { Request copy = request.newBuilder().build(); Buffer buffer = new Buffer(); if (copy.body() != null) copy.body().writeTo(buffer); return buffer.readUtf8(); } catch (IOException e) { e.printStackTrace(); return ""; } } }
package north.pathfindingmazejava.datastructures; /** * * @author northernpike */ import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class ArrayListTest { ArrayList<Integer> beforelist; Integer added; Integer added2; Integer added3; @Before public void setUp() { beforelist = new ArrayList<>(); added = 1; added2 = 2; added3 = 3; } @Test public void testAdd() { beforelist.add(added); assertEquals(added, beforelist.get(0)); } @Test public void testManyAdd() { beforelist.add(added); beforelist.add(added3); beforelist.add(added2); assertEquals(added, beforelist.get(0)); assertEquals(added3, beforelist.get(1)); assertEquals(added2, beforelist.get(2)); } @Test public void testGet() { beforelist.add(added2); beforelist.add(added); assertEquals(added2, beforelist.get(0)); assertEquals(added, beforelist.get(1)); } @Test public void testReverse() { beforelist.add(added); beforelist.add(added2); beforelist.add(added3); ArrayList<Integer> afterlist = new ArrayList<>(); afterlist.add(added3); afterlist.add(added2); afterlist.add(added); afterlist.reverse(); assertEquals(afterlist.get(0), beforelist.get(0)); assertEquals(afterlist.get(1), beforelist.get(1)); assertEquals(afterlist.get(2), beforelist.get(2)); } @Test public void testSize() { beforelist.add(added); assertEquals(1, beforelist.getSize()); } @Test public void testSizeWhenEmpty() { assertEquals(0, beforelist.getSize()); } }
package com.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet Filter implementation class TestingLogInFilter */ // ALL Filter setup in web.xml // please refer setting with web-site www.codejava.net/java-ee/servlet/webfilter-annotation-examples // 消費者視角(前台),有些按鈕只有MemberUsing可以進去。 public class MemCanBtnFilter implements Filter { /** * Default constructor. */ // public BusAccessBackFilter() { // // TODO Auto-generated constructor stub // } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) * * Only Bus identity can access Background. * In session, use "BusUsing" as key name. */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; HttpSession session = req.getSession(); if (session.getAttribute("MemberUsing") == null) { res.sendRedirect(req.getContextPath()+"/nest-frontend/showBtnFilter.jsp"); } else { chain.doFilter(request, response); } } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } }
// Dstl (c) Crown Copyright 2017 package uk.gov.dstl.baleen.annotators.testing; import java.util.Collection; import org.apache.uima.analysis_engine.AnalysisEngine; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.pipeline.SimplePipeline; import org.apache.uima.resource.ResourceInitializationException; import org.junit.Before; import uk.gov.dstl.baleen.uima.BaleenAnnotator; /** * A base class for testing annotators where multiple annotators are needed in a pipeline. * * <p>For example in testing entity extraction annotator you might first need to perform POS * tagging. * * <p>This is more like an integration test than a unit test, but given the complexity of some * annotators outputs it might be easier to use the real annotator than attempt to manually mock its * output. */ public abstract class AbstractMultiAnnotatorTest extends AnnotatorTestBase { private AnalysisEngine[] analysisEngines; @Before public void beforeMultiAnnotatorTest() throws ResourceInitializationException { analysisEngines = createAnalysisEngines(); } protected abstract AnalysisEngine[] createAnalysisEngines() throws ResourceInitializationException; /** * Get an analysis engine for the provided class. * * @param annotatorClass the class of the annotator to create as an analysis engine * @return * @throws ResourceInitializationException */ protected AnalysisEngine createAnalysisEngine(Class<? extends BaleenAnnotator> annotatorClass) throws ResourceInitializationException { return AnalysisEngineFactory.createEngine(annotatorClass); } /** * Get an analysis engine for the provided class * * @param annotatorClass the class of the annotorat to create as an analysis engine * @param args name-value pairs * @return * @throws ResourceInitializationException */ protected AnalysisEngine createAnalysisEngine( Class<? extends BaleenAnnotator> annotatorClass, Object... args) throws ResourceInitializationException { return AnalysisEngineFactory.createEngine(annotatorClass, args); } /** * Convert variable argument to array. * * <p>Helper for use with createAnalysisEngines() implementations. * * @param args analysis engines as variable arguments * @return an array of the args * @throws ResourceInitializationException */ protected AnalysisEngine[] asArray(AnalysisEngine... args) { return args; } /** * Convert list argument to array of analysisengines. * * <p>Helper for use with createAnalysisEngines() implementations. * * @param aes analysis engines as collection * @return an array of of analysis engines provided in the collection * @throws ResourceInitializationException */ protected AnalysisEngine[] asArray(Collection<AnalysisEngine> aes) { return aes.toArray(new AnalysisEngine[aes.size()]); } /** * process the {@link AnnotatorTestBase}'s jCas with the annotator. * * @throws ResourceInitializationException * @throws AnalysisEngineProcessException */ protected void processJCas() throws ResourceInitializationException, AnalysisEngineProcessException { SimplePipeline.runPipeline(jCas, analysisEngines); } }
package mil.nga.tiff; /** * TIFF Test Constants * * @author osbornb */ public class TiffTestConstants { /** * Stripped TIFF test file */ public static final String FILE_STRIPPED = "stripped.tiff"; /** * Packbits compressed TIFF test file */ public static final String FILE_PACKBITS = "packbits.tiff"; /** * LZW compressed TIFF test file */ public static final String FILE_LZW = "lzw.tiff"; /** * Tiled TIFF test file */ public static final String FILE_TILED = "tiled.tiff"; /** * Float 32 TIFF test file */ public static final String FILE_FLOAT32 = "float32.tiff"; /** * Float 64 TIFF test file */ public static final String FILE_FLOAT64 = "float64.tiff"; /** * Int 32 TIFF test file */ public static final String FILE_INT32 = "int32.tiff"; /** * Unsigned Int 32 TIFF test file */ public static final String FILE_UINT32 = "uint32.tiff"; /** * Interleave TIFF test file */ public static final String FILE_INTERLEAVE = "interleave.tiff"; /** * Tiled Planar TIFF test file */ public static final String FILE_TILED_PLANAR = "tiledplanar.tiff"; }
package com.example.jpro; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.view.View; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton; public class UserGoogleMaps extends AppCompatActivity { SupportMapFragment supportMapFragment; FusedLocationProviderClient client; String refnum = ""; String enufullname = ""; String houseowner = ""; Double lat; Double lon; ExtendedFloatingActionButton fab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_google_maps); fab = findViewById(R.id.extended_fab); Bundle bundle = getIntent().getExtras(); if (bundle != null) { refnum = bundle.getString("refNum"); enufullname = bundle.getString("enufullname"); houseowner = bundle.getString("houseowner"); // Log.d("wele", "onCreate: "+enufullname); // Log.d("wele", "onCreate: "+refnum); // Log.d("wele", "onCreate: "+houseowner); } supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapfragment); //initialize fused location client = LocationServices.getFusedLocationProviderClient(this); //check permission if (ActivityCompat.checkSelfPermission(UserGoogleMaps.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED | ActivityCompat.checkSelfPermission(UserGoogleMaps.this, Manifest.permission.ACCESS_COARSE_LOCATION) ==PackageManager.PERMISSION_GRANTED ) { //call location getCurrentLocation(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44); } fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle bundle = new Bundle(); bundle.putString("refNum", refnum); bundle.putString("enufullname", enufullname); bundle.putString("houseowner", houseowner); bundle.putDouble("lat", lat); bundle.putDouble("lon", lon); Intent intent = new Intent(UserGoogleMaps.this, General_Information_Form2.class); intent.putExtras(bundle); startActivity(intent); } }); } private void getCurrentLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED | ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44); Task<Location> task = client.getLastLocation(); } Task<Location> task = client.getLastLocation(); task.addOnSuccessListener(new OnSuccessListener<Location>() { @Override public void onSuccess(final Location location) { //when success if (location != null){ //syn map supportMapFragment.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { //initialize latln LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); //create marker MarkerOptions options = new MarkerOptions() .position(latLng) .title("Current Location") .snippet(location.getLatitude()+" " + location.getLongitude()); //zoom in on map googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15)); //add marker googleMap.addMarker(options); lat = location.getLatitude(); lon = location.getLongitude(); } }); } else { Task<Location> task1 = client.getLastLocation(); } } }); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == 44){ if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ //when permission granted //call method getCurrentLocation(); } } } }
package fake.package_5; public class Foo3 { public void foo0(){ new Foo2().foo49(); } public void foo1(){ foo0(); } public void foo2(){ foo1(); } public void foo3(){ foo2(); } public void foo4(){ foo3(); } public void foo5(){ foo4(); } public void foo6(){ foo5(); } public void foo7(){ foo6(); } public void foo8(){ foo7(); } public void foo9(){ foo8(); } public void foo10(){ foo9(); } public void foo11(){ foo10(); } public void foo12(){ foo11(); } public void foo13(){ foo12(); } public void foo14(){ foo13(); } public void foo15(){ foo14(); } public void foo16(){ foo15(); } public void foo17(){ foo16(); } public void foo18(){ foo17(); } public void foo19(){ foo18(); } public void foo20(){ foo19(); } public void foo21(){ foo20(); } public void foo22(){ foo21(); } public void foo23(){ foo22(); } public void foo24(){ foo23(); } public void foo25(){ foo24(); } public void foo26(){ foo25(); } public void foo27(){ foo26(); } public void foo28(){ foo27(); } public void foo29(){ foo28(); } public void foo30(){ foo29(); } public void foo31(){ foo30(); } public void foo32(){ foo31(); } public void foo33(){ foo32(); } public void foo34(){ foo33(); } public void foo35(){ foo34(); } public void foo36(){ foo35(); } public void foo37(){ foo36(); } public void foo38(){ foo37(); } public void foo39(){ foo38(); } public void foo40(){ foo39(); } public void foo41(){ foo40(); } public void foo42(){ foo41(); } public void foo43(){ foo42(); } public void foo44(){ foo43(); } public void foo45(){ foo44(); } public void foo46(){ foo45(); } public void foo47(){ foo46(); } public void foo48(){ foo47(); } public void foo49(){ foo48(); } }
package exerc_lista01; import javax.swing.JOptionPane; public class Exercicio_31 { public Exercicio_31() { //Código do construtor } public static void Executar_Programa_31() { //Exercicio de fatoração usando laço de repetição int num = Integer.parseInt(JOptionPane.showInputDialog("Digite um número inteiro: ")), result = num; System.out.println("O fatorial de " + num + " é: " + num); //Laço para realizar a fatoração for (int i = num; i > 1; i--) { System.out.println("\t\t x " + (i - 1)); result *= i - 1; } System.out.println("Resultado da fatoração é: " + result + "\n"); System.exit(0); } }
package de.jcm.darkpowers.network; import de.jcm.darkpowers.DarkPowers; import net.minecraft.entity.player.EntityPlayerMP; import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.relauncher.Side; public class PacketDispatcher { private static byte packetId = 0; public static final void registerPackets() { PacketDispatcher.registerBiMessage(PacketSyncDarkPlayerData.Handler.class, PacketSyncDarkPlayerData.class); PacketDispatcher.registerMessage(PacketClientEffect.Handler.class, PacketClientEffect.class, Side.CLIENT); PacketDispatcher.registerMessage(PacketDarkAction.Handler.class, PacketDarkAction.class, Side.SERVER); } public static <REQ extends IMessage, REPLY extends IMessage> void registerMessage(Class<? extends IMessageHandler<REQ, REPLY>> messageHandler, Class<REQ> requestMessageType, Side side) { DarkPowers.wrapper.registerMessage(messageHandler, requestMessageType, packetId++, side); } public static final <REQ extends IMessage, REPLY extends IMessage> void registerMessage(Class<? extends IMessageHandler<REQ, REPLY>> handlerClass, Class<REQ> messageClass) { Side side = AbstractClientMessageHandler.class.isAssignableFrom(handlerClass) ? Side.CLIENT : Side.SERVER; DarkPowers.wrapper.registerMessage(handlerClass, messageClass, packetId++, side); } public static void sendToAll(IMessage message) { DarkPowers.wrapper.sendToAll(message); } public static void sendTo(IMessage message, EntityPlayerMP player) { DarkPowers.wrapper.sendTo(message, player); } public static void sendToAllAround(IMessage message, TargetPoint point) { DarkPowers.wrapper.sendToAllAround(message, point); } public static void sendToDimension(IMessage message, int dimensionId) { DarkPowers.wrapper.sendToDimension(message, dimensionId); } public static void sendToServer(IMessage message) { DarkPowers.wrapper.sendToServer(message); } public static final void registerBiMessage(Class handlerClass, Class messageClass) { if (AbstractBiMessageHandler.class.isAssignableFrom(handlerClass)) { DarkPowers.wrapper.registerMessage(handlerClass, messageClass, packetId, Side.CLIENT); DarkPowers.wrapper.registerMessage(handlerClass, messageClass, packetId++, Side.SERVER); } else { throw new IllegalArgumentException("Cannot register " + handlerClass.getName() + " on both sides - must extend AbstractBiMessageHandler!"); } } }
package com.example.weven.bankapp.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.example.weven.bankapp.Bean.FeedbackInfo; import com.example.weven.bankapp.Bean.RechargeSuccessful; import com.example.weven.bankapp.Bean.Url; import com.example.weven.bankapp.R; import com.example.weven.bankapp.util.HttpUtil; import com.example.weven.bankapp.util.IntentUtil; import com.example.weven.bankapp.util.ToastUtil; import com.example.weven.bankapp.util.okhttp.callback.ObjectCallBack; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.HashMap; import java.util.Map; import okhttp3.Call; public class Exchange1 extends BaseActivity { TextView importIn, tv_deposit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exchange1); importIn = (TextView) findViewById(R.id.importIn); tv_deposit = (TextView) findViewById(R.id.tv_deposit); EventBus.getDefault().register(Exchange1.this); initData(); importIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { IntentUtil.startActivity(Exchange1.this, RechargeActivity.class); } }); } @Override protected void initData() { Map<String, String> params = new HashMap<>(); params.put("token", BaseApplication.getToken()); params.put("id", BaseApplication.getCardId()); HttpUtil.postResponse(Url.getCurrentDeposit, params, this, new ObjectCallBack<FeedbackInfo>(FeedbackInfo.class) { @Override public void onSuccess(FeedbackInfo response) { if (response == null){ ToastUtil.showBottomToast(R.string.load_failure); }else { if (response.isSuccess()){ ToastUtil.showBottomToast(response.getMessage()); tv_deposit.setText(response.getData().toString()); }else { ToastUtil.showBottomToast(response.getMessage()); } } } @Override public void onFail(Call call, Exception e) { ToastUtil.showBottomToast(R.string.load_failure); } }); } @Subscribe(threadMode = ThreadMode.MAIN) public void refresh(RechargeSuccessful event){ initData(); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(Exchange1.this); } }
package de.c0debase.bot.commands.general; import de.c0debase.bot.commands.Command; import de.c0debase.bot.utils.Constants; import net.dv8tion.jda.core.entities.Message; public class SpongebobCommand extends Command { public SpongebobCommand() { super("spongebob", "Macht einen normalen Satz zu einem lustigen Spongebob Satz", Category.GENERAL); } @Override public void execute(String[] args, Message message) { if(args.length == 0){ message.getChannel().sendMessage( getEmbed(message.getGuild(), message.getAuthor()).setDescription("!spongebob [msg]").build()) .queue(); } else { String spongebob = ""; for(String splitted : String.join(" ", args).split("")){ if(Constants.RANDOM.nextBoolean()){ spongebob+= splitted.toUpperCase(); } else { spongebob+= splitted.toLowerCase(); } } message.getChannel().sendMessage(spongebob).queue(); } } }
/* * 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.google.android.exoplayer.chunk; import android.util.Log; import com.google.android.exoplayer.upstream.BandwidthMeter; import java.util.List; import java.util.Random; /** * Selects from a number of available formats during playback. */ public interface FormatEvaluator { static final int TRIGGER_INITIAL = 0; /** * The trigger for a format selection that was triggered by the user. */ static final int TRIGGER_MANUAL = 1; /** * The trigger for an adaptive format selection. */ static final int TRIGGER_ADAPTIVE = 2; /** * Implementations may define custom trigger codes greater than or equal to this value. */ static final int TRIGGER_CUSTOM_BASE = 10000; /** * Enables the evaluator. */ void enable(); /** * Disables the evaluator. */ void disable(); /** * Update the supplied evaluation. * <p> * When the method is invoked, {@code evaluation} will contain the currently selected * format (null for the first evaluation), the most recent trigger (TRIGGER_INITIAL for the * first evaluation) and the current queue size. The implementation should update these * fields as necessary. * <p> * The trigger should be considered "sticky" for as long as a given representation is selected, * and so should only be changed if the representation is also changed. * * @param queue A read only representation of the currently buffered {@link MediaChunk}s. * @param playbackPositionUs The current playback position. * @param formats The formats from which to select, ordered by decreasing bandwidth. * @param evaluation The evaluation. */ // TODO: Pass more useful information into this method, and finalize the interface. void evaluate(List<? extends MediaChunk> queue, long playbackPositionUs, Format[] formats, Evaluation evaluation); /** * A format evaluation. */ public static final class Evaluation { /** * The desired size of the queue. */ public int queueSize; /** * The sticky reason for the format selection. */ public int trigger; /** * The selected format. */ public Format format; public Evaluation() { trigger = Chunk.TRIGGER_INITIAL; } } /** * Always selects the first format. */ public static final class FixedEvaluator implements FormatEvaluator { @Override public void enable() { // Do nothing. } @Override public void disable() { // Do nothing. } @Override public void evaluate(List<? extends MediaChunk> queue, long playbackPositionUs, Format[] formats, Evaluation evaluation) { evaluation.format = formats[0]; } } /** * Selects randomly between the available formats. */ public static final class RandomEvaluator implements FormatEvaluator { private final Random random; public RandomEvaluator() { this.random = new Random(); } /** * @param seed A seed for the underlying random number generator. */ public RandomEvaluator(int seed) { this.random = new Random(seed); } @Override public void enable() { // Do nothing. } @Override public void disable() { // Do nothing. } @Override public void evaluate(List<? extends MediaChunk> queue, long playbackPositionUs, Format[] formats, Evaluation evaluation) { Format newFormat = formats[random.nextInt(formats.length)]; if (evaluation.format != null && !evaluation.format.equals(newFormat)) { evaluation.trigger = Chunk.TRIGGER_ADAPTIVE; } evaluation.format = newFormat; } } /** * An adaptive evaluator for video formats, which attempts to select the best quality possible * given the current network conditions and state of the buffer. * <p> * This implementation should be used for video only, and should not be used for audio. It is a * reference implementation only. It is recommended that application developers implement their * own adaptive evaluator to more precisely suit their use case. */ public static final class AdaptiveEvaluator implements FormatEvaluator { public static final int DEFAULT_MAX_INITIAL_BITRATE = 800000; public static final int DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS = 10000; public static final int DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS = 25000; public static final int DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS = 25000; public static final float DEFAULT_BANDWIDTH_FRACTION = 0.75f; private final BandwidthMeter bandwidthMeter; private final int maxInitialBitrate; private final long minDurationForQualityIncreaseUs; private final long maxDurationForQualityDecreaseUs; private final long minDurationToRetainAfterDiscardUs; private final float bandwidthFraction; private boolean isInit = true; /** * @param bandwidthMeter Provides an estimate of the currently available bandwidth. */ public AdaptiveEvaluator(BandwidthMeter bandwidthMeter) { this (bandwidthMeter, DEFAULT_MAX_INITIAL_BITRATE, DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS, DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS, DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS, DEFAULT_BANDWIDTH_FRACTION); } /** * @param bandwidthMeter Provides an estimate of the currently available bandwidth. * @param maxInitialBitrate The maximum bitrate in bits per second that should be assumed * when bandwidthMeter cannot provide an estimate due to playback having only just started. * @param minDurationForQualityIncreaseMs The minimum duration of buffered data required for * the evaluator to consider switching to a higher quality format. * @param maxDurationForQualityDecreaseMs The maximum duration of buffered data required for * the evaluator to consider switching to a lower quality format. * @param minDurationToRetainAfterDiscardMs When switching to a significantly higher quality * format, the evaluator may discard some of the media that it has already buffered at the * lower quality, so as to switch up to the higher quality faster. This is the minimum * duration of media that must be retained at the lower quality. * @param bandwidthFraction The fraction of the available bandwidth that the evaluator should * consider available for use. Setting to a value less than 1 is recommended to account * for inaccuracies in the bandwidth estimator. */ public AdaptiveEvaluator(BandwidthMeter bandwidthMeter, int maxInitialBitrate, int minDurationForQualityIncreaseMs, int maxDurationForQualityDecreaseMs, int minDurationToRetainAfterDiscardMs, float bandwidthFraction) { this.bandwidthMeter = bandwidthMeter; this.maxInitialBitrate = maxInitialBitrate; this.minDurationForQualityIncreaseUs = minDurationForQualityIncreaseMs * 1000L; this.maxDurationForQualityDecreaseUs = maxDurationForQualityDecreaseMs * 1000L; this.minDurationToRetainAfterDiscardUs = minDurationToRetainAfterDiscardMs * 1000L; this.bandwidthFraction = bandwidthFraction; } @Override public void enable() { // Do nothing. } @Override public void disable() { // Do nothing. } //LLEEJ : Evalutation 발생 @Override public void evaluate(List<? extends MediaChunk> queue, long playbackPositionUs, Format[] formats, Evaluation evaluation) { long bufferedDurationUs = queue.isEmpty() ? 0 : queue.get(queue.size() - 1).endTimeUs - playbackPositionUs; Format current = evaluation.format; Format ideal = determineIdealFormat(formats, bandwidthMeter.getBitrateEstimate()); if(isInit) { for (int i = 0; i < formats.length; i++){ Log.d("LLEEJ","AVAILABLE FORMAT : " + formats[i].width +"x" + formats[i].height + " , " + formats[i].bitrate); } isInit = false; } boolean isHigher = ideal != null && current != null && ideal.bitrate > current.bitrate; // ideal boolean isLower = ideal != null && current != null && ideal.bitrate < current.bitrate; if (isHigher) { if (bufferedDurationUs < minDurationForQualityIncreaseUs) { // The ideal format is a higher quality, but we have insufficient buffer to // safely switch up. Defer switching up for now. ideal = current; } else if (bufferedDurationUs >= minDurationToRetainAfterDiscardUs) { // We're switching from an SD stream to a stream of higher resolution. Consider // discarding already buffered media chunks. Specifically, discard media chunks starting // from the first one that is of lower bandwidth, lower resolution and that is not HD. for (int i = 1; i < queue.size(); i++) { MediaChunk thisChunk = queue.get(i); long durationBeforeThisSegmentUs = thisChunk.startTimeUs - playbackPositionUs; if (durationBeforeThisSegmentUs >= minDurationToRetainAfterDiscardUs && thisChunk.format.bitrate < ideal.bitrate && thisChunk.format.height < ideal.height && thisChunk.format.height < 720 && thisChunk.format.width < 1280) { // Discard chunks from this one onwards. evaluation.queueSize = i; break; } } } } else if (isLower && current != null && bufferedDurationUs >= maxDurationForQualityDecreaseUs) { // The ideal format is a lower quality, but we have sufficient buffer to defer switching // down for now. ideal = current; } if (current != null && ideal != current) { evaluation.trigger = Chunk.TRIGGER_ADAPTIVE; } isInit = false; evaluation.format = ideal; } /** * Compute the ideal format ignoring buffer health. */ private Format determineIdealFormat(Format[] formats, long bitrateEstimate) { long effectiveBitrate = bitrateEstimate == BandwidthMeter.NO_ESTIMATE ? maxInitialBitrate : (long) (bitrateEstimate * bandwidthFraction); for (int i = 0; i < formats.length; i++) { Format format = formats[i]; if (format.bitrate <= effectiveBitrate) { return format; } } // We didn't manage to calculate a suitable format. Return the lowest quality format. return formats[formats.length - 1]; } } public static final class AdaptiveEvaluatorTest implements FormatEvaluator { public static final int DEFAULT_MAX_INITIAL_BITRATE = 800000; public static final int DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS = 10000; public static final int DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS = 25000; public static final int DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS = 25000; public static final float DEFAULT_BANDWIDTH_FRACTION = 0.75f; private final BandwidthMeter bandwidthMeter; private final int maxInitialBitrate; private final long minDurationForQualityIncreaseUs; private final long maxDurationForQualityDecreaseUs; private final long minDurationToRetainAfterDiscardUs; private final float bandwidthFraction; /** * @param bandwidthMeter Provides an estimate of the currently available bandwidth. */ public AdaptiveEvaluatorTest(BandwidthMeter bandwidthMeter) { this(bandwidthMeter, DEFAULT_MAX_INITIAL_BITRATE, DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS, DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS, DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS, DEFAULT_BANDWIDTH_FRACTION); } /** * @param bandwidthMeter Provides an estimate of the currently available bandwidth. * @param maxInitialBitrate The maximum bitrate in bits per second that should be assumed * when bandwidthMeter cannot provide an estimate due to playback having only just started. * @param minDurationForQualityIncreaseMs The minimum duration of buffered data required for * the evaluator to consider switching to a higher quality format. * @param maxDurationForQualityDecreaseMs The maximum duration of buffered data required for * the evaluator to consider switching to a lower quality format. * @param minDurationToRetainAfterDiscardMs When switching to a significantly higher quality * format, the evaluator may discard some of the media that it has already buffered at the * lower quality, so as to switch up to the higher quality faster. This is the minimum * duration of media that must be retained at the lower quality. * @param bandwidthFraction The fraction of the available bandwidth that the evaluator should * consider available for use. Setting to a value less than 1 is recommended to account * for inaccuracies in the bandwidth estimator. */ public AdaptiveEvaluatorTest(BandwidthMeter bandwidthMeter, int maxInitialBitrate, int minDurationForQualityIncreaseMs, int maxDurationForQualityDecreaseMs, int minDurationToRetainAfterDiscardMs, float bandwidthFraction) { this.bandwidthMeter = bandwidthMeter; this.maxInitialBitrate = maxInitialBitrate; this.minDurationForQualityIncreaseUs = minDurationForQualityIncreaseMs * 1000L; this.maxDurationForQualityDecreaseUs = maxDurationForQualityDecreaseMs * 1000L; this.minDurationToRetainAfterDiscardUs = minDurationToRetainAfterDiscardMs * 1000L; this.bandwidthFraction = bandwidthFraction; } @Override public void enable() { // Do nothing. } @Override public void disable() { // Do nothing. } //LLEEJ : Evalutation 발생 @Override public void evaluate(List<? extends MediaChunk> queue, long playbackPositionUs, Format[] formats, Evaluation evaluation) { long bufferedDurationUs = queue.isEmpty() ? 0 : queue.get(queue.size() - 1).endTimeUs - playbackPositionUs; Format current = evaluation.format; Format ideal = determineIdealFormat(formats, bandwidthMeter.getBitrateEstimate()); //LLEEJ : //Format fixed = formats[0]; //Log.d("LLEEJ","ideal : " + ideal.height); boolean isHigher = ideal != null && current != null && ideal.bitrate > current.bitrate; // ideal boolean isLower = ideal != null && current != null && ideal.bitrate < current.bitrate; if (isHigher) { if (bufferedDurationUs < minDurationForQualityIncreaseUs) { // The ideal format is a higher quality, but we have insufficient buffer to // safely switch up. Defer switching up for now. ideal = current; } else if (bufferedDurationUs >= minDurationToRetainAfterDiscardUs) { // We're switching from an SD stream to a stream of higher resolution. Consider // discarding already buffered media chunks. Specifically, discard media chunks starting // from the first one that is of lower bandwidth, lower resolution and that is not HD. for (int i = 1; i < queue.size(); i++) { MediaChunk thisChunk = queue.get(i); long durationBeforeThisSegmentUs = thisChunk.startTimeUs - playbackPositionUs; if (durationBeforeThisSegmentUs >= minDurationToRetainAfterDiscardUs && thisChunk.format.bitrate < ideal.bitrate && thisChunk.format.height < ideal.height && thisChunk.format.height < 720 && thisChunk.format.width < 1280) { // Discard chunks from this one onwards. evaluation.queueSize = i; break; } } } } else if (isLower && current != null && bufferedDurationUs >= maxDurationForQualityDecreaseUs) { // The ideal format is a lower quality, but we have sufficient buffer to defer switching // down for now. ideal = current; } if (current != null && ideal != current) { evaluation.trigger = Chunk.TRIGGER_ADAPTIVE; } evaluation.format = ideal; } /** * Compute the ideal format ignoring buffer health. */ private Format determineIdealFormat(Format[] formats, long bitrateEstimate) { double newFraction = 1.2; long effectiveBitrate = bitrateEstimate == BandwidthMeter.NO_ESTIMATE ? maxInitialBitrate : (long) (bitrateEstimate * newFraction); for (int i = 0; i < formats.length; i++) { Format format = formats[i]; if (format.bitrate <= effectiveBitrate) { return format; } } // We didn't manage to calculate a suitable format. Return the lowest quality format. return formats[formats.length - 1]; } } }
/* * Copyright 2019-present Facebook, 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.facebook.buck.core.rules.platform; import com.facebook.buck.core.exceptions.DependencyStack; import com.facebook.buck.core.exceptions.HumanReadableException; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.platform.ConstraintResolver; import com.facebook.buck.core.model.platform.ConstraintValue; import com.facebook.buck.core.model.platform.NamedPlatform; import com.facebook.buck.core.model.platform.PlatformResolver; import com.facebook.buck.core.model.platform.impl.ConstraintBasedPlatform; import com.facebook.buck.core.rules.config.ConfigurationRule; import com.facebook.buck.core.rules.config.ConfigurationRuleResolver; import com.facebook.buck.core.util.graph.AcyclicDepthFirstPostOrderTraversalWithPayloadAndDependencyStack; import com.facebook.buck.core.util.graph.CycleException; import com.facebook.buck.core.util.graph.GraphTraversableWithPayloadAndDependencyStack; import com.facebook.buck.util.types.Pair; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.util.LinkedHashMap; public class RuleBasedPlatformResolver implements PlatformResolver { private final ConfigurationRuleResolver configurationRuleResolver; private final ConstraintResolver constraintResolver; public RuleBasedPlatformResolver( ConfigurationRuleResolver configurationRuleResolver, ConstraintResolver constraintResolver) { this.configurationRuleResolver = configurationRuleResolver; this.constraintResolver = constraintResolver; } @Override public NamedPlatform getPlatform(BuildTarget buildTarget, DependencyStack dependencyStack) { GraphTraversableWithPayloadAndDependencyStack<BuildTarget, PlatformRule> traversable = (target, dependencyStack1) -> { PlatformRule platformRule = getPlatformRule(target, dependencyStack1); return new Pair<>(platformRule, platformRule.getDeps().iterator()); }; AcyclicDepthFirstPostOrderTraversalWithPayloadAndDependencyStack<BuildTarget, PlatformRule> platformTraversal = new AcyclicDepthFirstPostOrderTraversalWithPayloadAndDependencyStack<>( traversable, DependencyStack::child); LinkedHashMap<BuildTarget, Pair<PlatformRule, DependencyStack>> platformTargets; try { platformTargets = platformTraversal.traverse(ImmutableList.of(buildTarget)); } catch (CycleException e) { throw new HumanReadableException(dependencyStack, e.getMessage()); } ImmutableSet<ConstraintValue> constraintValues = platformTargets.values().stream() .flatMap(t -> t.getFirst().getConstrainValues().stream()) .map( buildTarget1 -> constraintResolver.getConstraintValue( buildTarget1, dependencyStack.child(buildTarget1))) .collect(ImmutableSet.toImmutableSet()); return new ConstraintBasedPlatform(buildTarget, constraintValues); } private PlatformRule getPlatformRule(BuildTarget buildTarget, DependencyStack dependencyStack) { ConfigurationRule configurationRule = configurationRuleResolver.getRule(buildTarget, dependencyStack); if (!(configurationRule instanceof PlatformRule)) { throw new HumanReadableException( dependencyStack, "%s is used as a target platform, but not declared using `platform` rule", buildTarget.getFullyQualifiedName()); } return (PlatformRule) configurationRule; } }
/** * Copyright 2011-2013 Terracotta, Inc. * Copyright 2011-2013 Oracle, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jsr107.tck.annotations.cdi.test;
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2017 Eric Lafortune @ GuardSquare * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.obfuscate; import proguard.classfile.*; import proguard.classfile.util.*; import proguard.classfile.visitor.MemberVisitor; import java.util.*; /** * This MemberVisitor obfuscates all class members that it visits. * It uses names from the given name factory. At the same time, it avoids names * from the given descriptor map. * <p> * The class members must have been linked before applying this visitor. * * @see MethodLinker * * @author Eric Lafortune */ public class MemberObfuscator extends SimplifiedVisitor implements MemberVisitor { private final boolean allowAggressiveOverloading; private final NameFactory nameFactory; private final Map descriptorMap; /** * Creates a new MemberObfuscator. * @param allowAggressiveOverloading a flag that specifies whether class * members can be overloaded aggressively. * @param nameFactory the factory that can produce * obfuscated member names. * @param descriptorMap the map of descriptors to * [new name - old name] maps. */ public MemberObfuscator(boolean allowAggressiveOverloading, NameFactory nameFactory, Map descriptorMap) { this.allowAggressiveOverloading = allowAggressiveOverloading; this.nameFactory = nameFactory; this.descriptorMap = descriptorMap; } // Implementations for MemberVisitor. public void visitAnyMember(Clazz clazz, Member member) { // Special cases: <clinit> and <init> are always kept unchanged. // We can ignore them here. String name = member.getName(clazz); if (ClassUtil.isInitializer(name)) { return; } // Get the member's descriptor. String descriptor = member.getDescriptor(clazz); // Check whether we're allowed to overload aggressively. if (!allowAggressiveOverloading) { // Trim the return argument from the descriptor if not. // Works for fields and methods alike. descriptor = descriptor.substring(0, descriptor.indexOf(')')+1); } // Get the name map, creating a new one if necessary. Map nameMap = retrieveNameMap(descriptorMap, descriptor); // Get the member's new name. String newName = newMemberName(member); // Assign a new one, if necessary. if (newName == null) { // Find an acceptable new name. nameFactory.reset(); do { newName = nameFactory.nextName(); } while (nameMap.containsKey(newName)); // Remember not to use the new name again in this name space. nameMap.put(newName, name); // Assign the new name. setNewMemberName(member, newName); } } // Small utility methods. /** * Gets the name map, based on the given map and a given descriptor. * A new empty map is created if necessary. * @param descriptorMap the map of descriptors to [new name - old name] maps. * @param descriptor the class member descriptor. * @return the corresponding name map. */ static Map retrieveNameMap(Map descriptorMap, String descriptor) { // See if we can find the nested map with this descriptor key. Map nameMap = (Map)descriptorMap.get(descriptor); // Create a new one if not. if (nameMap == null) { nameMap = new HashMap(); descriptorMap.put(descriptor, nameMap); } return nameMap; } /** * Assigns a fixed new name to the given class member. * @param member the class member. * @param name the new name. */ static void setFixedNewMemberName(Member member, String name) { VisitorAccepter lastVisitorAccepter = MethodLinker.lastVisitorAccepter(member); if (!(lastVisitorAccepter instanceof LibraryMember) && !(lastVisitorAccepter instanceof MyFixedName)) { lastVisitorAccepter.setVisitorInfo(new MyFixedName(name)); } else { lastVisitorAccepter.setVisitorInfo(name); } } /** * Assigns a new name to the given class member. * @param member the class member. * @param name the new name. */ static void setNewMemberName(Member member, String name) { MethodLinker.lastVisitorAccepter(member).setVisitorInfo(name); } /** * Returns whether the new name of the given class member is fixed. * @param member the class member. * @return whether its new name is fixed. */ static boolean hasFixedNewMemberName(Member member) { VisitorAccepter lastVisitorAccepter = MethodLinker.lastVisitorAccepter(member); return lastVisitorAccepter instanceof LibraryMember || lastVisitorAccepter instanceof MyFixedName; } /** * Retrieves the new name of the given class member. * @param member the class member. * @return the class member's new name, or <code>null</code> if it doesn't * have one yet. */ static String newMemberName(Member member) { return (String)MethodLinker.lastVisitorAccepter(member).getVisitorInfo(); } /** * This VisitorAccepter can be used to wrap a name string, to indicate that * the name is fixed. */ private static class MyFixedName implements VisitorAccepter { private String newName; public MyFixedName(String newName) { this.newName = newName; } // Implementations for VisitorAccepter. public Object getVisitorInfo() { return newName; } public void setVisitorInfo(Object visitorInfo) { newName = (String)visitorInfo; } } }
package org.poem.result; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; /** * @author poem */ public class ResponseResult<T> implements Serializable { @ApiModelProperty(value = "业务状态码") private Integer code; @ApiModelProperty(value = "有效数据") private T data; @ApiModelProperty(value = "消息") private String message; public ResponseResult() { this.code = 0; } public ResponseResult(T data) { this.data = data; this.code = 0; } public ResponseResult(Integer code, T data) { this.code = code; this.data = data; } public ResponseResult(Integer code, T data, String message) { this.code = code; this.data = data; this.message = message; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public T getData() { return data; } public void setData(T data) { this.data = data; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
package com.gl.userservice.exception.handler; import com.gl.userservice.exception.UserNotFoundException; import com.gl.userservice.model.ApiError; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @ControllerAdvice public class UserServiceExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { BindingResult bindingResult = ex.getBindingResult(); List<FieldError> fieldErrors = bindingResult.getFieldErrors(); List<String> errors = fieldErrors .stream() .map(err -> err.getField() + ":" + err.getDefaultMessage()) .collect(Collectors.toList()); ApiError apiError = new ApiError(); apiError.setErrors(errors); apiError.setStatus(HttpStatus.BAD_REQUEST); apiError.setPath(request.getDescription(false)); return new ResponseEntity<>( apiError, new HttpHeaders(), apiError.getStatus()); } @ExceptionHandler({ConstraintViolationException.class}) public ResponseEntity<Object> handleConstraintViolation( ConstraintViolationException ex, ServletWebRequest request) { Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations(); List<String> errors = constraintViolations .stream() .map(err -> err.getRootBeanClass().getName() + " " + err.getPropertyPath() + ": " + err.getMessage()) .collect(Collectors.toList()); ApiError apiError = new ApiError(); apiError.setErrors(errors); apiError.setStatus(HttpStatus.BAD_REQUEST); apiError.setPath(request.getRequest().getRequestURI()); return new ResponseEntity<>( apiError, new HttpHeaders(), apiError.getStatus()); } @ExceptionHandler public ResponseEntity<Object> userNotFoundException(UserNotFoundException ex, ServletWebRequest request){ ApiError apiError = new ApiError(); apiError.setErrors(List.of(ex.getMessage())); apiError.setStatus(HttpStatus.NOT_FOUND); apiError.setPath(request.getRequest().getRequestURI()); return new ResponseEntity<>( apiError, new HttpHeaders(), apiError.getStatus()); } }
/* * Copyright 2010-2018 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 software.amazon.awssdk.core.client.handler; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.Request; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.http.SdkHttpFullRequestAdapter; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptorChain; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.internal.http.response.SdkErrorResponseHandler; import software.amazon.awssdk.http.SdkHttpFullRequest; @SdkProtectedApi public abstract class BaseClientHandler { private SdkClientConfiguration clientConfiguration; protected BaseClientHandler(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } static <InputT extends SdkRequest> InputT finalizeSdkRequest(ExecutionContext executionContext) { runBeforeExecutionInterceptors(executionContext); return runModifyRequestInterceptors(executionContext); } static <InputT extends SdkRequest, OutputT> SdkHttpFullRequest finalizeSdkHttpFullRequest( ClientExecutionParams<InputT, OutputT> executionParams, ExecutionContext executionContext, InputT inputT, SdkClientConfiguration clientConfiguration) { runBeforeMarshallingInterceptors(executionContext); Request<InputT> request = executionParams.getMarshaller().marshall(inputT); request.setEndpoint(clientConfiguration.option(SdkClientOption.ENDPOINT)); executionContext.executionAttributes().putAttribute(SdkExecutionAttribute.SERVICE_NAME, request.getServiceName()); addHttpRequest(executionContext, SdkHttpFullRequestAdapter.toHttpFullRequest(request)); runAfterMarshallingInterceptors(executionContext); return runModifyHttpRequestInterceptors(executionContext); } private static void runBeforeExecutionInterceptors(ExecutionContext executionContext) { executionContext.interceptorChain().beforeExecution(executionContext.interceptorContext(), executionContext.executionAttributes()); } private static <T> T runModifyRequestInterceptors(ExecutionContext executionContext) { InterceptorContext interceptorContext = executionContext.interceptorChain().modifyRequest(executionContext.interceptorContext(), executionContext.executionAttributes()); executionContext.interceptorContext(interceptorContext); return (T) interceptorContext.request(); } private static void runBeforeMarshallingInterceptors(ExecutionContext executionContext) { executionContext.interceptorChain().beforeMarshalling(executionContext.interceptorContext(), executionContext.executionAttributes()); } private static void addHttpRequest(ExecutionContext executionContext, SdkHttpFullRequest request) { InterceptorContext interceptorContext = executionContext.interceptorContext().copy(b -> b.httpRequest(request)); executionContext.interceptorContext(interceptorContext); } private static void runAfterMarshallingInterceptors(ExecutionContext executionContext) { executionContext.interceptorChain().afterMarshalling(executionContext.interceptorContext(), executionContext.executionAttributes()); } private static SdkHttpFullRequest runModifyHttpRequestInterceptors(ExecutionContext executionContext) { InterceptorContext interceptorContext = executionContext.interceptorChain().modifyHttpRequest(executionContext.interceptorContext(), executionContext.executionAttributes()); executionContext.interceptorContext(interceptorContext); return interceptorContext.httpRequest(); } private static <OutputT extends SdkResponse> OutputT runAfterUnmarshallingInterceptors(OutputT response, ExecutionContext context) { // Update interceptor context to include response InterceptorContext interceptorContext = context.interceptorContext().copy(b -> b.response(response)); context.interceptorChain().afterUnmarshalling(interceptorContext, context.executionAttributes()); interceptorContext = context.interceptorChain().modifyResponse(interceptorContext, context.executionAttributes()); // Store updated context context.interceptorContext(interceptorContext); return (OutputT) interceptorContext.response(); } static <OutputT extends SdkResponse> HttpResponseHandler<OutputT> interceptorCalling( HttpResponseHandler<OutputT> delegate, ExecutionContext context) { return (response, executionAttributes) -> runAfterUnmarshallingInterceptors(delegate.handle(response, executionAttributes), context); } protected static <InputT extends SdkRequest, OutputT> ClientExecutionParams<InputT, OutputT> addErrorResponseHandler( ClientExecutionParams<InputT, OutputT> params) { return params.withErrorResponseHandler( new SdkErrorResponseHandler(params.getErrorResponseHandler())); } protected <InputT extends SdkRequest, OutputT extends SdkResponse> ExecutionContext createExecutionContext( ClientExecutionParams<InputT, OutputT> params) { SdkRequest originalRequest = params.getInput(); ExecutionAttributes executionAttributes = new ExecutionAttributes() .putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, clientConfiguration.option(SdkClientOption.SERVICE_CONFIGURATION)); ExecutionInterceptorChain interceptorChain = new ExecutionInterceptorChain(clientConfiguration.option(SdkClientOption.EXECUTION_INTERCEPTORS)); return ExecutionContext.builder() .interceptorChain(interceptorChain) .interceptorContext(InterceptorContext.builder() .request(originalRequest) .build()) .executionAttributes(executionAttributes) .signer(clientConfiguration.option(SdkAdvancedClientOption.SIGNER)) .build(); } protected boolean isCalculateCrc32FromCompressedData() { return clientConfiguration.option(SdkClientOption.CRC32_FROM_COMPRESSED_DATA_ENABLED); } /** * Decorate response handlers by running after unmarshalling Interceptors and adding http response metadata. */ <OutputT extends SdkResponse> HttpResponseHandler<OutputT> decorateResponseHandlers( HttpResponseHandler<OutputT> delegate, ExecutionContext executionContext) { HttpResponseHandler<OutputT> interceptorCallingResponseHandler = interceptorCalling(delegate, executionContext); return new AttachHttpMetadataResponseHandler<>(interceptorCallingResponseHandler); } }
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; import ru.stqa.pft.addressbook.model.Contacts; import java.io.File; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.testng.Assert.assertEquals; public class ContactModificationTests extends TestBase { public void ensurePreconditions() { if (app.db().contacts().size() == 0) { app.contact().create(new ContactData().withFirstname("Ivan Ivanich").withLastname("Test").withAddress("Tara") .withEmail("i@test.ru").withEmail2("test@mail.ru").withEmail3("te@test.ru") .withPhonehome("2400").withPhonemobile("8565").withPhonework("223"), false); app.goTo().homePage(); } } @Test public void testContactModification() { File photo = new File("src/test/resources/123.png"); Contacts before = app.db().contacts(); ContactData modifiedContact = before.iterator().next(); ContactData contact = new ContactData() .withId(modifiedContact.getId()).withFirstname("Vanya").withLastname("Test").withAddress("Tara") .withEmail("i@test.ru").withEmail2("test@mail.ru").withEmail3("te@test.ru") .withPhonehome("2400").withPhonemobile("8565").withPhonework("223").withPhoto(photo); app.goTo().homePage(); app.contact().modify(contact); assertThat(app.contact().count(), equalTo(before.size())); Contacts after = app.db().contacts(); assertEquals(after.size(), before.size()); assertThat(after, equalTo(before.without(modifiedContact).withAdded(contact))); verifyContactListInUI(); } }
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.uibuilder.handlers.absolute; import com.android.SdkConstants; import com.android.tools.adtui.common.SwingCoordinate; import com.android.tools.idea.common.api.DragType; import com.android.tools.idea.common.api.InsertType; import com.android.tools.idea.common.scene.Placeholder; import com.android.tools.idea.uibuilder.api.*; import com.android.tools.idea.common.model.NlComponent; import com.android.tools.idea.common.scene.SceneComponent; import com.android.tools.idea.uibuilder.handlers.constraint.ConstraintDragHandler; import com.android.tools.idea.common.scene.SceneInteraction; import com.android.tools.idea.uibuilder.scene.target.ResizeBaseTarget; import com.android.tools.idea.common.scene.target.Target; import com.android.tools.idea.common.surface.Interaction; import com.android.tools.idea.uibuilder.surface.ScreenView; import com.google.common.collect.ImmutableList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; /** * Handler for {@link com.android.SdkConstants#ABSOLUTE_LAYOUT} */ public class AbsoluteLayoutHandler extends ViewGroupHandler { @Override @Nullable public DragHandler createDragHandler(@NotNull ViewEditor editor, @NotNull SceneComponent layout, @NotNull List<NlComponent> components, @NotNull DragType type) { return new ConstraintDragHandler(editor, this, layout, components, type); } @Override @Nullable public Interaction createInteraction(@NotNull ScreenView screenView, @SwingCoordinate int x, @SwingCoordinate int y, @NotNull NlComponent component) { return new SceneInteraction(screenView); } @Override public boolean handlesPainting() { return true; } @Override public void onChildRemoved(@NotNull ViewEditor editor, @NotNull NlComponent layout, @NotNull NlComponent newChild, @NotNull InsertType insertType) { newChild.removeAttribute(SdkConstants.ANDROID_URI, SdkConstants.ATTR_LAYOUT_X); newChild.removeAttribute(SdkConstants.ANDROID_URI, SdkConstants.ATTR_LAYOUT_Y); } @NotNull @Override public List<Target> createChildTargets(@NotNull SceneComponent parentComponent, @NotNull SceneComponent childComponent) { return ImmutableList.of( new AbsoluteDragTarget(), new AbsoluteResizeTarget(ResizeBaseTarget.Type.LEFT), new AbsoluteResizeTarget(ResizeBaseTarget.Type.LEFT_TOP), new AbsoluteResizeTarget(ResizeBaseTarget.Type.TOP), new AbsoluteResizeTarget(ResizeBaseTarget.Type.RIGHT_TOP), new AbsoluteResizeTarget(ResizeBaseTarget.Type.RIGHT), new AbsoluteResizeTarget(ResizeBaseTarget.Type.RIGHT_BOTTOM), new AbsoluteResizeTarget(ResizeBaseTarget.Type.BOTTOM), new AbsoluteResizeTarget(ResizeBaseTarget.Type.LEFT_BOTTOM) ); } @Override public List<Placeholder> getPlaceholders(@NotNull SceneComponent component) { return ImmutableList.of(new AbsolutePlaceholder(component)); } }
package com.googlecode.javaewah32.symmetric; import com.googlecode.javaewah.datastructure.BitSet; import com.googlecode.javaewah32.BitmapStorage32; import java.util.Iterator; import java.util.List; /** * This is a Java specification for an "updatable" Boolean function meant to run * over EWAH bitmaps. * * Reference: * * Daniel Lemire, Owen Kaser, Kamel Aouiche, Sorting improves word-aligned * bitmap indexes. Data &amp; Knowledge Engineering 69 (1), pages 3-28, 2010. * * @author Daniel Lemire * @since 0.8.2 */ public abstract class UpdateableBitmapFunction32 { EWAHPointer32[] rw = new EWAHPointer32[0]; int hammingWeight = 0; int litWeight = 0; boolean[] b = new boolean[0]; final BitSet litwlist = new BitSet(0); UpdateableBitmapFunction32() { } /** * @return the current number of literal words */ public final int getNumberOfLiterals() { return this.litwlist.cardinality(); } /** * Goes through the literals. * * @return an iterator */ public final Iterable<EWAHPointer32> getLiterals() { return new Iterable<EWAHPointer32>() { @Override public Iterator<EWAHPointer32> iterator() { return new Iterator<EWAHPointer32>() { int k = UpdateableBitmapFunction32.this.litwlist .nextSetBit(0); @Override public boolean hasNext() { return this.k >= 0; } @Override public EWAHPointer32 next() { EWAHPointer32 answer = UpdateableBitmapFunction32.this.rw[this.k]; this.k = UpdateableBitmapFunction32.this.litwlist .nextSetBit(this.k + 1); return answer; } @Override public void remove() { throw new RuntimeException( "N/A"); } }; } }; } /** * append to the list the literal words as EWAHPointer * * @param container where we write */ public final void fillWithLiterals(final List<EWAHPointer32> container) { for (int k = this.litwlist.nextSetBit(0); k >= 0; k = this.litwlist .nextSetBit(k + 1)) { container.add(this.rw[k]); } } /** * @param newsize the number of inputs */ public final void resize(final int newsize) { this.rw = java.util.Arrays.copyOf(this.rw, newsize); this.litwlist.resize(newsize); this.b = java.util.Arrays.copyOf(this.b, newsize); } /** * @param pos position of a literal */ public void setLiteral(final int pos) { if (!this.litwlist.get(pos)) { this.litwlist.set(pos); this.litWeight++; if (this.b[pos]) { this.b[pos] = false; --this.hammingWeight; } } } /** * @param pos position where a literal was removed */ public void clearLiteral(final int pos) { if (this.litwlist.get(pos)) { // litwlist.unset(pos); this.litwlist.set(pos, false); this.litWeight--; } } /** * @param pos position where a zero word was added */ public final void setZero(final int pos) { if (this.b[pos]) { this.b[pos] = false; --this.hammingWeight; } else { clearLiteral(pos); } } /** * @param pos position were a 11...1 word was added */ public final void setOne(final int pos) { if (!this.b[pos]) { clearLiteral(pos); this.b[pos] = true; ++this.hammingWeight; } } /** * Writes out the answer. * * @param out output buffer * @param runBegin beginning of the run * @param runend end of the run */ public abstract void dispatch(BitmapStorage32 out, int runBegin, int runend); }
package com.github.demo2; /** * @author 许大仙 * @version 1.0 * @since 2021-10-14 10:05 */ public class Test { public static void main(String[] args) { Runnable runnable = new SubRunnable(); Thread t1 = new Thread(runnable); Thread t2 = new Thread(runnable); t1.start(); t2.start(); } }
package myGameEngine.util; import ray.rml.Vector3; public class MovementUtils { private MovementUtils() {} // deny construction /** * Determine if the separation between object 1 and object 2 is permissible, * as specified by the maxSeparation passed into the method. * * @param obj1 Object 1 * @param obj2 Object 2 * @param maxSeparation the maximum allowed separation * @return True if the separation is within the limit specified, or false if outside the max limit. */ public static boolean validateSeparation(Vector3 obj1, Vector3 obj2, float maxSeparation) { final float o1X = obj1.x(); final float o1Y = obj1.y(); final float o1Z = obj1.z(); final float o2X = obj2.x(); final float o2Y = obj2.y(); final float o2Z = obj2.z(); // use distance formula to calculate separation final double distance = Math.sqrt( Math.pow((o1X - o2X), 2) + Math.pow((o1Y - o2Y), 2) + Math.pow((o1Z - o2Z), 2)); return (distance > maxSeparation) ? false : true; } }
package uk.gov.hmcts.reform.divorce.model.parties; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Arrays; public enum DivorceParty { PETITIONER("petitioner"), RESPONDENT("respondent"), CO_RESPONDENT("co-respondent"); private final String description; DivorceParty(String description) { this.description = description; } public static DivorceParty getDivorcePartyByDescription(String description) throws DivorcePartyNotFoundException { return Arrays.stream(DivorceParty.values()) .filter(d -> d.description.equals(description)) .findFirst() .orElseThrow(() -> new DivorcePartyNotFoundException(description)); } @JsonValue public String getDescription() { return description; } }
/* * Copyright 2018 Syam Pillai * * 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.storedobject.common; import java.io.BufferedWriter; import java.io.FilterReader; import java.io.Reader; import java.util.Objects; /** * A {@link java.io.FilterReader} that translates its stream on-the-fly. * * @author Syam */ public abstract class TranslatedReader extends FilterReader { private final InputOutputStream inout; protected final Reader in; protected final BufferedWriter out; /** * Creates a new translated reader. * * @param in Reader object providing the underlying stream. */ protected TranslatedReader(Reader in) { this(new InputOutputStream(), in); } private TranslatedReader(InputOutputStream inout, Reader in) { super(Objects.requireNonNull(IO.getReader(inout.getInputStream()))); this.inout = inout; this.in = in; this.out = IO.getWriter(inout.getOutputStream()); Executor.execute(this::xlate); } private void xlate() { try { translate(); } catch (Exception e) { inout.setExternalException(e); } finally { IO.close(in, out); } } /** * Translation should be done here. Original reader is available in the variable <code>in</code> and * the translated output should be written to the {@link BufferedWriter} (variable <code>out</code>). * * @throws Exception Throws any exception so that the ultimate reading program will get it. */ protected abstract void translate() throws Exception; }
package ma.glasnost.orika.test.community; import ma.glasnost.orika.MapperFactory; import ma.glasnost.orika.impl.DefaultMapperFactory; import org.junit.Test; public class Issue161TestCase { public static class Optional<T> { } public static class Range<C extends Comparable<C>> { } public static class SelfReferencingGenericType<T extends SelfReferencingGenericType<T>> { public Optional<Range<String>> getOptionalStringRange() { return null; } } public static class Foo extends SelfReferencingGenericType<Foo> { } @Test public void mapSelfReferencingGenericType() { MapperFactory factory = new DefaultMapperFactory.Builder().build(); factory.classMap(Foo.class, String.class).byDefault().register(); } }
package com.android.samples.arch.componentsbasicsample.ui.news; import android.content.Context; import android.widget.ImageView; import android.widget.TextView; import com.android.samples.arch.componentsbasicsample.R; import com.android.samples.arch.componentsbasicsample.model.InfiniteFeedInfo; import com.bumptech.glide.Glide; import com.mindorks.placeholderview.annotations.Layout; import com.mindorks.placeholderview.annotations.Resolve; import com.mindorks.placeholderview.annotations.View; /** * Created by janisharali on 24/08/16. */ @Layout(R.layout.load_more_item_view) public class ItemView { @View(R.id.titleTxt) TextView titleTxt; @View(R.id.captionTxt) TextView captionTxt; @View(R.id.timeTxt) TextView timeTxt; @View(R.id.imageView) ImageView imageView; private InfiniteFeedInfo mInfo; private Context mContext; public ItemView(Context context, InfiniteFeedInfo info) { mContext = context; mInfo = info; } @Resolve public void onResolved() { titleTxt.setText(mInfo.getTitle()); captionTxt.setText(mInfo.getCaption()); timeTxt.setText(mInfo.getTime()); Glide.with(mContext).load(mInfo.getImageUrl()).into(imageView); } public InfiniteFeedInfo getInfo() { return mInfo; } }
package com.github.charlemaznable.guardians.context; public interface GuardEmptyContext { String contextValue(); }
package tech.aomi.cloud.gateway.repository; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import tech.aomi.cloud.gateway.entity.SystemAllowToken; /** * @author Sean createAt 2021/6/25 */ @Repository public interface SystemAllowTokenRepository extends MongoRepository<SystemAllowToken, String> { boolean existsByToken(String token); }
package models; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.prefs.Preferences; public class Address { private int addressId; private String area , phaseBlockGali,houseNumber; private int floor ; private Colony colony ; public Address() { } public Address(int addressId, String area, String phaseBlockGali, String houseNumber, int floor, Colony colony) { this.addressId = addressId; this.area = area; this.phaseBlockGali = phaseBlockGali; this.houseNumber = houseNumber; this.floor = floor; this.colony = colony; } public int getAddressId() { return addressId; } public String getArea() { return area; } public Colony getColony() { return colony; } public int getFloor() { return floor; } public String getHouseNumber() { return houseNumber; } public String getPhaseBlockGali() { return phaseBlockGali; } public void setAddressId(int addressId) { this.addressId = addressId; } public void setArea(String area) { this.area = area; } public void setColony(Colony colony) { this.colony = colony; } public void setFloor(int floor) { this.floor = floor; } public void setHouseNumber(String houseNumber) { this.houseNumber = houseNumber; } public void setPhaseBlockGali(String phaseBlockGali) { this.phaseBlockGali = phaseBlockGali; } @Override public String toString() { String s = addressId +" ## "+ area +" ## "+ phaseBlockGali +" ##" + " "+ floor +" ## "+ houseNumber +" ## "+ colony ; return s; //To change body of generated methods, choose Tools | Templates. } // database communication private static Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Preferences prefs = Preferences.userRoot(); String host = prefs.get("host", ""); String user = prefs.get("user", ""); String password = prefs.get("password", ""); Connection con = DriverManager.getConnection("jdbc:mysql://"+host+"/jms" , user , password); //Connection con = DriverManager.getConnection("jdbc:mysql://192.168.42.47/jms" , "root1" , "1234"); return con; } public int saveAddress(){ try(Connection con = getConnection();){ String query = "insert into addresses(area , phase_block_gali ,colony_id , floor , house_number) " + " value (?,?,?,?,?)"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, area); ps.setString(2 , phaseBlockGali.toUpperCase()); ps.setInt(3, colony.getId()); ps.setInt(4 , floor); ps.setString(5 , houseNumber); int result = ps.executeUpdate(); if(result>0){ query = "select max(address_id) as max from addresses"; ps = con.prepareStatement(query); ResultSet rs = ps.executeQuery(); while(rs.next()){ return rs.getInt(1); } } con.close(); }catch(ClassNotFoundException | SQLException ex){ return -1; } return -1; } public static Address getAddress(int id){ try(Connection con = getConnection();){ String query = "select area , phase_block_gali ,colony_id , floor , house_number " + "from addresses where address_id = (?)"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); while(rs.next()){ Address addr = new Address(); addr.setAddressId(id); addr.setArea(rs.getString(1)); addr.setPhaseBlockGali(rs.getString(2)); addr.setColony(Colony.getColony(rs.getInt(3))); addr.setFloor(rs.getInt(4)); addr.setHouseNumber(rs.getString(5)); return addr; } con.close(); }catch(ClassNotFoundException | SQLException ex){ ex.printStackTrace(); return null; } return null; } public static ArrayList<Address> getAddressesByColony(int colonyId){ ArrayList<Address> addrs = new ArrayList(); try(Connection con = getConnection();){ String query = "select area , phase_block_gali ,colony_id , floor , house_number , address_id " + "from addresses where colony_id = ?"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, colonyId); ResultSet rs = ps.executeQuery(); while(rs.next()){ Address addr = new Address(); addr.setArea(rs.getString(1)); addr.setPhaseBlockGali(rs.getString(2)); addr.setColony(Colony.getColony(rs.getInt(3))); addr.setFloor(rs.getInt(4)); addr.setHouseNumber(rs.getString(5)); addr.setAddressId(rs.getInt(6)); addrs.add(addr); } con.close(); }catch(ClassNotFoundException | SQLException ex){ ex.printStackTrace(); return addrs; } return addrs; } public static ArrayList<Address> getAddresses(){ ArrayList<Address> addrs = new ArrayList(); try(Connection con = getConnection();){ String query = "select area , phase_block_gali ,colony_id , floor , house_number , address_id " + "from addresses"; PreparedStatement ps = con.prepareStatement(query); ResultSet rs = ps.executeQuery(); while(rs.next()){ Address addr = new Address(); addr.setArea(rs.getString(1)); addr.setPhaseBlockGali(rs.getString(2)); addr.setColony(Colony.getColony(rs.getInt(3))); addr.setFloor(rs.getInt(4)); addr.setHouseNumber(rs.getString(5)); addr.setAddressId(rs.getInt(6)); addrs.add(addr); } con.close(); }catch(ClassNotFoundException | SQLException ex){ ex.printStackTrace(); return addrs; } return addrs; } }
/* * Copyright 2014-2019 michael-simons.eu. * * 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 ac.simons.biking2.bikingpictures; import java.time.ZonedDateTime; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.rules.ExpectedException.none; /** * @author Michael J. Simons, 2014-05-23 */ public class BikingPictureEntityTest { @Rule public final ExpectedException expectedException = none(); @Test public void beanShouldWorkAsExpected() { // Test default constructor BikingPictureEntity bikingPicture; bikingPicture = new BikingPictureEntity(); Assert.assertEquals(bikingPicture, new BikingPictureEntity()); Assert.assertNull(bikingPicture.getExternalId()); Assert.assertNull(bikingPicture.getId()); Assert.assertNull(bikingPicture.getLink()); Assert.assertNull(bikingPicture.getPubDate()); final ZonedDateTime now = ZonedDateTime.now(); bikingPicture = new BikingPictureEntity("http://dailyfratze.de/fratzen/m/45644.jpg", now, "http://dailyfratze.de/michael/2014/1/12"); Assert.assertNotEquals(bikingPicture, new BikingPictureEntity()); Assert.assertNotEquals(bikingPicture, null); Assert.assertNotEquals(bikingPicture, "not equals"); Assert.assertEquals(Integer.valueOf(45644), bikingPicture.getExternalId()); Assert.assertNull(bikingPicture.getId()); Assert.assertEquals("http://dailyfratze.de/michael/2014/1/12", bikingPicture.getLink()); Assert.assertEquals(now.toOffsetDateTime(), bikingPicture.getPubDate()); final BikingPictureEntity bikingPicture2 = new BikingPictureEntity("http://dailyfratze.de/fratzen/m/45644.jpg", now, "http://dailyfratze.de/michael/2014/1/12"); Assert.assertEquals(bikingPicture, bikingPicture2); Assert.assertEquals(bikingPicture.hashCode(), bikingPicture2.hashCode()); } @Test public void shouldHandleInvalidGuidsGracefully() { this.expectedException.expect(InvalidGUIDException.class); final ZonedDateTime now = ZonedDateTime.now(); new BikingPictureEntity("http://www.heise.de", now, "http://www.heise.de"); } }
package com.test.testpro.model; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; import java.time.LocalDateTime; @MappedSuperclass @EntityListeners(AuditingEntityListener.class) public abstract class Auditable { @CreatedBy private String createdBy; @CreatedDate private LocalDateTime creationDate; @LastModifiedBy private String lastModifiedBy; @LastModifiedDate private LocalDateTime lastModifiedDate; public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public LocalDateTime getCreationDate() { return creationDate; } public void setCreationDate(LocalDateTime creationDate) { this.creationDate = creationDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public LocalDateTime getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(LocalDateTime lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } }
/* * Copyright 2013-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tools; import java.io.IOException; import java.net.URI; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.ResponseExtractor; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; /** * * RestTemplate that logs erroneous responses and throws AssertionsError on any connection * issues. * * @author Marcin Grzejszczak */ public class AssertingRestTemplate extends RestTemplate { private static final Log log = LogFactory.getLog(AssertingRestTemplate.class); public AssertingRestTemplate() { setErrorHandler(new DefaultResponseErrorHandler() { @Override public void handleError(ClientHttpResponse response) throws IOException { if (hasError(response)) { log.error("Response has status code [" + response.getStatusCode() + "] and text [" + response.getStatusText() + "])"); } } }); } @Override protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { try { return super.doExecute(url, method, requestCallback, responseExtractor); } catch (Exception e) { log.error("Exception occurred while sending the message to uri [" + url + "]. Exception [" + e.getCause() + "]"); throw new AssertionError(e); } } }
/* * Copyright 2017-present Open Networking Foundation * * 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.p4runtime.ctl; import com.google.common.collect.Lists; import com.google.common.testing.EqualsTester; import org.junit.Test; import org.onlab.util.ImmutableByteSequence; import org.onosproject.bmv2.model.Bmv2PipelineModelParser; import org.onosproject.net.pi.model.DefaultPiPipeconf; import org.onosproject.net.pi.model.PiPipeconf; import org.onosproject.net.pi.model.PiPipeconfId; import org.onosproject.net.pi.runtime.PiAction; import org.onosproject.net.pi.runtime.PiActionId; import org.onosproject.net.pi.runtime.PiActionParam; import org.onosproject.net.pi.runtime.PiActionParamId; import org.onosproject.net.pi.runtime.PiHeaderFieldId; import org.onosproject.net.pi.runtime.PiMatchKey; import org.onosproject.net.pi.runtime.PiTableEntry; import org.onosproject.net.pi.runtime.PiTableId; import org.onosproject.net.pi.runtime.PiTernaryFieldMatch; import org.slf4j.Logger; import p4.P4RuntimeOuterClass.Action; import p4.P4RuntimeOuterClass.TableEntry; import java.net.URL; import java.util.Collection; import java.util.Random; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.onlab.util.ImmutableByteSequence.copyFrom; import static org.onlab.util.ImmutableByteSequence.fit; import static org.onlab.util.ImmutableByteSequence.ofOnes; import static org.onosproject.net.pi.model.PiPipeconf.ExtensionType.BMV2_JSON; import static org.onosproject.net.pi.model.PiPipeconf.ExtensionType.P4_INFO_TEXT; import static org.onosproject.p4runtime.ctl.TableEntryEncoder.decode; import static org.onosproject.p4runtime.ctl.TableEntryEncoder.encode; import static org.slf4j.LoggerFactory.getLogger; //import org.onosproject.driver.pipeline.DefaultSingleTablePipeline; //import org.onosproject.drivers.bmv2.Bmv2DefaultInterpreter; public class TableEntryEncoderTest { private final Logger log = getLogger(getClass()); private static final String TABLE_0 = "table0"; private static final String SET_EGRESS_PORT = "set_egress_port"; private static final String PORT = "port"; private static final String ETHERNET = "ethernet"; private static final String DST_ADDR = "dstAddr"; private static final String SRC_ADDR = "srcAddr"; private static final String STANDARD_METADATA = "standard_metadata"; private static final String INGRESS_PORT = "ingress_port"; private static final String ETHER_TYPE = "etherType"; private final Random rand = new Random(); private final URL p4InfoUrl = this.getClass().getResource("/default.p4info"); private final URL jsonUrl = this.getClass().getResource("/default.json"); private final PiPipeconf defaultPipeconf = DefaultPiPipeconf.builder() .withId(new PiPipeconfId("mock")) .withPipelineModel(Bmv2PipelineModelParser.parse(jsonUrl)) // .addBehaviour(PiPipelineInterpreter.class, Bmv2DefaultInterpreter.class) .addExtension(P4_INFO_TEXT, p4InfoUrl) .addExtension(BMV2_JSON, jsonUrl) .build(); private final P4InfoBrowser browser = PipeconfHelper.getP4InfoBrowser(defaultPipeconf); private final ImmutableByteSequence ethAddr = fit(copyFrom(rand.nextInt()), 48); private final ImmutableByteSequence portValue = copyFrom((short) rand.nextInt()); private final PiHeaderFieldId ethDstAddrFieldId = PiHeaderFieldId.of(ETHERNET, DST_ADDR); private final PiHeaderFieldId ethSrcAddrFieldId = PiHeaderFieldId.of(ETHERNET, SRC_ADDR); private final PiHeaderFieldId inPortFieldId = PiHeaderFieldId.of(STANDARD_METADATA, INGRESS_PORT); private final PiHeaderFieldId ethTypeFieldId = PiHeaderFieldId.of(ETHERNET, ETHER_TYPE); private final PiActionParamId portParamId = PiActionParamId.of(PORT); private final PiActionId outActionId = PiActionId.of(SET_EGRESS_PORT); private final PiTableId tableId = PiTableId.of(TABLE_0); private final PiTableEntry piTableEntry = PiTableEntry .builder() .forTable(tableId) .withMatchKey(PiMatchKey.builder() .addFieldMatch(new PiTernaryFieldMatch(ethDstAddrFieldId, ethAddr, ofOnes(6))) .addFieldMatch(new PiTernaryFieldMatch(ethSrcAddrFieldId, ethAddr, ofOnes(6))) .addFieldMatch(new PiTernaryFieldMatch(inPortFieldId, portValue, ofOnes(2))) .addFieldMatch(new PiTernaryFieldMatch(ethTypeFieldId, portValue, ofOnes(2))) .build()) .withAction(PiAction .builder() .withId(outActionId) .withParameter(new PiActionParam(portParamId, portValue)) .build()) .withPriority(1) .withCookie(2) .build(); public TableEntryEncoderTest() throws ImmutableByteSequence.ByteSequenceTrimException { } @Test public void testP4InfoBrowser() throws Exception { P4InfoBrowser browser = PipeconfHelper.getP4InfoBrowser(defaultPipeconf); assertThat(browser.tables().hasName(TABLE_0), is(true)); assertThat(browser.actions().hasName(SET_EGRESS_PORT), is(true)); int tableId = browser.tables().getByName(TABLE_0).getPreamble().getId(); int actionId = browser.actions().getByName(SET_EGRESS_PORT).getPreamble().getId(); assertThat(browser.matchFields(tableId).hasName(STANDARD_METADATA + "." + INGRESS_PORT), is(true)); assertThat(browser.actionParams(actionId).hasName(PORT), is(true)); // TODO: improve, assert browsing other entities (counters, meters, etc.) } @Test public void testTableEntryEncoder() throws P4InfoBrowser.NotFoundException, ImmutableByteSequence.ByteSequenceTrimException { Collection<TableEntry> result = encode(Lists.newArrayList(piTableEntry), defaultPipeconf); assertThat(result, hasSize(1)); TableEntry tableEntryMsg = result.iterator().next(); Collection<PiTableEntry> decodedResults = decode(Lists.newArrayList(tableEntryMsg), defaultPipeconf); PiTableEntry decodedPiTableEntry = decodedResults.iterator().next(); // Test equality for decoded entry. new EqualsTester() .addEqualityGroup(piTableEntry, decodedPiTableEntry) .testEquals(); // Table ID. int p4InfoTableId = browser.tables().getByName(tableId.id()).getPreamble().getId(); int encodedTableId = tableEntryMsg.getTableId(); assertThat(encodedTableId, is(p4InfoTableId)); // Ternary match. byte[] encodedTernaryMatchValue = tableEntryMsg.getMatch(0).getTernary().getValue().toByteArray(); assertThat(encodedTernaryMatchValue, is(ethAddr.asArray())); Action actionMsg = tableEntryMsg.getAction().getAction(); // Action ID. int p4InfoActionId = browser.actions().getByName(outActionId.name()).getPreamble().getId(); int encodedActionId = actionMsg.getActionId(); assertThat(encodedActionId, is(p4InfoActionId)); // Action param ID. int p4InfoActionParamId = browser.actionParams(p4InfoActionId).getByName(portParamId.name()).getId(); int encodedActionParamId = actionMsg.getParams(0).getParamId(); assertThat(encodedActionParamId, is(p4InfoActionParamId)); // Action param value. byte[] encodedActionParam = actionMsg.getParams(0).getValue().toByteArray(); assertThat(encodedActionParam, is(portValue.asArray())); // TODO: improve, assert other field match types (ternary, LPM) } }
package org.hisp.dhis.trackedentity; /* * Copyright (c) 2004-2020, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.program.Program; import org.hisp.dhis.user.User; /** * @author Ameen Mohamed */ public interface TrackerOwnershipManager { String OWNERSHIP_ACCESS_DENIED = "OWNERSHIP_ACCESS_DENIED"; String PROGRAM_ACCESS_CLOSED = "PROGRAM_ACCESS_CLOSED"; /** * @param entityInstance The tracked entity instance object * @param program The program object * @param orgUnit The org unit that has to become the owner * @param skipAccessValidation whether ownership access validation has to be * skipped or not. */ void transferOwnership( TrackedEntityInstance entityInstance, Program program, OrganisationUnit orgUnit, boolean skipAccessValidation, boolean createIfNotExists ); /** * @param entityInstance The tracked entity instance object * @param program The program object * @param organisationUnit The org unit that has to become the owner */ void assignOwnership( TrackedEntityInstance entityInstance, Program program, OrganisationUnit organisationUnit, boolean skipAccessValidation, boolean overwriteIfExists ); /** * Check whether the user has access (as owner or has temporarily broken the * glass) for the tracked entity instance - program combination. * * @param user The user with which access has to be checked for. * @param entityInstance The tracked entity instance. * @param program The program. * @return true if the user has access, false otherwise. */ boolean hasAccess( User user, TrackedEntityInstance entityInstance, Program program ); /** * Grant temporary ownership for a user for a specific tei-program * combination * * @param entityInstance The tracked entity instance object * @param program The program object * @param user The user for which temporary access is granted. * @param reason The reason for requesting temporary ownership */ void grantTemporaryOwnership( TrackedEntityInstance entityInstance, Program program, User user, String reason ); }
/* * Copyright (c) 2008-2022, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.cp.internal.raft.exception; import com.hazelcast.cp.exception.CPSubsystemException; import com.hazelcast.cp.internal.raft.impl.RaftEndpoint; /** * A {@code CPSubsystemException} which is thrown when a member, which is * requested to be removed from a CP group, is not a member of that group * or is already removed from that group. * Handled internally. */ public class MemberDoesNotExistException extends CPSubsystemException { private static final long serialVersionUID = -6536728347770526039L; public MemberDoesNotExistException(RaftEndpoint member) { super("Member does not exist: " + member, null); } private MemberDoesNotExistException(String message, Throwable cause) { super(message, cause, null); } @Override public MemberDoesNotExistException wrap() { return new MemberDoesNotExistException(getMessage(), this); } }
/* * 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.isis.core.commons.lang; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; public final class ListExtensions { private static final String DEFAULT_DELIMITER = ","; private ListExtensions() { } public static <T> List<T> combineWith(final List<T> extendee, final List<T> list2) { final List<T> combinedList = Lists.newArrayList(); combinedList.addAll(extendee); combinedList.addAll(list2); return combinedList; } /** * Returns list1 with everything in list2, ignoring duplicates. */ public static <T> List<T> mergeWith(final List<T> extendee, final List<T> list2) { for (final T obj : list2) { if (!(extendee.contains(obj))) { extendee.add(obj); } } return extendee; } /** * @see #listToString(List, String) * @see #stringToList(String) */ public static String listToString(final List<String> list) { return listToString(list, DEFAULT_DELIMITER); } /** * @see #listToString(List, String) * @see #stringToList(String) */ public static String listToString(final List<String> list, final String delimiter) { if (list.size() == 0) { return null; } final StringBuilder buf = new StringBuilder(); boolean first = true; for (final String str : list) { if (first) { first = false; } else { buf.append(delimiter); } buf.append(str); } return buf.toString(); } /** * @see #stringToList(String, String) * @see #listToString(List) */ public static List<String> stringToList(final String commaSeparated) { return appendDelimitedStringToList(commaSeparated, new ArrayList<String>()); } /** * @see #stringToList(String) * @see #listToString(List, String) */ public static List<String> stringToList(final String delimited, final String delimiter) { return appendDelimitedStringToList(delimited, delimiter, new ArrayList<String>()); } /** * @see #appendDelimitedStringToList(String, String, List) */ public static List<String> appendDelimitedStringToList(final String commaSeparated, final List<String> list) { return appendDelimitedStringToList(commaSeparated, DEFAULT_DELIMITER, list); } public static List<String> appendDelimitedStringToList(final String delimited, final String delimiter, final List<String> list) { if (delimited == null) { return list; } final String[] optionValues = delimited.split(delimiter); list.addAll(Arrays.asList(optionValues)); return list; } // ////////////////////////////////////// public static <T> List<T> mutableCopy(final List<T> input) { return Lists.newArrayList(input != null? input: Collections.<T>emptyList()); } public static <T> List<T> mutableCopy(T[] arr) { return mutableCopy(arr != null? Arrays.asList(arr): Collections.<T>emptyList()) ; } public static <T> void insert(final List<T> list, final int insertionPoint, final T elementToInsert) { extend(list, insertionPoint); list.add(insertionPoint, elementToInsert); } public static <T> void adjust(final List<T> list, final int requiredLength) { extend(list, requiredLength); if(list.size() > requiredLength) { list.subList(requiredLength, list.size()).clear();; } } private static <T> void extend(final List<T> list, final int requiredLength) { for(int i=list.size(); i<requiredLength; i++) { list.add(null); } } public static <T> Collection<T> filtered(final List<Object> extendee, final Class<T> type) { return Collections2.transform( Collections2.filter(extendee, ClassPredicates.isOfType(type)), ClassFunctions.castTo(type)); } }
/** * iBizSys 5.0 机器人生产代码(不要直接修改当前代码) * http://www.ibizsys.net */ package com.sa.unip.app.ywsp.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import net.ibizsys.paas.appmodel.AppModelGlobal; import net.ibizsys.paas.appmodel.IApplicationModel; import net.ibizsys.paas.demodel.DEModelGlobal; import net.ibizsys.paas.demodel.IDataEntityModel; import net.ibizsys.paas.service.IService; import net.ibizsys.paas.service.ServiceGlobal; import net.ibizsys.paas.sysmodel.ISystemModel; import net.ibizsys.paas.sysmodel.SysModelGlobal; import net.ibizsys.paas.controller.ViewControllerGlobal; import net.ibizsys.paas.ctrlmodel.ICtrlModel; import net.ibizsys.paas.ctrlhandler.ICtrlHandler; import com.sa.unip.srv.UniPSampleSysModel; import com.sa.unip.app.appAppModel; /** * 视图[OA_CCSQCCSQLC_D_WFEditView3]控制类基类 * * !! 不要对此代码进行修改 */ @Controller @RequestMapping(value = "/app/ywsp/OA_CCSQCCSQLC_D_WFEditView3.do") public class OA_CCSQCCSQLC_D_WFEditView3Controller extends net.ibizsys.pswf.controller.WFEditView3ControllerBase { public OA_CCSQCCSQLC_D_WFEditView3Controller() throws Exception { super(); this.setId("2a22e01f3a2a334a365680b78f5d6b53"); this.setCaption("出差申请"); this.setTitle("出差申请工作流视图(出差申请流程)"); this.setCapLanResTag("DE.LNAME.QA_CCSQ"); this.setAccessUserMode(2); // this.setAttribute("UI.CTRL.DRTAB","TRUE"); // this.setAttribute("UI.CTRL.FORM","TRUE"); //显示数据信息栏 this.setAttribute("UI.SHOWDATAINFOBAR","TRUE"); // this.setAttribute("UI.CTRL.TOOLBAR","TRUE"); ViewControllerGlobal.registerViewController("/app/ywsp/OA_CCSQCCSQLC_D_WFEditView3.do",this); ViewControllerGlobal.registerViewController("com.sa.unip.app.ywsp.controller.OA_CCSQCCSQLC_D_WFEditView3Controller",this); } @Override protected void prepareViewParam() throws Exception { super.prepareViewParam(); this.setWFModel(this.getSystemModel().getWFModel("8E3B9638-79A4-4ED1-AFBD-1D87D5EFCC5F")); this.setDEWF(this.getDEModel().getDEWF("A9392098-5077-434E-A00E-4A4E1771CEA2")); } private UniPSampleSysModel uniPSampleSysModel; public UniPSampleSysModel getUniPSampleSysModel() { if(this.uniPSampleSysModel==null) { try { this.uniPSampleSysModel = (UniPSampleSysModel)SysModelGlobal.getSystem("com.sa.unip.srv.UniPSampleSysModel"); } catch(Exception ex) { } } return this.uniPSampleSysModel; } @Override public ISystemModel getSystemModel() { return this.getUniPSampleSysModel(); } private appAppModel appAppModel; public appAppModel getappAppModel() { if(this.appAppModel==null) { try { this.appAppModel = (appAppModel)AppModelGlobal.getApplication("com.sa.unip.app.appAppModel"); } catch(Exception ex) { } } return this.appAppModel; } @Override public IApplicationModel getAppModel() { return this.getappAppModel(); } private com.sa.unip.srv.ywsp.demodel.OA_CCSQDEModel oA_CCSQDEModel; public com.sa.unip.srv.ywsp.demodel.OA_CCSQDEModel getOA_CCSQDEModel() { if(this.oA_CCSQDEModel==null) { try { this.oA_CCSQDEModel = (com.sa.unip.srv.ywsp.demodel.OA_CCSQDEModel)DEModelGlobal.getDEModel("com.sa.unip.srv.ywsp.demodel.OA_CCSQDEModel"); } catch(Exception ex) { } } return this.oA_CCSQDEModel; } public IDataEntityModel getDEModel() { return this.getOA_CCSQDEModel(); } public com.sa.unip.srv.ywsp.service.OA_CCSQService getOA_CCSQService() { try { return (com.sa.unip.srv.ywsp.service.OA_CCSQService)ServiceGlobal.getService("com.sa.unip.srv.ywsp.service.OA_CCSQService",this.getSessionFactory()); } catch(Exception ex) { return null; } } /* (non-Javadoc) * @see net.ibizsys.paas.controller.IViewController#getService() */ @Override public IService getService() { return getOA_CCSQService(); } /** * 准备部件模型 * @throws Exception */ @Override protected void prepareCtrlModels()throws Exception { //注册 drtab ICtrlModel drTab=(ICtrlModel)getUniPSampleSysModel().createObject("com.sa.unip.app.srv.ywsp.ctrlmodel.OA_CCSQCCSQLCDRDRTabModel"); drTab.init(this); this.registerCtrlModel("drtab",drTab); //注册 form ICtrlModel editForm=(ICtrlModel)getUniPSampleSysModel().createObject("com.sa.unip.app.srv.ywsp.ctrlmodel.OA_CCSQMainEditFormModel"); editForm.init(this); this.registerCtrlModel("form",editForm); } /** * 准备部件处理对象 * @throws Exception */ @Override protected void prepareCtrlHandlers()throws Exception { //注册 drtab ICtrlHandler drTab = (ICtrlHandler)getUniPSampleSysModel().createObject("com.sa.unip.app.ywsp.ctrlhandler.OA_CCSQCCSQLC_D_WFEditView3DRTabHandler"); drTab.init(this); this.registerCtrlHandler("drtab",drTab); //注册 form ICtrlHandler editForm = (ICtrlHandler)getUniPSampleSysModel().createObject("com.sa.unip.app.ywsp.ctrlhandler.OA_CCSQCCSQLC_D_WFEditView3EditFormHandler"); editForm.init(this); this.registerCtrlHandler("form",editForm); } /** * 注册界面行为 * @throws Exception */ @Override protected void prepareUIActions()throws Exception { } }
package io.github.devbhuwan.microservices.nutshell.order.service.workflow; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.springframework.stereotype.Component; @Component public class PrepareOrderServiceTask implements JavaDelegate { @Override public void execute(DelegateExecution execution) throws Exception { } }
package com.example.demo.aspect; import com.example.demo.annotation.Limit; import com.example.demo.constant.Constants; import com.example.demo.enums.LimitType; import com.example.demo.exception.TestException; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.DefaultParameterNameDiscoverer; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.stereotype.Component; import java.lang.reflect.Method; import java.util.Collections; import java.util.List; /** * description:限流切面 * create: 2020/9/9 18:50 * * @author NieMingXin * @version 1.0 */ @Aspect @Slf4j @Component public class LimitAspect { @Autowired private RedisTemplate<String, Object> redisTemplate; @Pointcut("@annotation(com.example.demo.annotation.Limit)") public void pointcut() { } @Around("pointcut()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method signatureMethod = signature.getMethod(); Limit limit = signatureMethod.getAnnotation(Limit.class); LimitType limitType = limit.limitType(); String key = limit.key(); if (limitType == LimitType.EL && key.contains(Constants.HASH)) { key = generateKeyBySpEl(limit.key(), joinPoint); } List<String> keys = Collections.singletonList(limit.prefix() + Constants.COLON + key); String luaScript = buildLuaScript(); RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class); Number count = redisTemplate.execute(redisScript, keys, limit.count(), limit.timeUnit().toSeconds(limit.ttl())); if (count != null && count.intValue() <= limit.count()) { log.info("第{}次访问key为 {},描述为 [{}] 的接口", count, keys, limit.key()); return joinPoint.proceed(); } else { String str = "此接口最多%s %s访问%s次"; String format = String.format(str, limit.ttl(), limit.timeUnit().toString().toLowerCase(), limit.count()); throw new TestException(format); } } /** * 限流lua脚本 */ private String buildLuaScript() { return "local c" + "\nc = redis.call('get',KEYS[1])" + "\nif c and tonumber(c) > tonumber(ARGV[1]) then" + "\nreturn c;" + "\nend" + "\nc = redis.call('incr',KEYS[1])" + "\nif tonumber(c) == 1 then" + "\nredis.call('expire',KEYS[1],ARGV[2])" + "\nend" + "\nreturn c;"; } public String generateKeyBySpEl(String elString, ProceedingJoinPoint joinPoint) { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); //用于SpEL表达式解析. SpelExpressionParser parser = new SpelExpressionParser(); //用于获取方法参数定义名字. DefaultParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer(); String[] paramNames = nameDiscoverer.getParameterNames(methodSignature.getMethod()); Expression expression = parser.parseExpression(elString); EvaluationContext context = new StandardEvaluationContext(); Object[] args = joinPoint.getArgs(); if (paramNames != null) { for (int i = 0; i < args.length; i++) { context.setVariable(paramNames[i], args[i]); } } Object value = expression.getValue(context); return value != null ? value.toString() : ""; } }
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.test.api.authorization.batch; import static org.assertj.core.api.Assertions.assertThat; import static org.camunda.bpm.engine.test.api.authorization.util.AuthorizationSpec.grant; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.camunda.bpm.engine.EntityTypes; import org.camunda.bpm.engine.HistoryService; import org.camunda.bpm.engine.ProcessEngineConfiguration; import org.camunda.bpm.engine.authorization.BatchPermissions; import org.camunda.bpm.engine.authorization.Permissions; import org.camunda.bpm.engine.authorization.Resources; import org.camunda.bpm.engine.batch.Batch; import org.camunda.bpm.engine.batch.history.HistoricBatch; import org.camunda.bpm.engine.history.HistoricProcessInstance; import org.camunda.bpm.engine.test.RequiredHistoryLevel; import org.camunda.bpm.engine.test.api.authorization.util.AuthorizationScenario; import org.camunda.bpm.engine.test.api.authorization.util.AuthorizationScenarioWithCount; import org.camunda.bpm.engine.test.api.authorization.util.AuthorizationTestRule; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.RuleChain; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; /** * @author Askar Akhmerov */ @RunWith(Parameterized.class) @RequiredHistoryLevel(ProcessEngineConfiguration.HISTORY_AUDIT) public class DeleteHistoricProcessInstancesBatchAuthorizationTest extends AbstractBatchAuthorizationTest { protected static final long BATCH_OPERATIONS = 3; @Rule public RuleChain ruleChain = RuleChain.outerRule(engineRule).around(authRule).around(testHelper); @Parameterized.Parameter public AuthorizationScenarioWithCount scenario; protected HistoryService historyService; @Before public void setupHistoricService() { historyService = engineRule.getHistoryService(); } public void cleanBatch() { super.cleanBatch(); List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().list(); if (list.size() > 0) { List<String> instances = new ArrayList<>(); for (HistoricProcessInstance hpi : list) { instances.add(hpi.getId()); } historyService.deleteHistoricProcessInstances(instances); } } @Parameterized.Parameters(name = "Scenario {index}") public static Collection<AuthorizationScenario[]> scenarios() { return AuthorizationTestRule.asParameters( AuthorizationScenarioWithCount.scenario() .withCount(1L) .withAuthorizations( grant(Resources.BATCH, "*", "userId", Permissions.CREATE), grant(Resources.PROCESS_DEFINITION, "Process_1", "userId", Permissions.READ_HISTORY, Permissions.DELETE_HISTORY), grant(Resources.PROCESS_DEFINITION, "Process_2", "userId", Permissions.READ_HISTORY) ) .failsDueToRequired( grant(Resources.PROCESS_DEFINITION, "Process_2", "userId", Permissions.DELETE_HISTORY) ), AuthorizationScenarioWithCount.scenario() .withCount(0L) .withAuthorizations( grant(Resources.BATCH, "*", "userId", Permissions.CREATE), grant(Resources.PROCESS_DEFINITION, "Process_1", "userId", Permissions.READ_HISTORY, Permissions.DELETE_HISTORY), grant(Resources.PROCESS_DEFINITION, "Process_2", "userId", Permissions.READ_HISTORY, Permissions.DELETE_HISTORY) ), AuthorizationScenarioWithCount.scenario() .withCount(0L) .withAuthorizations( grant(Resources.BATCH, "*", "userId", BatchPermissions.CREATE_BATCH_DELETE_FINISHED_PROCESS_INSTANCES), grant(Resources.PROCESS_DEFINITION, "Process_1", "userId", Permissions.READ_HISTORY, Permissions.DELETE_HISTORY), grant(Resources.PROCESS_DEFINITION, "Process_2", "userId", Permissions.READ_HISTORY, Permissions.DELETE_HISTORY) ).succeeds() ); } @Test public void testWithTwoInvocationsProcessInstancesList() { engineRule.getProcessEngineConfiguration().setInvocationsPerBatchJob(2); setupAndExecuteHistoricProcessInstancesListTest(); // then assertScenario(); assertThat(historyService.createHistoricProcessInstanceQuery().count()).isEqualTo(getScenario().getCount()); } @Test public void testProcessInstancesList() { setupAndExecuteHistoricProcessInstancesListTest(); // then assertScenario(); } protected void setupAndExecuteHistoricProcessInstancesListTest() { //given List<String> processInstanceIds = Arrays.asList(processInstance.getId(), processInstance2.getId()); runtimeService.deleteProcessInstances(processInstanceIds, null, true, false); List<String> historicProcessInstances = new ArrayList<>(); for (HistoricProcessInstance hpi : historyService.createHistoricProcessInstanceQuery().list()) { historicProcessInstances.add(hpi.getId()); } authRule .init(scenario) .withUser("userId") .bindResource("Process_1", sourceDefinition.getKey()) .bindResource("Process_2", sourceDefinition2.getKey()) .start(); // when batch = historyService.deleteHistoricProcessInstancesAsync( historicProcessInstances, TEST_REASON); executeSeedAndBatchJobs(); } @Override public AuthorizationScenarioWithCount getScenario() { return scenario; } protected void assertScenario() { if (authRule.assertScenario(getScenario())) { Batch batch = engineRule.getManagementService().createBatchQuery().singleResult(); assertEquals("userId", batch.getCreateUserId()); if (testHelper.isHistoryLevelFull()) { assertThat(engineRule.getHistoryService().createUserOperationLogQuery().entityType(EntityTypes.PROCESS_INSTANCE).count()).isEqualTo(BATCH_OPERATIONS); HistoricBatch historicBatch = engineRule.getHistoryService().createHistoricBatchQuery().list().get(0); assertEquals("userId", historicBatch.getCreateUserId()); } assertThat(historyService.createHistoricProcessInstanceQuery().count()).isEqualTo(0L); } } }
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.google.protobuf; import protobuf_unittest.UnittestProto; import com.google.protobuf.UnittestLite; // The static imports are to avoid 100+ char lines. The following is roughly equivalent to // import static protobuf_unittest.UnittestProto.*; import static protobuf_unittest.UnittestProto.defaultInt32Extension; import static protobuf_unittest.UnittestProto.defaultInt64Extension; import static protobuf_unittest.UnittestProto.defaultUint32Extension; import static protobuf_unittest.UnittestProto.defaultUint64Extension; import static protobuf_unittest.UnittestProto.defaultSint32Extension; import static protobuf_unittest.UnittestProto.defaultSint64Extension; import static protobuf_unittest.UnittestProto.defaultFixed32Extension; import static protobuf_unittest.UnittestProto.defaultFixed64Extension; import static protobuf_unittest.UnittestProto.defaultSfixed32Extension; import static protobuf_unittest.UnittestProto.defaultSfixed64Extension; import static protobuf_unittest.UnittestProto.defaultFloatExtension; import static protobuf_unittest.UnittestProto.defaultDoubleExtension; import static protobuf_unittest.UnittestProto.defaultBoolExtension; import static protobuf_unittest.UnittestProto.defaultStringExtension; import static protobuf_unittest.UnittestProto.defaultBytesExtension; import static protobuf_unittest.UnittestProto.defaultNestedEnumExtension; import static protobuf_unittest.UnittestProto.defaultForeignEnumExtension; import static protobuf_unittest.UnittestProto.defaultImportEnumExtension; import static protobuf_unittest.UnittestProto.defaultStringPieceExtension; import static protobuf_unittest.UnittestProto.defaultCordExtension; import static protobuf_unittest.UnittestProto.oneofUint32Extension; import static protobuf_unittest.UnittestProto.oneofNestedMessageExtension; import static protobuf_unittest.UnittestProto.oneofStringExtension; import static protobuf_unittest.UnittestProto.oneofBytesExtension; import static protobuf_unittest.UnittestProto.optionalInt32Extension; import static protobuf_unittest.UnittestProto.optionalInt64Extension; import static protobuf_unittest.UnittestProto.optionalUint32Extension; import static protobuf_unittest.UnittestProto.optionalUint64Extension; import static protobuf_unittest.UnittestProto.optionalSint32Extension; import static protobuf_unittest.UnittestProto.optionalSint64Extension; import static protobuf_unittest.UnittestProto.optionalFixed32Extension; import static protobuf_unittest.UnittestProto.optionalFixed64Extension; import static protobuf_unittest.UnittestProto.optionalSfixed32Extension; import static protobuf_unittest.UnittestProto.optionalSfixed64Extension; import static protobuf_unittest.UnittestProto.optionalFloatExtension; import static protobuf_unittest.UnittestProto.optionalDoubleExtension; import static protobuf_unittest.UnittestProto.optionalBoolExtension; import static protobuf_unittest.UnittestProto.optionalStringExtension; import static protobuf_unittest.UnittestProto.optionalBytesExtension; import static protobuf_unittest.UnittestProto.optionalGroupExtension; import static protobuf_unittest.UnittestProto.optionalCordExtension; import static protobuf_unittest.UnittestProto.optionalForeignEnumExtension; import static protobuf_unittest.UnittestProto.optionalForeignMessageExtension; import static protobuf_unittest.UnittestProto.optionalImportEnumExtension; import static protobuf_unittest.UnittestProto.optionalImportMessageExtension; import static protobuf_unittest.UnittestProto.optionalNestedEnumExtension; import static protobuf_unittest.UnittestProto.optionalNestedMessageExtension; import static protobuf_unittest.UnittestProto.optionalPublicImportMessageExtension; import static protobuf_unittest.UnittestProto.optionalLazyMessageExtension; import static protobuf_unittest.UnittestProto.optionalStringPieceExtension; import static protobuf_unittest.UnittestProto.repeatedInt32Extension; import static protobuf_unittest.UnittestProto.repeatedInt64Extension; import static protobuf_unittest.UnittestProto.repeatedUint32Extension; import static protobuf_unittest.UnittestProto.repeatedUint64Extension; import static protobuf_unittest.UnittestProto.repeatedSint32Extension; import static protobuf_unittest.UnittestProto.repeatedSint64Extension; import static protobuf_unittest.UnittestProto.repeatedFixed32Extension; import static protobuf_unittest.UnittestProto.repeatedFixed64Extension; import static protobuf_unittest.UnittestProto.repeatedSfixed32Extension; import static protobuf_unittest.UnittestProto.repeatedSfixed64Extension; import static protobuf_unittest.UnittestProto.repeatedFloatExtension; import static protobuf_unittest.UnittestProto.repeatedDoubleExtension; import static protobuf_unittest.UnittestProto.repeatedBoolExtension; import static protobuf_unittest.UnittestProto.repeatedStringExtension; import static protobuf_unittest.UnittestProto.repeatedBytesExtension; import static protobuf_unittest.UnittestProto.repeatedGroupExtension; import static protobuf_unittest.UnittestProto.repeatedNestedMessageExtension; import static protobuf_unittest.UnittestProto.repeatedForeignMessageExtension; import static protobuf_unittest.UnittestProto.repeatedImportMessageExtension; import static protobuf_unittest.UnittestProto.repeatedLazyMessageExtension; import static protobuf_unittest.UnittestProto.repeatedNestedEnumExtension; import static protobuf_unittest.UnittestProto.repeatedForeignEnumExtension; import static protobuf_unittest.UnittestProto.repeatedImportEnumExtension; import static protobuf_unittest.UnittestProto.repeatedStringPieceExtension; import static protobuf_unittest.UnittestProto.repeatedCordExtension; import static protobuf_unittest.UnittestProto.OptionalGroup_extension; import static protobuf_unittest.UnittestProto.RepeatedGroup_extension; import static protobuf_unittest.UnittestProto.packedInt32Extension; import static protobuf_unittest.UnittestProto.packedInt64Extension; import static protobuf_unittest.UnittestProto.packedUint32Extension; import static protobuf_unittest.UnittestProto.packedUint64Extension; import static protobuf_unittest.UnittestProto.packedSint32Extension; import static protobuf_unittest.UnittestProto.packedSint64Extension; import static protobuf_unittest.UnittestProto.packedFixed32Extension; import static protobuf_unittest.UnittestProto.packedFixed64Extension; import static protobuf_unittest.UnittestProto.packedSfixed32Extension; import static protobuf_unittest.UnittestProto.packedSfixed64Extension; import static protobuf_unittest.UnittestProto.packedFloatExtension; import static protobuf_unittest.UnittestProto.packedDoubleExtension; import static protobuf_unittest.UnittestProto.packedBoolExtension; import static protobuf_unittest.UnittestProto.packedEnumExtension; import static com.google.protobuf.UnittestLite.defaultInt32ExtensionLite; import static com.google.protobuf.UnittestLite.defaultInt64ExtensionLite; import static com.google.protobuf.UnittestLite.defaultUint32ExtensionLite; import static com.google.protobuf.UnittestLite.defaultUint64ExtensionLite; import static com.google.protobuf.UnittestLite.defaultSint32ExtensionLite; import static com.google.protobuf.UnittestLite.defaultSint64ExtensionLite; import static com.google.protobuf.UnittestLite.defaultFixed32ExtensionLite; import static com.google.protobuf.UnittestLite.defaultFixed64ExtensionLite; import static com.google.protobuf.UnittestLite.defaultSfixed32ExtensionLite; import static com.google.protobuf.UnittestLite.defaultSfixed64ExtensionLite; import static com.google.protobuf.UnittestLite.defaultFloatExtensionLite; import static com.google.protobuf.UnittestLite.defaultDoubleExtensionLite; import static com.google.protobuf.UnittestLite.defaultBoolExtensionLite; import static com.google.protobuf.UnittestLite.defaultStringExtensionLite; import static com.google.protobuf.UnittestLite.defaultBytesExtensionLite; import static com.google.protobuf.UnittestLite.defaultNestedEnumExtensionLite; import static com.google.protobuf.UnittestLite.defaultForeignEnumExtensionLite; import static com.google.protobuf.UnittestLite.defaultImportEnumExtensionLite; import static com.google.protobuf.UnittestLite.defaultStringPieceExtensionLite; import static com.google.protobuf.UnittestLite.defaultCordExtensionLite; import static com.google.protobuf.UnittestLite.oneofUint32ExtensionLite; import static com.google.protobuf.UnittestLite.oneofNestedMessageExtensionLite; import static com.google.protobuf.UnittestLite.oneofStringExtensionLite; import static com.google.protobuf.UnittestLite.oneofBytesExtensionLite; import static com.google.protobuf.UnittestLite.optionalInt32ExtensionLite; import static com.google.protobuf.UnittestLite.optionalInt64ExtensionLite; import static com.google.protobuf.UnittestLite.optionalUint32ExtensionLite; import static com.google.protobuf.UnittestLite.optionalUint64ExtensionLite; import static com.google.protobuf.UnittestLite.optionalSint32ExtensionLite; import static com.google.protobuf.UnittestLite.optionalSint64ExtensionLite; import static com.google.protobuf.UnittestLite.optionalFixed32ExtensionLite; import static com.google.protobuf.UnittestLite.optionalFixed64ExtensionLite; import static com.google.protobuf.UnittestLite.optionalSfixed32ExtensionLite; import static com.google.protobuf.UnittestLite.optionalSfixed64ExtensionLite; import static com.google.protobuf.UnittestLite.optionalFloatExtensionLite; import static com.google.protobuf.UnittestLite.optionalDoubleExtensionLite; import static com.google.protobuf.UnittestLite.optionalBoolExtensionLite; import static com.google.protobuf.UnittestLite.optionalStringExtensionLite; import static com.google.protobuf.UnittestLite.optionalBytesExtensionLite; import static com.google.protobuf.UnittestLite.optionalGroupExtensionLite; import static com.google.protobuf.UnittestLite.optionalNestedMessageExtensionLite; import static com.google.protobuf.UnittestLite.optionalForeignEnumExtensionLite; import static com.google.protobuf.UnittestLite.optionalForeignMessageExtensionLite; import static com.google.protobuf.UnittestLite.optionalImportEnumExtensionLite; import static com.google.protobuf.UnittestLite.optionalImportMessageExtensionLite; import static com.google.protobuf.UnittestLite.optionalNestedEnumExtensionLite; import static com.google.protobuf.UnittestLite.optionalPublicImportMessageExtensionLite; import static com.google.protobuf.UnittestLite.optionalLazyMessageExtensionLite; import static com.google.protobuf.UnittestLite.optionalStringPieceExtensionLite; import static com.google.protobuf.UnittestLite.optionalCordExtensionLite; import static com.google.protobuf.UnittestLite.repeatedInt32ExtensionLite; import static com.google.protobuf.UnittestLite.repeatedInt64ExtensionLite; import static com.google.protobuf.UnittestLite.repeatedUint32ExtensionLite; import static com.google.protobuf.UnittestLite.repeatedUint64ExtensionLite; import static com.google.protobuf.UnittestLite.repeatedSint32ExtensionLite; import static com.google.protobuf.UnittestLite.repeatedSint64ExtensionLite; import static com.google.protobuf.UnittestLite.repeatedFixed32ExtensionLite; import static com.google.protobuf.UnittestLite.repeatedFixed64ExtensionLite; import static com.google.protobuf.UnittestLite.repeatedSfixed32ExtensionLite; import static com.google.protobuf.UnittestLite.repeatedSfixed64ExtensionLite; import static com.google.protobuf.UnittestLite.repeatedFloatExtensionLite; import static com.google.protobuf.UnittestLite.repeatedDoubleExtensionLite; import static com.google.protobuf.UnittestLite.repeatedBoolExtensionLite; import static com.google.protobuf.UnittestLite.repeatedStringExtensionLite; import static com.google.protobuf.UnittestLite.repeatedBytesExtensionLite; import static com.google.protobuf.UnittestLite.repeatedGroupExtensionLite; import static com.google.protobuf.UnittestLite.repeatedNestedMessageExtensionLite; import static com.google.protobuf.UnittestLite.repeatedForeignMessageExtensionLite; import static com.google.protobuf.UnittestLite.repeatedImportMessageExtensionLite; import static com.google.protobuf.UnittestLite.repeatedLazyMessageExtensionLite; import static com.google.protobuf.UnittestLite.repeatedNestedEnumExtensionLite; import static com.google.protobuf.UnittestLite.repeatedForeignEnumExtensionLite; import static com.google.protobuf.UnittestLite.repeatedImportEnumExtensionLite; import static com.google.protobuf.UnittestLite.repeatedStringPieceExtensionLite; import static com.google.protobuf.UnittestLite.repeatedCordExtensionLite; import static com.google.protobuf.UnittestLite.OptionalGroup_extension_lite; import static com.google.protobuf.UnittestLite.RepeatedGroup_extension_lite; import static com.google.protobuf.UnittestLite.packedInt32ExtensionLite; import static com.google.protobuf.UnittestLite.packedInt64ExtensionLite; import static com.google.protobuf.UnittestLite.packedUint32ExtensionLite; import static com.google.protobuf.UnittestLite.packedUint64ExtensionLite; import static com.google.protobuf.UnittestLite.packedSint32ExtensionLite; import static com.google.protobuf.UnittestLite.packedSint64ExtensionLite; import static com.google.protobuf.UnittestLite.packedFixed32ExtensionLite; import static com.google.protobuf.UnittestLite.packedFixed64ExtensionLite; import static com.google.protobuf.UnittestLite.packedSfixed32ExtensionLite; import static com.google.protobuf.UnittestLite.packedSfixed64ExtensionLite; import static com.google.protobuf.UnittestLite.packedFloatExtensionLite; import static com.google.protobuf.UnittestLite.packedDoubleExtensionLite; import static com.google.protobuf.UnittestLite.packedBoolExtensionLite; import static com.google.protobuf.UnittestLite.packedEnumExtensionLite; import protobuf_unittest.UnittestProto.TestAllExtensions; import protobuf_unittest.UnittestProto.TestAllExtensionsOrBuilder; import protobuf_unittest.UnittestProto.TestAllTypes; import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder; import protobuf_unittest.UnittestProto.TestOneof2; import protobuf_unittest.UnittestProto.TestPackedExtensions; import protobuf_unittest.UnittestProto.TestPackedTypes; import protobuf_unittest.UnittestProto.TestUnpackedTypes; import protobuf_unittest.UnittestProto.ForeignMessage; import protobuf_unittest.UnittestProto.ForeignEnum; import com.google.protobuf.test.UnittestImport.ImportEnum; import com.google.protobuf.test.UnittestImport.ImportMessage; import com.google.protobuf.test.UnittestImportPublic.PublicImportMessage; import com.google.protobuf.UnittestLite.TestAllTypesLite; import com.google.protobuf.UnittestLite.TestAllExtensionsLite; import com.google.protobuf.UnittestLite.TestAllExtensionsLiteOrBuilder; import com.google.protobuf.UnittestLite.TestPackedExtensionsLite; import com.google.protobuf.UnittestLite.ForeignMessageLite; import com.google.protobuf.UnittestLite.ForeignEnumLite; import com.google.protobuf.UnittestImportLite.ImportEnumLite; import com.google.protobuf.UnittestImportLite.ImportMessageLite; import com.google.protobuf.UnittestImportPublicLite.PublicImportMessageLite; import junit.framework.Assert; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; /** * Contains methods for setting all fields of {@code TestAllTypes} to * some values as well as checking that all the fields are set to those values. * These are useful for testing various protocol message features, e.g. * set all fields of a message, serialize it, parse it, and check that all * fields are set. * * <p>This code is not to be used outside of {@code com.google.protobuf} and * subpackages. * * @author kenton@google.com Kenton Varda */ public final class TestUtil { private TestUtil() {} /** Helper to convert a String to ByteString. */ static ByteString toBytes(String str) { return ByteString.copyFrom(str.getBytes(Internal.UTF_8)); } /** * Get a {@code TestAllTypes} with all fields set as they would be by * {@link #setAllFields(TestAllTypes.Builder)}. */ public static TestAllTypes getAllSet() { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); setAllFields(builder); return builder.build(); } /** * Get a {@code TestAllTypes.Builder} with all fields set as they would be by * {@link #setAllFields(TestAllTypes.Builder)}. */ public static TestAllTypes.Builder getAllSetBuilder() { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); setAllFields(builder); return builder; } /** * Get a {@code TestAllExtensions} with all fields set as they would be by * {@link #setAllExtensions(TestAllExtensions.Builder)}. */ public static TestAllExtensions getAllExtensionsSet() { TestAllExtensions.Builder builder = TestAllExtensions.newBuilder(); setAllExtensions(builder); return builder.build(); } public static TestAllExtensionsLite getAllLiteExtensionsSet() { TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder(); setAllExtensions(builder); return builder.build(); } public static TestPackedTypes getPackedSet() { TestPackedTypes.Builder builder = TestPackedTypes.newBuilder(); setPackedFields(builder); return builder.build(); } public static TestUnpackedTypes getUnpackedSet() { TestUnpackedTypes.Builder builder = TestUnpackedTypes.newBuilder(); setUnpackedFields(builder); return builder.build(); } public static TestPackedExtensions getPackedExtensionsSet() { TestPackedExtensions.Builder builder = TestPackedExtensions.newBuilder(); setPackedExtensions(builder); return builder.build(); } public static TestPackedExtensionsLite getLitePackedExtensionsSet() { TestPackedExtensionsLite.Builder builder = TestPackedExtensionsLite.newBuilder(); setPackedExtensions(builder); return builder.build(); } /** * Set every field of {@code message} to the values expected by * {@code assertAllFieldsSet()}. */ public static void setAllFields(TestAllTypes.Builder message) { message.setOptionalInt32 (101); message.setOptionalInt64 (102); message.setOptionalUint32 (103); message.setOptionalUint64 (104); message.setOptionalSint32 (105); message.setOptionalSint64 (106); message.setOptionalFixed32 (107); message.setOptionalFixed64 (108); message.setOptionalSfixed32(109); message.setOptionalSfixed64(110); message.setOptionalFloat (111); message.setOptionalDouble (112); message.setOptionalBool (true); message.setOptionalString ("115"); message.setOptionalBytes (toBytes("116")); message.setOptionalGroup( TestAllTypes.OptionalGroup.newBuilder().setA(117).build()); message.setOptionalNestedMessage( TestAllTypes.NestedMessage.newBuilder().setBb(118).build()); message.setOptionalForeignMessage( ForeignMessage.newBuilder().setC(119).build()); message.setOptionalImportMessage( ImportMessage.newBuilder().setD(120).build()); message.setOptionalPublicImportMessage( PublicImportMessage.newBuilder().setE(126).build()); message.setOptionalLazyMessage( TestAllTypes.NestedMessage.newBuilder().setBb(127).build()); message.setOptionalNestedEnum (TestAllTypes.NestedEnum.BAZ); message.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAZ); message.setOptionalImportEnum (ImportEnum.IMPORT_BAZ); message.setOptionalStringPiece("124"); message.setOptionalCord("125"); // ----------------------------------------------------------------- message.addRepeatedInt32 (201); message.addRepeatedInt64 (202); message.addRepeatedUint32 (203); message.addRepeatedUint64 (204); message.addRepeatedSint32 (205); message.addRepeatedSint64 (206); message.addRepeatedFixed32 (207); message.addRepeatedFixed64 (208); message.addRepeatedSfixed32(209); message.addRepeatedSfixed64(210); message.addRepeatedFloat (211); message.addRepeatedDouble (212); message.addRepeatedBool (true); message.addRepeatedString ("215"); message.addRepeatedBytes (toBytes("216")); message.addRepeatedGroup( TestAllTypes.RepeatedGroup.newBuilder().setA(217).build()); message.addRepeatedNestedMessage( TestAllTypes.NestedMessage.newBuilder().setBb(218).build()); message.addRepeatedForeignMessage( ForeignMessage.newBuilder().setC(219).build()); message.addRepeatedImportMessage( ImportMessage.newBuilder().setD(220).build()); message.addRepeatedLazyMessage( TestAllTypes.NestedMessage.newBuilder().setBb(227).build()); message.addRepeatedNestedEnum (TestAllTypes.NestedEnum.BAR); message.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAR); message.addRepeatedImportEnum (ImportEnum.IMPORT_BAR); message.addRepeatedStringPiece("224"); message.addRepeatedCord("225"); // Add a second one of each field. message.addRepeatedInt32 (301); message.addRepeatedInt64 (302); message.addRepeatedUint32 (303); message.addRepeatedUint64 (304); message.addRepeatedSint32 (305); message.addRepeatedSint64 (306); message.addRepeatedFixed32 (307); message.addRepeatedFixed64 (308); message.addRepeatedSfixed32(309); message.addRepeatedSfixed64(310); message.addRepeatedFloat (311); message.addRepeatedDouble (312); message.addRepeatedBool (false); message.addRepeatedString ("315"); message.addRepeatedBytes (toBytes("316")); message.addRepeatedGroup( TestAllTypes.RepeatedGroup.newBuilder().setA(317).build()); message.addRepeatedNestedMessage( TestAllTypes.NestedMessage.newBuilder().setBb(318).build()); message.addRepeatedForeignMessage( ForeignMessage.newBuilder().setC(319).build()); message.addRepeatedImportMessage( ImportMessage.newBuilder().setD(320).build()); message.addRepeatedLazyMessage( TestAllTypes.NestedMessage.newBuilder().setBb(327).build()); message.addRepeatedNestedEnum (TestAllTypes.NestedEnum.BAZ); message.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAZ); message.addRepeatedImportEnum (ImportEnum.IMPORT_BAZ); message.addRepeatedStringPiece("324"); message.addRepeatedCord("325"); // ----------------------------------------------------------------- message.setDefaultInt32 (401); message.setDefaultInt64 (402); message.setDefaultUint32 (403); message.setDefaultUint64 (404); message.setDefaultSint32 (405); message.setDefaultSint64 (406); message.setDefaultFixed32 (407); message.setDefaultFixed64 (408); message.setDefaultSfixed32(409); message.setDefaultSfixed64(410); message.setDefaultFloat (411); message.setDefaultDouble (412); message.setDefaultBool (false); message.setDefaultString ("415"); message.setDefaultBytes (toBytes("416")); message.setDefaultNestedEnum (TestAllTypes.NestedEnum.FOO); message.setDefaultForeignEnum(ForeignEnum.FOREIGN_FOO); message.setDefaultImportEnum (ImportEnum.IMPORT_FOO); message.setDefaultStringPiece("424"); message.setDefaultCord("425"); message.setOneofUint32(601); message.setOneofNestedMessage( TestAllTypes.NestedMessage.newBuilder().setBb(602).build()); message.setOneofString("603"); message.setOneofBytes(toBytes("604")); } // ------------------------------------------------------------------- /** * Modify the repeated fields of {@code message} to contain the values * expected by {@code assertRepeatedFieldsModified()}. */ public static void modifyRepeatedFields(TestAllTypes.Builder message) { message.setRepeatedInt32 (1, 501); message.setRepeatedInt64 (1, 502); message.setRepeatedUint32 (1, 503); message.setRepeatedUint64 (1, 504); message.setRepeatedSint32 (1, 505); message.setRepeatedSint64 (1, 506); message.setRepeatedFixed32 (1, 507); message.setRepeatedFixed64 (1, 508); message.setRepeatedSfixed32(1, 509); message.setRepeatedSfixed64(1, 510); message.setRepeatedFloat (1, 511); message.setRepeatedDouble (1, 512); message.setRepeatedBool (1, true); message.setRepeatedString (1, "515"); message.setRepeatedBytes (1, toBytes("516")); message.setRepeatedGroup(1, TestAllTypes.RepeatedGroup.newBuilder().setA(517).build()); message.setRepeatedNestedMessage(1, TestAllTypes.NestedMessage.newBuilder().setBb(518).build()); message.setRepeatedForeignMessage(1, ForeignMessage.newBuilder().setC(519).build()); message.setRepeatedImportMessage(1, ImportMessage.newBuilder().setD(520).build()); message.setRepeatedLazyMessage(1, TestAllTypes.NestedMessage.newBuilder().setBb(527).build()); message.setRepeatedNestedEnum (1, TestAllTypes.NestedEnum.FOO); message.setRepeatedForeignEnum(1, ForeignEnum.FOREIGN_FOO); message.setRepeatedImportEnum (1, ImportEnum.IMPORT_FOO); message.setRepeatedStringPiece(1, "524"); message.setRepeatedCord(1, "525"); } // ------------------------------------------------------------------- /** * Assert (using {@code junit.framework.Assert}} that all fields of * {@code message} are set to the values assigned by {@code setAllFields}. */ public static void assertAllFieldsSet(TestAllTypesOrBuilder message) { Assert.assertTrue(message.hasOptionalInt32 ()); Assert.assertTrue(message.hasOptionalInt64 ()); Assert.assertTrue(message.hasOptionalUint32 ()); Assert.assertTrue(message.hasOptionalUint64 ()); Assert.assertTrue(message.hasOptionalSint32 ()); Assert.assertTrue(message.hasOptionalSint64 ()); Assert.assertTrue(message.hasOptionalFixed32 ()); Assert.assertTrue(message.hasOptionalFixed64 ()); Assert.assertTrue(message.hasOptionalSfixed32()); Assert.assertTrue(message.hasOptionalSfixed64()); Assert.assertTrue(message.hasOptionalFloat ()); Assert.assertTrue(message.hasOptionalDouble ()); Assert.assertTrue(message.hasOptionalBool ()); Assert.assertTrue(message.hasOptionalString ()); Assert.assertTrue(message.hasOptionalBytes ()); Assert.assertTrue(message.hasOptionalGroup ()); Assert.assertTrue(message.hasOptionalNestedMessage ()); Assert.assertTrue(message.hasOptionalForeignMessage()); Assert.assertTrue(message.hasOptionalImportMessage ()); Assert.assertTrue(message.getOptionalGroup ().hasA()); Assert.assertTrue(message.getOptionalNestedMessage ().hasBb()); Assert.assertTrue(message.getOptionalForeignMessage().hasC()); Assert.assertTrue(message.getOptionalImportMessage ().hasD()); Assert.assertTrue(message.hasOptionalNestedEnum ()); Assert.assertTrue(message.hasOptionalForeignEnum()); Assert.assertTrue(message.hasOptionalImportEnum ()); Assert.assertTrue(message.hasOptionalStringPiece()); Assert.assertTrue(message.hasOptionalCord()); Assert.assertEquals(101 , message.getOptionalInt32 ()); Assert.assertEquals(102 , message.getOptionalInt64 ()); Assert.assertEquals(103 , message.getOptionalUint32 ()); Assert.assertEquals(104 , message.getOptionalUint64 ()); Assert.assertEquals(105 , message.getOptionalSint32 ()); Assert.assertEquals(106 , message.getOptionalSint64 ()); Assert.assertEquals(107 , message.getOptionalFixed32 ()); Assert.assertEquals(108 , message.getOptionalFixed64 ()); Assert.assertEquals(109 , message.getOptionalSfixed32()); Assert.assertEquals(110 , message.getOptionalSfixed64()); Assert.assertEquals(111 , message.getOptionalFloat (), 0.0); Assert.assertEquals(112 , message.getOptionalDouble (), 0.0); Assert.assertEquals(true , message.getOptionalBool ()); Assert.assertEquals("115", message.getOptionalString ()); Assert.assertEquals(toBytes("116"), message.getOptionalBytes()); Assert.assertEquals(117, message.getOptionalGroup ().getA()); Assert.assertEquals(118, message.getOptionalNestedMessage ().getBb()); Assert.assertEquals(119, message.getOptionalForeignMessage ().getC()); Assert.assertEquals(120, message.getOptionalImportMessage ().getD()); Assert.assertEquals(126, message.getOptionalPublicImportMessage().getE()); Assert.assertEquals(127, message.getOptionalLazyMessage ().getBb()); Assert.assertEquals(TestAllTypes.NestedEnum.BAZ, message.getOptionalNestedEnum()); Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getOptionalForeignEnum()); Assert.assertEquals(ImportEnum.IMPORT_BAZ, message.getOptionalImportEnum()); Assert.assertEquals("124", message.getOptionalStringPiece()); Assert.assertEquals("125", message.getOptionalCord()); // ----------------------------------------------------------------- Assert.assertEquals(2, message.getRepeatedInt32Count ()); Assert.assertEquals(2, message.getRepeatedInt64Count ()); Assert.assertEquals(2, message.getRepeatedUint32Count ()); Assert.assertEquals(2, message.getRepeatedUint64Count ()); Assert.assertEquals(2, message.getRepeatedSint32Count ()); Assert.assertEquals(2, message.getRepeatedSint64Count ()); Assert.assertEquals(2, message.getRepeatedFixed32Count ()); Assert.assertEquals(2, message.getRepeatedFixed64Count ()); Assert.assertEquals(2, message.getRepeatedSfixed32Count()); Assert.assertEquals(2, message.getRepeatedSfixed64Count()); Assert.assertEquals(2, message.getRepeatedFloatCount ()); Assert.assertEquals(2, message.getRepeatedDoubleCount ()); Assert.assertEquals(2, message.getRepeatedBoolCount ()); Assert.assertEquals(2, message.getRepeatedStringCount ()); Assert.assertEquals(2, message.getRepeatedBytesCount ()); Assert.assertEquals(2, message.getRepeatedGroupCount ()); Assert.assertEquals(2, message.getRepeatedNestedMessageCount ()); Assert.assertEquals(2, message.getRepeatedForeignMessageCount()); Assert.assertEquals(2, message.getRepeatedImportMessageCount ()); Assert.assertEquals(2, message.getRepeatedLazyMessageCount ()); Assert.assertEquals(2, message.getRepeatedNestedEnumCount ()); Assert.assertEquals(2, message.getRepeatedForeignEnumCount ()); Assert.assertEquals(2, message.getRepeatedImportEnumCount ()); Assert.assertEquals(2, message.getRepeatedStringPieceCount()); Assert.assertEquals(2, message.getRepeatedCordCount()); Assert.assertEquals(201 , message.getRepeatedInt32 (0)); Assert.assertEquals(202 , message.getRepeatedInt64 (0)); Assert.assertEquals(203 , message.getRepeatedUint32 (0)); Assert.assertEquals(204 , message.getRepeatedUint64 (0)); Assert.assertEquals(205 , message.getRepeatedSint32 (0)); Assert.assertEquals(206 , message.getRepeatedSint64 (0)); Assert.assertEquals(207 , message.getRepeatedFixed32 (0)); Assert.assertEquals(208 , message.getRepeatedFixed64 (0)); Assert.assertEquals(209 , message.getRepeatedSfixed32(0)); Assert.assertEquals(210 , message.getRepeatedSfixed64(0)); Assert.assertEquals(211 , message.getRepeatedFloat (0), 0.0); Assert.assertEquals(212 , message.getRepeatedDouble (0), 0.0); Assert.assertEquals(true , message.getRepeatedBool (0)); Assert.assertEquals("215", message.getRepeatedString (0)); Assert.assertEquals(toBytes("216"), message.getRepeatedBytes(0)); Assert.assertEquals(217, message.getRepeatedGroup (0).getA()); Assert.assertEquals(218, message.getRepeatedNestedMessage (0).getBb()); Assert.assertEquals(219, message.getRepeatedForeignMessage(0).getC()); Assert.assertEquals(220, message.getRepeatedImportMessage (0).getD()); Assert.assertEquals(227, message.getRepeatedLazyMessage (0).getBb()); Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum (0)); Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getRepeatedForeignEnum(0)); Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getRepeatedImportEnum(0)); Assert.assertEquals("224", message.getRepeatedStringPiece(0)); Assert.assertEquals("225", message.getRepeatedCord(0)); Assert.assertEquals(301 , message.getRepeatedInt32 (1)); Assert.assertEquals(302 , message.getRepeatedInt64 (1)); Assert.assertEquals(303 , message.getRepeatedUint32 (1)); Assert.assertEquals(304 , message.getRepeatedUint64 (1)); Assert.assertEquals(305 , message.getRepeatedSint32 (1)); Assert.assertEquals(306 , message.getRepeatedSint64 (1)); Assert.assertEquals(307 , message.getRepeatedFixed32 (1)); Assert.assertEquals(308 , message.getRepeatedFixed64 (1)); Assert.assertEquals(309 , message.getRepeatedSfixed32(1)); Assert.assertEquals(310 , message.getRepeatedSfixed64(1)); Assert.assertEquals(311 , message.getRepeatedFloat (1), 0.0); Assert.assertEquals(312 , message.getRepeatedDouble (1), 0.0); Assert.assertEquals(false, message.getRepeatedBool (1)); Assert.assertEquals("315", message.getRepeatedString (1)); Assert.assertEquals(toBytes("316"), message.getRepeatedBytes(1)); Assert.assertEquals(317, message.getRepeatedGroup (1).getA()); Assert.assertEquals(318, message.getRepeatedNestedMessage (1).getBb()); Assert.assertEquals(319, message.getRepeatedForeignMessage(1).getC()); Assert.assertEquals(320, message.getRepeatedImportMessage (1).getD()); Assert.assertEquals(327, message.getRepeatedLazyMessage (1).getBb()); Assert.assertEquals(TestAllTypes.NestedEnum.BAZ, message.getRepeatedNestedEnum (1)); Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getRepeatedForeignEnum(1)); Assert.assertEquals(ImportEnum.IMPORT_BAZ, message.getRepeatedImportEnum(1)); Assert.assertEquals("324", message.getRepeatedStringPiece(1)); Assert.assertEquals("325", message.getRepeatedCord(1)); // ----------------------------------------------------------------- Assert.assertTrue(message.hasDefaultInt32 ()); Assert.assertTrue(message.hasDefaultInt64 ()); Assert.assertTrue(message.hasDefaultUint32 ()); Assert.assertTrue(message.hasDefaultUint64 ()); Assert.assertTrue(message.hasDefaultSint32 ()); Assert.assertTrue(message.hasDefaultSint64 ()); Assert.assertTrue(message.hasDefaultFixed32 ()); Assert.assertTrue(message.hasDefaultFixed64 ()); Assert.assertTrue(message.hasDefaultSfixed32()); Assert.assertTrue(message.hasDefaultSfixed64()); Assert.assertTrue(message.hasDefaultFloat ()); Assert.assertTrue(message.hasDefaultDouble ()); Assert.assertTrue(message.hasDefaultBool ()); Assert.assertTrue(message.hasDefaultString ()); Assert.assertTrue(message.hasDefaultBytes ()); Assert.assertTrue(message.hasDefaultNestedEnum ()); Assert.assertTrue(message.hasDefaultForeignEnum()); Assert.assertTrue(message.hasDefaultImportEnum ()); Assert.assertTrue(message.hasDefaultStringPiece()); Assert.assertTrue(message.hasDefaultCord()); Assert.assertEquals(401 , message.getDefaultInt32 ()); Assert.assertEquals(402 , message.getDefaultInt64 ()); Assert.assertEquals(403 , message.getDefaultUint32 ()); Assert.assertEquals(404 , message.getDefaultUint64 ()); Assert.assertEquals(405 , message.getDefaultSint32 ()); Assert.assertEquals(406 , message.getDefaultSint64 ()); Assert.assertEquals(407 , message.getDefaultFixed32 ()); Assert.assertEquals(408 , message.getDefaultFixed64 ()); Assert.assertEquals(409 , message.getDefaultSfixed32()); Assert.assertEquals(410 , message.getDefaultSfixed64()); Assert.assertEquals(411 , message.getDefaultFloat (), 0.0); Assert.assertEquals(412 , message.getDefaultDouble (), 0.0); Assert.assertEquals(false, message.getDefaultBool ()); Assert.assertEquals("415", message.getDefaultString ()); Assert.assertEquals(toBytes("416"), message.getDefaultBytes()); Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getDefaultNestedEnum ()); Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getDefaultForeignEnum()); Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getDefaultImportEnum()); Assert.assertEquals("424", message.getDefaultStringPiece()); Assert.assertEquals("425", message.getDefaultCord()); Assert.assertEquals(TestAllTypes.OneofFieldCase.ONEOF_BYTES, message.getOneofFieldCase()); Assert.assertFalse(message.hasOneofUint32()); Assert.assertFalse(message.hasOneofNestedMessage()); Assert.assertFalse(message.hasOneofString()); Assert.assertTrue(message.hasOneofBytes()); Assert.assertEquals(toBytes("604"), message.getOneofBytes()); } // ------------------------------------------------------------------- /** * Assert (using {@code junit.framework.Assert}} that all fields of * {@code message} are cleared, and that getting the fields returns their * default values. */ public static void assertClear(TestAllTypesOrBuilder message) { // hasBlah() should initially be false for all optional fields. Assert.assertFalse(message.hasOptionalInt32 ()); Assert.assertFalse(message.hasOptionalInt64 ()); Assert.assertFalse(message.hasOptionalUint32 ()); Assert.assertFalse(message.hasOptionalUint64 ()); Assert.assertFalse(message.hasOptionalSint32 ()); Assert.assertFalse(message.hasOptionalSint64 ()); Assert.assertFalse(message.hasOptionalFixed32 ()); Assert.assertFalse(message.hasOptionalFixed64 ()); Assert.assertFalse(message.hasOptionalSfixed32()); Assert.assertFalse(message.hasOptionalSfixed64()); Assert.assertFalse(message.hasOptionalFloat ()); Assert.assertFalse(message.hasOptionalDouble ()); Assert.assertFalse(message.hasOptionalBool ()); Assert.assertFalse(message.hasOptionalString ()); Assert.assertFalse(message.hasOptionalBytes ()); Assert.assertFalse(message.hasOptionalGroup ()); Assert.assertFalse(message.hasOptionalNestedMessage ()); Assert.assertFalse(message.hasOptionalForeignMessage()); Assert.assertFalse(message.hasOptionalImportMessage ()); Assert.assertFalse(message.hasOptionalNestedEnum ()); Assert.assertFalse(message.hasOptionalForeignEnum()); Assert.assertFalse(message.hasOptionalImportEnum ()); Assert.assertFalse(message.hasOptionalStringPiece()); Assert.assertFalse(message.hasOptionalCord()); // Optional fields without defaults are set to zero or something like it. Assert.assertEquals(0 , message.getOptionalInt32 ()); Assert.assertEquals(0 , message.getOptionalInt64 ()); Assert.assertEquals(0 , message.getOptionalUint32 ()); Assert.assertEquals(0 , message.getOptionalUint64 ()); Assert.assertEquals(0 , message.getOptionalSint32 ()); Assert.assertEquals(0 , message.getOptionalSint64 ()); Assert.assertEquals(0 , message.getOptionalFixed32 ()); Assert.assertEquals(0 , message.getOptionalFixed64 ()); Assert.assertEquals(0 , message.getOptionalSfixed32()); Assert.assertEquals(0 , message.getOptionalSfixed64()); Assert.assertEquals(0 , message.getOptionalFloat (), 0.0); Assert.assertEquals(0 , message.getOptionalDouble (), 0.0); Assert.assertEquals(false, message.getOptionalBool ()); Assert.assertEquals("" , message.getOptionalString ()); Assert.assertEquals(ByteString.EMPTY, message.getOptionalBytes()); // Embedded messages should also be clear. Assert.assertFalse(message.getOptionalGroup ().hasA()); Assert.assertFalse(message.getOptionalNestedMessage ().hasBb()); Assert.assertFalse(message.getOptionalForeignMessage ().hasC()); Assert.assertFalse(message.getOptionalImportMessage ().hasD()); Assert.assertFalse(message.getOptionalPublicImportMessage().hasE()); Assert.assertFalse(message.getOptionalLazyMessage ().hasBb()); Assert.assertEquals(0, message.getOptionalGroup ().getA()); Assert.assertEquals(0, message.getOptionalNestedMessage ().getBb()); Assert.assertEquals(0, message.getOptionalForeignMessage ().getC()); Assert.assertEquals(0, message.getOptionalImportMessage ().getD()); Assert.assertEquals(0, message.getOptionalPublicImportMessage().getE()); Assert.assertEquals(0, message.getOptionalLazyMessage ().getBb()); // Enums without defaults are set to the first value in the enum. Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getOptionalNestedEnum ()); Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getOptionalForeignEnum()); Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getOptionalImportEnum()); Assert.assertEquals("", message.getOptionalStringPiece()); Assert.assertEquals("", message.getOptionalCord()); // Repeated fields are empty. Assert.assertEquals(0, message.getRepeatedInt32Count ()); Assert.assertEquals(0, message.getRepeatedInt64Count ()); Assert.assertEquals(0, message.getRepeatedUint32Count ()); Assert.assertEquals(0, message.getRepeatedUint64Count ()); Assert.assertEquals(0, message.getRepeatedSint32Count ()); Assert.assertEquals(0, message.getRepeatedSint64Count ()); Assert.assertEquals(0, message.getRepeatedFixed32Count ()); Assert.assertEquals(0, message.getRepeatedFixed64Count ()); Assert.assertEquals(0, message.getRepeatedSfixed32Count()); Assert.assertEquals(0, message.getRepeatedSfixed64Count()); Assert.assertEquals(0, message.getRepeatedFloatCount ()); Assert.assertEquals(0, message.getRepeatedDoubleCount ()); Assert.assertEquals(0, message.getRepeatedBoolCount ()); Assert.assertEquals(0, message.getRepeatedStringCount ()); Assert.assertEquals(0, message.getRepeatedBytesCount ()); Assert.assertEquals(0, message.getRepeatedGroupCount ()); Assert.assertEquals(0, message.getRepeatedNestedMessageCount ()); Assert.assertEquals(0, message.getRepeatedForeignMessageCount()); Assert.assertEquals(0, message.getRepeatedImportMessageCount ()); Assert.assertEquals(0, message.getRepeatedLazyMessageCount ()); Assert.assertEquals(0, message.getRepeatedNestedEnumCount ()); Assert.assertEquals(0, message.getRepeatedForeignEnumCount ()); Assert.assertEquals(0, message.getRepeatedImportEnumCount ()); Assert.assertEquals(0, message.getRepeatedStringPieceCount()); Assert.assertEquals(0, message.getRepeatedCordCount()); // hasBlah() should also be false for all default fields. Assert.assertFalse(message.hasDefaultInt32 ()); Assert.assertFalse(message.hasDefaultInt64 ()); Assert.assertFalse(message.hasDefaultUint32 ()); Assert.assertFalse(message.hasDefaultUint64 ()); Assert.assertFalse(message.hasDefaultSint32 ()); Assert.assertFalse(message.hasDefaultSint64 ()); Assert.assertFalse(message.hasDefaultFixed32 ()); Assert.assertFalse(message.hasDefaultFixed64 ()); Assert.assertFalse(message.hasDefaultSfixed32()); Assert.assertFalse(message.hasDefaultSfixed64()); Assert.assertFalse(message.hasDefaultFloat ()); Assert.assertFalse(message.hasDefaultDouble ()); Assert.assertFalse(message.hasDefaultBool ()); Assert.assertFalse(message.hasDefaultString ()); Assert.assertFalse(message.hasDefaultBytes ()); Assert.assertFalse(message.hasDefaultNestedEnum ()); Assert.assertFalse(message.hasDefaultForeignEnum()); Assert.assertFalse(message.hasDefaultImportEnum ()); Assert.assertFalse(message.hasDefaultStringPiece()); Assert.assertFalse(message.hasDefaultCord()); // Fields with defaults have their default values (duh). Assert.assertEquals( 41 , message.getDefaultInt32 ()); Assert.assertEquals( 42 , message.getDefaultInt64 ()); Assert.assertEquals( 43 , message.getDefaultUint32 ()); Assert.assertEquals( 44 , message.getDefaultUint64 ()); Assert.assertEquals(-45 , message.getDefaultSint32 ()); Assert.assertEquals( 46 , message.getDefaultSint64 ()); Assert.assertEquals( 47 , message.getDefaultFixed32 ()); Assert.assertEquals( 48 , message.getDefaultFixed64 ()); Assert.assertEquals( 49 , message.getDefaultSfixed32()); Assert.assertEquals(-50 , message.getDefaultSfixed64()); Assert.assertEquals( 51.5 , message.getDefaultFloat (), 0.0); Assert.assertEquals( 52e3 , message.getDefaultDouble (), 0.0); Assert.assertEquals(true , message.getDefaultBool ()); Assert.assertEquals("hello", message.getDefaultString ()); Assert.assertEquals(toBytes("world"), message.getDefaultBytes()); Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getDefaultNestedEnum ()); Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getDefaultForeignEnum()); Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getDefaultImportEnum()); Assert.assertEquals("abc", message.getDefaultStringPiece()); Assert.assertEquals("123", message.getDefaultCord()); Assert.assertFalse(message.hasOneofUint32()); Assert.assertFalse(message.hasOneofNestedMessage()); Assert.assertFalse(message.hasOneofString()); Assert.assertFalse(message.hasOneofBytes()); } // ------------------------------------------------------------------- /** * Assert (using {@code junit.framework.Assert}} that all fields of * {@code message} are set to the values assigned by {@code setAllFields} * followed by {@code modifyRepeatedFields}. */ public static void assertRepeatedFieldsModified( TestAllTypesOrBuilder message) { // ModifyRepeatedFields only sets the second repeated element of each // field. In addition to verifying this, we also verify that the first // element and size were *not* modified. Assert.assertEquals(2, message.getRepeatedInt32Count ()); Assert.assertEquals(2, message.getRepeatedInt64Count ()); Assert.assertEquals(2, message.getRepeatedUint32Count ()); Assert.assertEquals(2, message.getRepeatedUint64Count ()); Assert.assertEquals(2, message.getRepeatedSint32Count ()); Assert.assertEquals(2, message.getRepeatedSint64Count ()); Assert.assertEquals(2, message.getRepeatedFixed32Count ()); Assert.assertEquals(2, message.getRepeatedFixed64Count ()); Assert.assertEquals(2, message.getRepeatedSfixed32Count()); Assert.assertEquals(2, message.getRepeatedSfixed64Count()); Assert.assertEquals(2, message.getRepeatedFloatCount ()); Assert.assertEquals(2, message.getRepeatedDoubleCount ()); Assert.assertEquals(2, message.getRepeatedBoolCount ()); Assert.assertEquals(2, message.getRepeatedStringCount ()); Assert.assertEquals(2, message.getRepeatedBytesCount ()); Assert.assertEquals(2, message.getRepeatedGroupCount ()); Assert.assertEquals(2, message.getRepeatedNestedMessageCount ()); Assert.assertEquals(2, message.getRepeatedForeignMessageCount()); Assert.assertEquals(2, message.getRepeatedImportMessageCount ()); Assert.assertEquals(2, message.getRepeatedLazyMessageCount ()); Assert.assertEquals(2, message.getRepeatedNestedEnumCount ()); Assert.assertEquals(2, message.getRepeatedForeignEnumCount ()); Assert.assertEquals(2, message.getRepeatedImportEnumCount ()); Assert.assertEquals(2, message.getRepeatedStringPieceCount()); Assert.assertEquals(2, message.getRepeatedCordCount()); Assert.assertEquals(201 , message.getRepeatedInt32 (0)); Assert.assertEquals(202L , message.getRepeatedInt64 (0)); Assert.assertEquals(203 , message.getRepeatedUint32 (0)); Assert.assertEquals(204L , message.getRepeatedUint64 (0)); Assert.assertEquals(205 , message.getRepeatedSint32 (0)); Assert.assertEquals(206L , message.getRepeatedSint64 (0)); Assert.assertEquals(207 , message.getRepeatedFixed32 (0)); Assert.assertEquals(208L , message.getRepeatedFixed64 (0)); Assert.assertEquals(209 , message.getRepeatedSfixed32(0)); Assert.assertEquals(210L , message.getRepeatedSfixed64(0)); Assert.assertEquals(211F , message.getRepeatedFloat (0)); Assert.assertEquals(212D , message.getRepeatedDouble (0)); Assert.assertEquals(true , message.getRepeatedBool (0)); Assert.assertEquals("215", message.getRepeatedString (0)); Assert.assertEquals(toBytes("216"), message.getRepeatedBytes(0)); Assert.assertEquals(217, message.getRepeatedGroup (0).getA()); Assert.assertEquals(218, message.getRepeatedNestedMessage (0).getBb()); Assert.assertEquals(219, message.getRepeatedForeignMessage(0).getC()); Assert.assertEquals(220, message.getRepeatedImportMessage (0).getD()); Assert.assertEquals(227, message.getRepeatedLazyMessage (0).getBb()); Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum (0)); Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getRepeatedForeignEnum(0)); Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getRepeatedImportEnum(0)); Assert.assertEquals("224", message.getRepeatedStringPiece(0)); Assert.assertEquals("225", message.getRepeatedCord(0)); // Actually verify the second (modified) elements now. Assert.assertEquals(501 , message.getRepeatedInt32 (1)); Assert.assertEquals(502L , message.getRepeatedInt64 (1)); Assert.assertEquals(503 , message.getRepeatedUint32 (1)); Assert.assertEquals(504L , message.getRepeatedUint64 (1)); Assert.assertEquals(505 , message.getRepeatedSint32 (1)); Assert.assertEquals(506L , message.getRepeatedSint64 (1)); Assert.assertEquals(507 , message.getRepeatedFixed32 (1)); Assert.assertEquals(508L , message.getRepeatedFixed64 (1)); Assert.assertEquals(509 , message.getRepeatedSfixed32(1)); Assert.assertEquals(510L , message.getRepeatedSfixed64(1)); Assert.assertEquals(511F , message.getRepeatedFloat (1)); Assert.assertEquals(512D , message.getRepeatedDouble (1)); Assert.assertEquals(true , message.getRepeatedBool (1)); Assert.assertEquals("515", message.getRepeatedString (1)); Assert.assertEquals(toBytes("516"), message.getRepeatedBytes(1)); Assert.assertEquals(517, message.getRepeatedGroup (1).getA()); Assert.assertEquals(518, message.getRepeatedNestedMessage (1).getBb()); Assert.assertEquals(519, message.getRepeatedForeignMessage(1).getC()); Assert.assertEquals(520, message.getRepeatedImportMessage (1).getD()); Assert.assertEquals(527, message.getRepeatedLazyMessage (1).getBb()); Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getRepeatedNestedEnum (1)); Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getRepeatedForeignEnum(1)); Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getRepeatedImportEnum(1)); Assert.assertEquals("524", message.getRepeatedStringPiece(1)); Assert.assertEquals("525", message.getRepeatedCord(1)); } /** * Set every field of {@code message} to a unique value. */ public static void setPackedFields(TestPackedTypes.Builder message) { message.addPackedInt32 (601); message.addPackedInt64 (602); message.addPackedUint32 (603); message.addPackedUint64 (604); message.addPackedSint32 (605); message.addPackedSint64 (606); message.addPackedFixed32 (607); message.addPackedFixed64 (608); message.addPackedSfixed32(609); message.addPackedSfixed64(610); message.addPackedFloat (611); message.addPackedDouble (612); message.addPackedBool (true); message.addPackedEnum (ForeignEnum.FOREIGN_BAR); // Add a second one of each field. message.addPackedInt32 (701); message.addPackedInt64 (702); message.addPackedUint32 (703); message.addPackedUint64 (704); message.addPackedSint32 (705); message.addPackedSint64 (706); message.addPackedFixed32 (707); message.addPackedFixed64 (708); message.addPackedSfixed32(709); message.addPackedSfixed64(710); message.addPackedFloat (711); message.addPackedDouble (712); message.addPackedBool (false); message.addPackedEnum (ForeignEnum.FOREIGN_BAZ); } /** * Set every field of {@code message} to a unique value. Must correspond with * the values applied by {@code setPackedFields}. */ public static void setUnpackedFields(TestUnpackedTypes.Builder message) { message.addUnpackedInt32 (601); message.addUnpackedInt64 (602); message.addUnpackedUint32 (603); message.addUnpackedUint64 (604); message.addUnpackedSint32 (605); message.addUnpackedSint64 (606); message.addUnpackedFixed32 (607); message.addUnpackedFixed64 (608); message.addUnpackedSfixed32(609); message.addUnpackedSfixed64(610); message.addUnpackedFloat (611); message.addUnpackedDouble (612); message.addUnpackedBool (true); message.addUnpackedEnum (ForeignEnum.FOREIGN_BAR); // Add a second one of each field. message.addUnpackedInt32 (701); message.addUnpackedInt64 (702); message.addUnpackedUint32 (703); message.addUnpackedUint64 (704); message.addUnpackedSint32 (705); message.addUnpackedSint64 (706); message.addUnpackedFixed32 (707); message.addUnpackedFixed64 (708); message.addUnpackedSfixed32(709); message.addUnpackedSfixed64(710); message.addUnpackedFloat (711); message.addUnpackedDouble (712); message.addUnpackedBool (false); message.addUnpackedEnum (ForeignEnum.FOREIGN_BAZ); } /** * Assert (using {@code junit.framework.Assert}} that all fields of * {@code message} are set to the values assigned by {@code setPackedFields}. */ public static void assertPackedFieldsSet(TestPackedTypes message) { Assert.assertEquals(2, message.getPackedInt32Count ()); Assert.assertEquals(2, message.getPackedInt64Count ()); Assert.assertEquals(2, message.getPackedUint32Count ()); Assert.assertEquals(2, message.getPackedUint64Count ()); Assert.assertEquals(2, message.getPackedSint32Count ()); Assert.assertEquals(2, message.getPackedSint64Count ()); Assert.assertEquals(2, message.getPackedFixed32Count ()); Assert.assertEquals(2, message.getPackedFixed64Count ()); Assert.assertEquals(2, message.getPackedSfixed32Count()); Assert.assertEquals(2, message.getPackedSfixed64Count()); Assert.assertEquals(2, message.getPackedFloatCount ()); Assert.assertEquals(2, message.getPackedDoubleCount ()); Assert.assertEquals(2, message.getPackedBoolCount ()); Assert.assertEquals(2, message.getPackedEnumCount ()); Assert.assertEquals(601 , message.getPackedInt32 (0)); Assert.assertEquals(602 , message.getPackedInt64 (0)); Assert.assertEquals(603 , message.getPackedUint32 (0)); Assert.assertEquals(604 , message.getPackedUint64 (0)); Assert.assertEquals(605 , message.getPackedSint32 (0)); Assert.assertEquals(606 , message.getPackedSint64 (0)); Assert.assertEquals(607 , message.getPackedFixed32 (0)); Assert.assertEquals(608 , message.getPackedFixed64 (0)); Assert.assertEquals(609 , message.getPackedSfixed32(0)); Assert.assertEquals(610 , message.getPackedSfixed64(0)); Assert.assertEquals(611 , message.getPackedFloat (0), 0.0); Assert.assertEquals(612 , message.getPackedDouble (0), 0.0); Assert.assertEquals(true , message.getPackedBool (0)); Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getPackedEnum(0)); Assert.assertEquals(701 , message.getPackedInt32 (1)); Assert.assertEquals(702 , message.getPackedInt64 (1)); Assert.assertEquals(703 , message.getPackedUint32 (1)); Assert.assertEquals(704 , message.getPackedUint64 (1)); Assert.assertEquals(705 , message.getPackedSint32 (1)); Assert.assertEquals(706 , message.getPackedSint64 (1)); Assert.assertEquals(707 , message.getPackedFixed32 (1)); Assert.assertEquals(708 , message.getPackedFixed64 (1)); Assert.assertEquals(709 , message.getPackedSfixed32(1)); Assert.assertEquals(710 , message.getPackedSfixed64(1)); Assert.assertEquals(711 , message.getPackedFloat (1), 0.0); Assert.assertEquals(712 , message.getPackedDouble (1), 0.0); Assert.assertEquals(false, message.getPackedBool (1)); Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getPackedEnum(1)); } /** * Assert (using {@code junit.framework.Assert}} that all fields of * {@code message} are set to the values assigned by {@code setUnpackedFields}. */ public static void assertUnpackedFieldsSet(TestUnpackedTypes message) { Assert.assertEquals(2, message.getUnpackedInt32Count ()); Assert.assertEquals(2, message.getUnpackedInt64Count ()); Assert.assertEquals(2, message.getUnpackedUint32Count ()); Assert.assertEquals(2, message.getUnpackedUint64Count ()); Assert.assertEquals(2, message.getUnpackedSint32Count ()); Assert.assertEquals(2, message.getUnpackedSint64Count ()); Assert.assertEquals(2, message.getUnpackedFixed32Count ()); Assert.assertEquals(2, message.getUnpackedFixed64Count ()); Assert.assertEquals(2, message.getUnpackedSfixed32Count()); Assert.assertEquals(2, message.getUnpackedSfixed64Count()); Assert.assertEquals(2, message.getUnpackedFloatCount ()); Assert.assertEquals(2, message.getUnpackedDoubleCount ()); Assert.assertEquals(2, message.getUnpackedBoolCount ()); Assert.assertEquals(2, message.getUnpackedEnumCount ()); Assert.assertEquals(601 , message.getUnpackedInt32 (0)); Assert.assertEquals(602 , message.getUnpackedInt64 (0)); Assert.assertEquals(603 , message.getUnpackedUint32 (0)); Assert.assertEquals(604 , message.getUnpackedUint64 (0)); Assert.assertEquals(605 , message.getUnpackedSint32 (0)); Assert.assertEquals(606 , message.getUnpackedSint64 (0)); Assert.assertEquals(607 , message.getUnpackedFixed32 (0)); Assert.assertEquals(608 , message.getUnpackedFixed64 (0)); Assert.assertEquals(609 , message.getUnpackedSfixed32(0)); Assert.assertEquals(610 , message.getUnpackedSfixed64(0)); Assert.assertEquals(611 , message.getUnpackedFloat (0), 0.0); Assert.assertEquals(612 , message.getUnpackedDouble (0), 0.0); Assert.assertEquals(true , message.getUnpackedBool (0)); Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getUnpackedEnum(0)); Assert.assertEquals(701 , message.getUnpackedInt32 (1)); Assert.assertEquals(702 , message.getUnpackedInt64 (1)); Assert.assertEquals(703 , message.getUnpackedUint32 (1)); Assert.assertEquals(704 , message.getUnpackedUint64 (1)); Assert.assertEquals(705 , message.getUnpackedSint32 (1)); Assert.assertEquals(706 , message.getUnpackedSint64 (1)); Assert.assertEquals(707 , message.getUnpackedFixed32 (1)); Assert.assertEquals(708 , message.getUnpackedFixed64 (1)); Assert.assertEquals(709 , message.getUnpackedSfixed32(1)); Assert.assertEquals(710 , message.getUnpackedSfixed64(1)); Assert.assertEquals(711 , message.getUnpackedFloat (1), 0.0); Assert.assertEquals(712 , message.getUnpackedDouble (1), 0.0); Assert.assertEquals(false, message.getUnpackedBool (1)); Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getUnpackedEnum(1)); } // =================================================================== // Like above, but for extensions // Java gets confused with things like assertEquals(int, Integer): it can't // decide whether to call assertEquals(int, int) or assertEquals(Object, // Object). So we define these methods to help it. private static void assertEqualsExactType(int a, int b) { Assert.assertEquals(a, b); } private static void assertEqualsExactType(long a, long b) { Assert.assertEquals(a, b); } private static void assertEqualsExactType(float a, float b) { Assert.assertEquals(a, b, 0.0); } private static void assertEqualsExactType(double a, double b) { Assert.assertEquals(a, b, 0.0); } private static void assertEqualsExactType(boolean a, boolean b) { Assert.assertEquals(a, b); } private static void assertEqualsExactType(String a, String b) { Assert.assertEquals(a, b); } private static void assertEqualsExactType(ByteString a, ByteString b) { Assert.assertEquals(a, b); } private static void assertEqualsExactType(TestAllTypes.NestedEnum a, TestAllTypes.NestedEnum b) { Assert.assertEquals(a, b); } private static void assertEqualsExactType(ForeignEnum a, ForeignEnum b) { Assert.assertEquals(a, b); } private static void assertEqualsExactType(ImportEnum a, ImportEnum b) { Assert.assertEquals(a, b); } private static void assertEqualsExactType(TestAllTypesLite.NestedEnum a, TestAllTypesLite.NestedEnum b) { Assert.assertEquals(a, b); } private static void assertEqualsExactType(ForeignEnumLite a, ForeignEnumLite b) { Assert.assertEquals(a, b); } private static void assertEqualsExactType(ImportEnumLite a, ImportEnumLite b) { Assert.assertEquals(a, b); } /** * Get an unmodifiable {@link ExtensionRegistry} containing all the * extensions of {@code TestAllExtensions}. */ public static ExtensionRegistry getExtensionRegistry() { ExtensionRegistry registry = ExtensionRegistry.newInstance(); registerAllExtensions(registry); return registry.getUnmodifiable(); } public static ExtensionRegistryLite getExtensionRegistryLite() { ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance(); registerAllExtensionsLite(registry); return registry.getUnmodifiable(); } /** * Register all of {@code TestAllExtensions}'s extensions with the * given {@link ExtensionRegistry}. */ public static void registerAllExtensions(ExtensionRegistry registry) { UnittestProto.registerAllExtensions(registry); registerAllExtensionsLite(registry); } public static void registerAllExtensionsLite(ExtensionRegistryLite registry) { UnittestLite.registerAllExtensions(registry); } /** * Set every field of {@code message} to the values expected by * {@code assertAllExtensionsSet()}. */ public static void setAllExtensions(TestAllExtensions.Builder message) { message.setExtension(optionalInt32Extension , 101); message.setExtension(optionalInt64Extension , 102L); message.setExtension(optionalUint32Extension , 103); message.setExtension(optionalUint64Extension , 104L); message.setExtension(optionalSint32Extension , 105); message.setExtension(optionalSint64Extension , 106L); message.setExtension(optionalFixed32Extension , 107); message.setExtension(optionalFixed64Extension , 108L); message.setExtension(optionalSfixed32Extension, 109); message.setExtension(optionalSfixed64Extension, 110L); message.setExtension(optionalFloatExtension , 111F); message.setExtension(optionalDoubleExtension , 112D); message.setExtension(optionalBoolExtension , true); message.setExtension(optionalStringExtension , "115"); message.setExtension(optionalBytesExtension , toBytes("116")); message.setExtension(optionalGroupExtension, OptionalGroup_extension.newBuilder().setA(117).build()); message.setExtension(optionalNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(118).build()); message.setExtension(optionalForeignMessageExtension, ForeignMessage.newBuilder().setC(119).build()); message.setExtension(optionalImportMessageExtension, ImportMessage.newBuilder().setD(120).build()); message.setExtension(optionalPublicImportMessageExtension, PublicImportMessage.newBuilder().setE(126).build()); message.setExtension(optionalLazyMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(127).build()); message.setExtension(optionalNestedEnumExtension, TestAllTypes.NestedEnum.BAZ); message.setExtension(optionalForeignEnumExtension, ForeignEnum.FOREIGN_BAZ); message.setExtension(optionalImportEnumExtension, ImportEnum.IMPORT_BAZ); message.setExtension(optionalStringPieceExtension, "124"); message.setExtension(optionalCordExtension, "125"); // ----------------------------------------------------------------- message.addExtension(repeatedInt32Extension , 201); message.addExtension(repeatedInt64Extension , 202L); message.addExtension(repeatedUint32Extension , 203); message.addExtension(repeatedUint64Extension , 204L); message.addExtension(repeatedSint32Extension , 205); message.addExtension(repeatedSint64Extension , 206L); message.addExtension(repeatedFixed32Extension , 207); message.addExtension(repeatedFixed64Extension , 208L); message.addExtension(repeatedSfixed32Extension, 209); message.addExtension(repeatedSfixed64Extension, 210L); message.addExtension(repeatedFloatExtension , 211F); message.addExtension(repeatedDoubleExtension , 212D); message.addExtension(repeatedBoolExtension , true); message.addExtension(repeatedStringExtension , "215"); message.addExtension(repeatedBytesExtension , toBytes("216")); message.addExtension(repeatedGroupExtension, RepeatedGroup_extension.newBuilder().setA(217).build()); message.addExtension(repeatedNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(218).build()); message.addExtension(repeatedForeignMessageExtension, ForeignMessage.newBuilder().setC(219).build()); message.addExtension(repeatedImportMessageExtension, ImportMessage.newBuilder().setD(220).build()); message.addExtension(repeatedLazyMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(227).build()); message.addExtension(repeatedNestedEnumExtension, TestAllTypes.NestedEnum.BAR); message.addExtension(repeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAR); message.addExtension(repeatedImportEnumExtension, ImportEnum.IMPORT_BAR); message.addExtension(repeatedStringPieceExtension, "224"); message.addExtension(repeatedCordExtension, "225"); // Add a second one of each field. message.addExtension(repeatedInt32Extension , 301); message.addExtension(repeatedInt64Extension , 302L); message.addExtension(repeatedUint32Extension , 303); message.addExtension(repeatedUint64Extension , 304L); message.addExtension(repeatedSint32Extension , 305); message.addExtension(repeatedSint64Extension , 306L); message.addExtension(repeatedFixed32Extension , 307); message.addExtension(repeatedFixed64Extension , 308L); message.addExtension(repeatedSfixed32Extension, 309); message.addExtension(repeatedSfixed64Extension, 310L); message.addExtension(repeatedFloatExtension , 311F); message.addExtension(repeatedDoubleExtension , 312D); message.addExtension(repeatedBoolExtension , false); message.addExtension(repeatedStringExtension , "315"); message.addExtension(repeatedBytesExtension , toBytes("316")); message.addExtension(repeatedGroupExtension, RepeatedGroup_extension.newBuilder().setA(317).build()); message.addExtension(repeatedNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(318).build()); message.addExtension(repeatedForeignMessageExtension, ForeignMessage.newBuilder().setC(319).build()); message.addExtension(repeatedImportMessageExtension, ImportMessage.newBuilder().setD(320).build()); message.addExtension(repeatedLazyMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(327).build()); message.addExtension(repeatedNestedEnumExtension, TestAllTypes.NestedEnum.BAZ); message.addExtension(repeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAZ); message.addExtension(repeatedImportEnumExtension, ImportEnum.IMPORT_BAZ); message.addExtension(repeatedStringPieceExtension, "324"); message.addExtension(repeatedCordExtension, "325"); // ----------------------------------------------------------------- message.setExtension(defaultInt32Extension , 401); message.setExtension(defaultInt64Extension , 402L); message.setExtension(defaultUint32Extension , 403); message.setExtension(defaultUint64Extension , 404L); message.setExtension(defaultSint32Extension , 405); message.setExtension(defaultSint64Extension , 406L); message.setExtension(defaultFixed32Extension , 407); message.setExtension(defaultFixed64Extension , 408L); message.setExtension(defaultSfixed32Extension, 409); message.setExtension(defaultSfixed64Extension, 410L); message.setExtension(defaultFloatExtension , 411F); message.setExtension(defaultDoubleExtension , 412D); message.setExtension(defaultBoolExtension , false); message.setExtension(defaultStringExtension , "415"); message.setExtension(defaultBytesExtension , toBytes("416")); message.setExtension(defaultNestedEnumExtension, TestAllTypes.NestedEnum.FOO); message.setExtension(defaultForeignEnumExtension, ForeignEnum.FOREIGN_FOO); message.setExtension(defaultImportEnumExtension, ImportEnum.IMPORT_FOO); message.setExtension(defaultStringPieceExtension, "424"); message.setExtension(defaultCordExtension, "425"); message.setExtension(oneofUint32Extension, 601); message.setExtension(oneofNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(602).build()); message.setExtension(oneofStringExtension, "603"); message.setExtension(oneofBytesExtension, toBytes("604")); } // ------------------------------------------------------------------- /** * Modify the repeated extensions of {@code message} to contain the values * expected by {@code assertRepeatedExtensionsModified()}. */ public static void modifyRepeatedExtensions( TestAllExtensions.Builder message) { message.setExtension(repeatedInt32Extension , 1, 501); message.setExtension(repeatedInt64Extension , 1, 502L); message.setExtension(repeatedUint32Extension , 1, 503); message.setExtension(repeatedUint64Extension , 1, 504L); message.setExtension(repeatedSint32Extension , 1, 505); message.setExtension(repeatedSint64Extension , 1, 506L); message.setExtension(repeatedFixed32Extension , 1, 507); message.setExtension(repeatedFixed64Extension , 1, 508L); message.setExtension(repeatedSfixed32Extension, 1, 509); message.setExtension(repeatedSfixed64Extension, 1, 510L); message.setExtension(repeatedFloatExtension , 1, 511F); message.setExtension(repeatedDoubleExtension , 1, 512D); message.setExtension(repeatedBoolExtension , 1, true); message.setExtension(repeatedStringExtension , 1, "515"); message.setExtension(repeatedBytesExtension , 1, toBytes("516")); message.setExtension(repeatedGroupExtension, 1, RepeatedGroup_extension.newBuilder().setA(517).build()); message.setExtension(repeatedNestedMessageExtension, 1, TestAllTypes.NestedMessage.newBuilder().setBb(518).build()); message.setExtension(repeatedForeignMessageExtension, 1, ForeignMessage.newBuilder().setC(519).build()); message.setExtension(repeatedImportMessageExtension, 1, ImportMessage.newBuilder().setD(520).build()); message.setExtension(repeatedLazyMessageExtension, 1, TestAllTypes.NestedMessage.newBuilder().setBb(527).build()); message.setExtension(repeatedNestedEnumExtension , 1, TestAllTypes.NestedEnum.FOO); message.setExtension(repeatedForeignEnumExtension, 1, ForeignEnum.FOREIGN_FOO); message.setExtension(repeatedImportEnumExtension , 1, ImportEnum.IMPORT_FOO); message.setExtension(repeatedStringPieceExtension, 1, "524"); message.setExtension(repeatedCordExtension, 1, "525"); } // ------------------------------------------------------------------- /** * Assert (using {@code junit.framework.Assert}} that all extensions of * {@code message} are set to the values assigned by {@code setAllExtensions}. */ public static void assertAllExtensionsSet( TestAllExtensionsOrBuilder message) { Assert.assertTrue(message.hasExtension(optionalInt32Extension )); Assert.assertTrue(message.hasExtension(optionalInt64Extension )); Assert.assertTrue(message.hasExtension(optionalUint32Extension )); Assert.assertTrue(message.hasExtension(optionalUint64Extension )); Assert.assertTrue(message.hasExtension(optionalSint32Extension )); Assert.assertTrue(message.hasExtension(optionalSint64Extension )); Assert.assertTrue(message.hasExtension(optionalFixed32Extension )); Assert.assertTrue(message.hasExtension(optionalFixed64Extension )); Assert.assertTrue(message.hasExtension(optionalSfixed32Extension)); Assert.assertTrue(message.hasExtension(optionalSfixed64Extension)); Assert.assertTrue(message.hasExtension(optionalFloatExtension )); Assert.assertTrue(message.hasExtension(optionalDoubleExtension )); Assert.assertTrue(message.hasExtension(optionalBoolExtension )); Assert.assertTrue(message.hasExtension(optionalStringExtension )); Assert.assertTrue(message.hasExtension(optionalBytesExtension )); Assert.assertTrue(message.hasExtension(optionalGroupExtension )); Assert.assertTrue(message.hasExtension(optionalNestedMessageExtension )); Assert.assertTrue(message.hasExtension(optionalForeignMessageExtension)); Assert.assertTrue(message.hasExtension(optionalImportMessageExtension )); Assert.assertTrue(message.getExtension(optionalGroupExtension ).hasA()); Assert.assertTrue(message.getExtension(optionalNestedMessageExtension ).hasBb()); Assert.assertTrue(message.getExtension(optionalForeignMessageExtension).hasC()); Assert.assertTrue(message.getExtension(optionalImportMessageExtension ).hasD()); Assert.assertTrue(message.hasExtension(optionalNestedEnumExtension )); Assert.assertTrue(message.hasExtension(optionalForeignEnumExtension)); Assert.assertTrue(message.hasExtension(optionalImportEnumExtension )); Assert.assertTrue(message.hasExtension(optionalStringPieceExtension)); Assert.assertTrue(message.hasExtension(optionalCordExtension)); assertEqualsExactType(101 , message.getExtension(optionalInt32Extension )); assertEqualsExactType(102L , message.getExtension(optionalInt64Extension )); assertEqualsExactType(103 , message.getExtension(optionalUint32Extension )); assertEqualsExactType(104L , message.getExtension(optionalUint64Extension )); assertEqualsExactType(105 , message.getExtension(optionalSint32Extension )); assertEqualsExactType(106L , message.getExtension(optionalSint64Extension )); assertEqualsExactType(107 , message.getExtension(optionalFixed32Extension )); assertEqualsExactType(108L , message.getExtension(optionalFixed64Extension )); assertEqualsExactType(109 , message.getExtension(optionalSfixed32Extension)); assertEqualsExactType(110L , message.getExtension(optionalSfixed64Extension)); assertEqualsExactType(111F , message.getExtension(optionalFloatExtension )); assertEqualsExactType(112D , message.getExtension(optionalDoubleExtension )); assertEqualsExactType(true , message.getExtension(optionalBoolExtension )); assertEqualsExactType("115", message.getExtension(optionalStringExtension )); assertEqualsExactType(toBytes("116"), message.getExtension(optionalBytesExtension)); assertEqualsExactType(117, message.getExtension(optionalGroupExtension ).getA()); assertEqualsExactType(118, message.getExtension(optionalNestedMessageExtension ).getBb()); assertEqualsExactType(119, message.getExtension(optionalForeignMessageExtension ).getC()); assertEqualsExactType(120, message.getExtension(optionalImportMessageExtension ).getD()); assertEqualsExactType(126, message.getExtension(optionalPublicImportMessageExtension).getE()); assertEqualsExactType(127, message.getExtension(optionalLazyMessageExtension ).getBb()); assertEqualsExactType(TestAllTypes.NestedEnum.BAZ, message.getExtension(optionalNestedEnumExtension)); assertEqualsExactType(ForeignEnum.FOREIGN_BAZ, message.getExtension(optionalForeignEnumExtension)); assertEqualsExactType(ImportEnum.IMPORT_BAZ, message.getExtension(optionalImportEnumExtension)); assertEqualsExactType("124", message.getExtension(optionalStringPieceExtension)); assertEqualsExactType("125", message.getExtension(optionalCordExtension)); // ----------------------------------------------------------------- Assert.assertEquals(2, message.getExtensionCount(repeatedInt32Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedInt64Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedUint32Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedUint64Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedSint32Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedSint64Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32Extension)); Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64Extension)); Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtension)); Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtension)); Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtension)); assertEqualsExactType(201 , message.getExtension(repeatedInt32Extension , 0)); assertEqualsExactType(202L , message.getExtension(repeatedInt64Extension , 0)); assertEqualsExactType(203 , message.getExtension(repeatedUint32Extension , 0)); assertEqualsExactType(204L , message.getExtension(repeatedUint64Extension , 0)); assertEqualsExactType(205 , message.getExtension(repeatedSint32Extension , 0)); assertEqualsExactType(206L , message.getExtension(repeatedSint64Extension , 0)); assertEqualsExactType(207 , message.getExtension(repeatedFixed32Extension , 0)); assertEqualsExactType(208L , message.getExtension(repeatedFixed64Extension , 0)); assertEqualsExactType(209 , message.getExtension(repeatedSfixed32Extension, 0)); assertEqualsExactType(210L , message.getExtension(repeatedSfixed64Extension, 0)); assertEqualsExactType(211F , message.getExtension(repeatedFloatExtension , 0)); assertEqualsExactType(212D , message.getExtension(repeatedDoubleExtension , 0)); assertEqualsExactType(true , message.getExtension(repeatedBoolExtension , 0)); assertEqualsExactType("215", message.getExtension(repeatedStringExtension , 0)); assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtension, 0)); assertEqualsExactType(217, message.getExtension(repeatedGroupExtension , 0).getA()); assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtension , 0).getBb()); assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtension, 0).getC()); assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtension , 0).getD()); assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtension , 0).getBb()); assertEqualsExactType(TestAllTypes.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtension, 0)); assertEqualsExactType(ForeignEnum.FOREIGN_BAR, message.getExtension(repeatedForeignEnumExtension, 0)); assertEqualsExactType(ImportEnum.IMPORT_BAR, message.getExtension(repeatedImportEnumExtension, 0)); assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtension, 0)); assertEqualsExactType("225", message.getExtension(repeatedCordExtension, 0)); assertEqualsExactType(301 , message.getExtension(repeatedInt32Extension , 1)); assertEqualsExactType(302L , message.getExtension(repeatedInt64Extension , 1)); assertEqualsExactType(303 , message.getExtension(repeatedUint32Extension , 1)); assertEqualsExactType(304L , message.getExtension(repeatedUint64Extension , 1)); assertEqualsExactType(305 , message.getExtension(repeatedSint32Extension , 1)); assertEqualsExactType(306L , message.getExtension(repeatedSint64Extension , 1)); assertEqualsExactType(307 , message.getExtension(repeatedFixed32Extension , 1)); assertEqualsExactType(308L , message.getExtension(repeatedFixed64Extension , 1)); assertEqualsExactType(309 , message.getExtension(repeatedSfixed32Extension, 1)); assertEqualsExactType(310L , message.getExtension(repeatedSfixed64Extension, 1)); assertEqualsExactType(311F , message.getExtension(repeatedFloatExtension , 1)); assertEqualsExactType(312D , message.getExtension(repeatedDoubleExtension , 1)); assertEqualsExactType(false, message.getExtension(repeatedBoolExtension , 1)); assertEqualsExactType("315", message.getExtension(repeatedStringExtension , 1)); assertEqualsExactType(toBytes("316"), message.getExtension(repeatedBytesExtension, 1)); assertEqualsExactType(317, message.getExtension(repeatedGroupExtension , 1).getA()); assertEqualsExactType(318, message.getExtension(repeatedNestedMessageExtension , 1).getBb()); assertEqualsExactType(319, message.getExtension(repeatedForeignMessageExtension, 1).getC()); assertEqualsExactType(320, message.getExtension(repeatedImportMessageExtension , 1).getD()); assertEqualsExactType(327, message.getExtension(repeatedLazyMessageExtension , 1).getBb()); assertEqualsExactType(TestAllTypes.NestedEnum.BAZ, message.getExtension(repeatedNestedEnumExtension, 1)); assertEqualsExactType(ForeignEnum.FOREIGN_BAZ, message.getExtension(repeatedForeignEnumExtension, 1)); assertEqualsExactType(ImportEnum.IMPORT_BAZ, message.getExtension(repeatedImportEnumExtension, 1)); assertEqualsExactType("324", message.getExtension(repeatedStringPieceExtension, 1)); assertEqualsExactType("325", message.getExtension(repeatedCordExtension, 1)); // ----------------------------------------------------------------- Assert.assertTrue(message.hasExtension(defaultInt32Extension )); Assert.assertTrue(message.hasExtension(defaultInt64Extension )); Assert.assertTrue(message.hasExtension(defaultUint32Extension )); Assert.assertTrue(message.hasExtension(defaultUint64Extension )); Assert.assertTrue(message.hasExtension(defaultSint32Extension )); Assert.assertTrue(message.hasExtension(defaultSint64Extension )); Assert.assertTrue(message.hasExtension(defaultFixed32Extension )); Assert.assertTrue(message.hasExtension(defaultFixed64Extension )); Assert.assertTrue(message.hasExtension(defaultSfixed32Extension)); Assert.assertTrue(message.hasExtension(defaultSfixed64Extension)); Assert.assertTrue(message.hasExtension(defaultFloatExtension )); Assert.assertTrue(message.hasExtension(defaultDoubleExtension )); Assert.assertTrue(message.hasExtension(defaultBoolExtension )); Assert.assertTrue(message.hasExtension(defaultStringExtension )); Assert.assertTrue(message.hasExtension(defaultBytesExtension )); Assert.assertTrue(message.hasExtension(defaultNestedEnumExtension )); Assert.assertTrue(message.hasExtension(defaultForeignEnumExtension)); Assert.assertTrue(message.hasExtension(defaultImportEnumExtension )); Assert.assertTrue(message.hasExtension(defaultStringPieceExtension)); Assert.assertTrue(message.hasExtension(defaultCordExtension)); assertEqualsExactType(401 , message.getExtension(defaultInt32Extension )); assertEqualsExactType(402L , message.getExtension(defaultInt64Extension )); assertEqualsExactType(403 , message.getExtension(defaultUint32Extension )); assertEqualsExactType(404L , message.getExtension(defaultUint64Extension )); assertEqualsExactType(405 , message.getExtension(defaultSint32Extension )); assertEqualsExactType(406L , message.getExtension(defaultSint64Extension )); assertEqualsExactType(407 , message.getExtension(defaultFixed32Extension )); assertEqualsExactType(408L , message.getExtension(defaultFixed64Extension )); assertEqualsExactType(409 , message.getExtension(defaultSfixed32Extension)); assertEqualsExactType(410L , message.getExtension(defaultSfixed64Extension)); assertEqualsExactType(411F , message.getExtension(defaultFloatExtension )); assertEqualsExactType(412D , message.getExtension(defaultDoubleExtension )); assertEqualsExactType(false, message.getExtension(defaultBoolExtension )); assertEqualsExactType("415", message.getExtension(defaultStringExtension )); assertEqualsExactType(toBytes("416"), message.getExtension(defaultBytesExtension)); assertEqualsExactType(TestAllTypes.NestedEnum.FOO, message.getExtension(defaultNestedEnumExtension )); assertEqualsExactType(ForeignEnum.FOREIGN_FOO, message.getExtension(defaultForeignEnumExtension)); assertEqualsExactType(ImportEnum.IMPORT_FOO, message.getExtension(defaultImportEnumExtension)); assertEqualsExactType("424", message.getExtension(defaultStringPieceExtension)); assertEqualsExactType("425", message.getExtension(defaultCordExtension)); Assert.assertTrue(message.hasExtension(oneofBytesExtension)); assertEqualsExactType(toBytes("604"), message.getExtension(oneofBytesExtension)); } // ------------------------------------------------------------------- /** * Assert (using {@code junit.framework.Assert}} that all extensions of * {@code message} are cleared, and that getting the extensions returns their * default values. */ public static void assertExtensionsClear(TestAllExtensionsOrBuilder message) { // hasBlah() should initially be false for all optional fields. Assert.assertFalse(message.hasExtension(optionalInt32Extension )); Assert.assertFalse(message.hasExtension(optionalInt64Extension )); Assert.assertFalse(message.hasExtension(optionalUint32Extension )); Assert.assertFalse(message.hasExtension(optionalUint64Extension )); Assert.assertFalse(message.hasExtension(optionalSint32Extension )); Assert.assertFalse(message.hasExtension(optionalSint64Extension )); Assert.assertFalse(message.hasExtension(optionalFixed32Extension )); Assert.assertFalse(message.hasExtension(optionalFixed64Extension )); Assert.assertFalse(message.hasExtension(optionalSfixed32Extension)); Assert.assertFalse(message.hasExtension(optionalSfixed64Extension)); Assert.assertFalse(message.hasExtension(optionalFloatExtension )); Assert.assertFalse(message.hasExtension(optionalDoubleExtension )); Assert.assertFalse(message.hasExtension(optionalBoolExtension )); Assert.assertFalse(message.hasExtension(optionalStringExtension )); Assert.assertFalse(message.hasExtension(optionalBytesExtension )); Assert.assertFalse(message.hasExtension(optionalGroupExtension )); Assert.assertFalse(message.hasExtension(optionalNestedMessageExtension )); Assert.assertFalse(message.hasExtension(optionalForeignMessageExtension)); Assert.assertFalse(message.hasExtension(optionalImportMessageExtension )); Assert.assertFalse(message.hasExtension(optionalNestedEnumExtension )); Assert.assertFalse(message.hasExtension(optionalForeignEnumExtension)); Assert.assertFalse(message.hasExtension(optionalImportEnumExtension )); Assert.assertFalse(message.hasExtension(optionalStringPieceExtension)); Assert.assertFalse(message.hasExtension(optionalCordExtension)); // Optional fields without defaults are set to zero or something like it. assertEqualsExactType(0 , message.getExtension(optionalInt32Extension )); assertEqualsExactType(0L , message.getExtension(optionalInt64Extension )); assertEqualsExactType(0 , message.getExtension(optionalUint32Extension )); assertEqualsExactType(0L , message.getExtension(optionalUint64Extension )); assertEqualsExactType(0 , message.getExtension(optionalSint32Extension )); assertEqualsExactType(0L , message.getExtension(optionalSint64Extension )); assertEqualsExactType(0 , message.getExtension(optionalFixed32Extension )); assertEqualsExactType(0L , message.getExtension(optionalFixed64Extension )); assertEqualsExactType(0 , message.getExtension(optionalSfixed32Extension)); assertEqualsExactType(0L , message.getExtension(optionalSfixed64Extension)); assertEqualsExactType(0F , message.getExtension(optionalFloatExtension )); assertEqualsExactType(0D , message.getExtension(optionalDoubleExtension )); assertEqualsExactType(false, message.getExtension(optionalBoolExtension )); assertEqualsExactType("" , message.getExtension(optionalStringExtension )); assertEqualsExactType(ByteString.EMPTY, message.getExtension(optionalBytesExtension)); // Embedded messages should also be clear. Assert.assertFalse(message.getExtension(optionalGroupExtension ).hasA()); Assert.assertFalse(message.getExtension(optionalNestedMessageExtension ).hasBb()); Assert.assertFalse(message.getExtension(optionalForeignMessageExtension).hasC()); Assert.assertFalse(message.getExtension(optionalImportMessageExtension ).hasD()); assertEqualsExactType(0, message.getExtension(optionalGroupExtension ).getA()); assertEqualsExactType(0, message.getExtension(optionalNestedMessageExtension ).getBb()); assertEqualsExactType(0, message.getExtension(optionalForeignMessageExtension).getC()); assertEqualsExactType(0, message.getExtension(optionalImportMessageExtension ).getD()); // Enums without defaults are set to the first value in the enum. assertEqualsExactType(TestAllTypes.NestedEnum.FOO, message.getExtension(optionalNestedEnumExtension )); assertEqualsExactType(ForeignEnum.FOREIGN_FOO, message.getExtension(optionalForeignEnumExtension)); assertEqualsExactType(ImportEnum.IMPORT_FOO, message.getExtension(optionalImportEnumExtension)); assertEqualsExactType("", message.getExtension(optionalStringPieceExtension)); assertEqualsExactType("", message.getExtension(optionalCordExtension)); // Repeated fields are empty. Assert.assertEquals(0, message.getExtensionCount(repeatedInt32Extension )); Assert.assertEquals(0, message.getExtensionCount(repeatedInt64Extension )); Assert.assertEquals(0, message.getExtensionCount(repeatedUint32Extension )); Assert.assertEquals(0, message.getExtensionCount(repeatedUint64Extension )); Assert.assertEquals(0, message.getExtensionCount(repeatedSint32Extension )); Assert.assertEquals(0, message.getExtensionCount(repeatedSint64Extension )); Assert.assertEquals(0, message.getExtensionCount(repeatedFixed32Extension )); Assert.assertEquals(0, message.getExtensionCount(repeatedFixed64Extension )); Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed32Extension)); Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed64Extension)); Assert.assertEquals(0, message.getExtensionCount(repeatedFloatExtension )); Assert.assertEquals(0, message.getExtensionCount(repeatedDoubleExtension )); Assert.assertEquals(0, message.getExtensionCount(repeatedBoolExtension )); Assert.assertEquals(0, message.getExtensionCount(repeatedStringExtension )); Assert.assertEquals(0, message.getExtensionCount(repeatedBytesExtension )); Assert.assertEquals(0, message.getExtensionCount(repeatedGroupExtension )); Assert.assertEquals(0, message.getExtensionCount(repeatedNestedMessageExtension )); Assert.assertEquals(0, message.getExtensionCount(repeatedForeignMessageExtension)); Assert.assertEquals(0, message.getExtensionCount(repeatedImportMessageExtension )); Assert.assertEquals(0, message.getExtensionCount(repeatedLazyMessageExtension )); Assert.assertEquals(0, message.getExtensionCount(repeatedNestedEnumExtension )); Assert.assertEquals(0, message.getExtensionCount(repeatedForeignEnumExtension )); Assert.assertEquals(0, message.getExtensionCount(repeatedImportEnumExtension )); Assert.assertEquals(0, message.getExtensionCount(repeatedStringPieceExtension)); Assert.assertEquals(0, message.getExtensionCount(repeatedCordExtension)); // Repeated fields are empty via getExtension().size(). Assert.assertEquals(0, message.getExtension(repeatedInt32Extension ).size()); Assert.assertEquals(0, message.getExtension(repeatedInt64Extension ).size()); Assert.assertEquals(0, message.getExtension(repeatedUint32Extension ).size()); Assert.assertEquals(0, message.getExtension(repeatedUint64Extension ).size()); Assert.assertEquals(0, message.getExtension(repeatedSint32Extension ).size()); Assert.assertEquals(0, message.getExtension(repeatedSint64Extension ).size()); Assert.assertEquals(0, message.getExtension(repeatedFixed32Extension ).size()); Assert.assertEquals(0, message.getExtension(repeatedFixed64Extension ).size()); Assert.assertEquals(0, message.getExtension(repeatedSfixed32Extension).size()); Assert.assertEquals(0, message.getExtension(repeatedSfixed64Extension).size()); Assert.assertEquals(0, message.getExtension(repeatedFloatExtension ).size()); Assert.assertEquals(0, message.getExtension(repeatedDoubleExtension ).size()); Assert.assertEquals(0, message.getExtension(repeatedBoolExtension ).size()); Assert.assertEquals(0, message.getExtension(repeatedStringExtension ).size()); Assert.assertEquals(0, message.getExtension(repeatedBytesExtension ).size()); Assert.assertEquals(0, message.getExtension(repeatedGroupExtension ).size()); Assert.assertEquals(0, message.getExtension(repeatedNestedMessageExtension ).size()); Assert.assertEquals(0, message.getExtension(repeatedForeignMessageExtension).size()); Assert.assertEquals(0, message.getExtension(repeatedImportMessageExtension ).size()); Assert.assertEquals(0, message.getExtension(repeatedLazyMessageExtension ).size()); Assert.assertEquals(0, message.getExtension(repeatedNestedEnumExtension ).size()); Assert.assertEquals(0, message.getExtension(repeatedForeignEnumExtension ).size()); Assert.assertEquals(0, message.getExtension(repeatedImportEnumExtension ).size()); Assert.assertEquals(0, message.getExtension(repeatedStringPieceExtension).size()); Assert.assertEquals(0, message.getExtension(repeatedCordExtension).size()); // hasBlah() should also be false for all default fields. Assert.assertFalse(message.hasExtension(defaultInt32Extension )); Assert.assertFalse(message.hasExtension(defaultInt64Extension )); Assert.assertFalse(message.hasExtension(defaultUint32Extension )); Assert.assertFalse(message.hasExtension(defaultUint64Extension )); Assert.assertFalse(message.hasExtension(defaultSint32Extension )); Assert.assertFalse(message.hasExtension(defaultSint64Extension )); Assert.assertFalse(message.hasExtension(defaultFixed32Extension )); Assert.assertFalse(message.hasExtension(defaultFixed64Extension )); Assert.assertFalse(message.hasExtension(defaultSfixed32Extension)); Assert.assertFalse(message.hasExtension(defaultSfixed64Extension)); Assert.assertFalse(message.hasExtension(defaultFloatExtension )); Assert.assertFalse(message.hasExtension(defaultDoubleExtension )); Assert.assertFalse(message.hasExtension(defaultBoolExtension )); Assert.assertFalse(message.hasExtension(defaultStringExtension )); Assert.assertFalse(message.hasExtension(defaultBytesExtension )); Assert.assertFalse(message.hasExtension(defaultNestedEnumExtension )); Assert.assertFalse(message.hasExtension(defaultForeignEnumExtension)); Assert.assertFalse(message.hasExtension(defaultImportEnumExtension )); Assert.assertFalse(message.hasExtension(defaultStringPieceExtension)); Assert.assertFalse(message.hasExtension(defaultCordExtension)); // Fields with defaults have their default values (duh). assertEqualsExactType( 41 , message.getExtension(defaultInt32Extension )); assertEqualsExactType( 42L , message.getExtension(defaultInt64Extension )); assertEqualsExactType( 43 , message.getExtension(defaultUint32Extension )); assertEqualsExactType( 44L , message.getExtension(defaultUint64Extension )); assertEqualsExactType(-45 , message.getExtension(defaultSint32Extension )); assertEqualsExactType( 46L , message.getExtension(defaultSint64Extension )); assertEqualsExactType( 47 , message.getExtension(defaultFixed32Extension )); assertEqualsExactType( 48L , message.getExtension(defaultFixed64Extension )); assertEqualsExactType( 49 , message.getExtension(defaultSfixed32Extension)); assertEqualsExactType(-50L , message.getExtension(defaultSfixed64Extension)); assertEqualsExactType( 51.5F , message.getExtension(defaultFloatExtension )); assertEqualsExactType( 52e3D , message.getExtension(defaultDoubleExtension )); assertEqualsExactType(true , message.getExtension(defaultBoolExtension )); assertEqualsExactType("hello", message.getExtension(defaultStringExtension )); assertEqualsExactType(toBytes("world"), message.getExtension(defaultBytesExtension)); assertEqualsExactType(TestAllTypes.NestedEnum.BAR, message.getExtension(defaultNestedEnumExtension )); assertEqualsExactType(ForeignEnum.FOREIGN_BAR, message.getExtension(defaultForeignEnumExtension)); assertEqualsExactType(ImportEnum.IMPORT_BAR, message.getExtension(defaultImportEnumExtension)); assertEqualsExactType("abc", message.getExtension(defaultStringPieceExtension)); assertEqualsExactType("123", message.getExtension(defaultCordExtension)); Assert.assertFalse(message.hasExtension(oneofUint32Extension)); Assert.assertFalse(message.hasExtension(oneofNestedMessageExtension)); Assert.assertFalse(message.hasExtension(oneofStringExtension)); Assert.assertFalse(message.hasExtension(oneofBytesExtension)); } // ------------------------------------------------------------------- /** * Assert (using {@code junit.framework.Assert}} that all extensions of * {@code message} are set to the values assigned by {@code setAllExtensions} * followed by {@code modifyRepeatedExtensions}. */ public static void assertRepeatedExtensionsModified( TestAllExtensionsOrBuilder message) { // ModifyRepeatedFields only sets the second repeated element of each // field. In addition to verifying this, we also verify that the first // element and size were *not* modified. Assert.assertEquals(2, message.getExtensionCount(repeatedInt32Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedInt64Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedUint32Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedUint64Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedSint32Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedSint64Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64Extension )); Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32Extension)); Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64Extension)); Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtension)); Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtension )); Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtension)); Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtension)); assertEqualsExactType(201 , message.getExtension(repeatedInt32Extension , 0)); assertEqualsExactType(202L , message.getExtension(repeatedInt64Extension , 0)); assertEqualsExactType(203 , message.getExtension(repeatedUint32Extension , 0)); assertEqualsExactType(204L , message.getExtension(repeatedUint64Extension , 0)); assertEqualsExactType(205 , message.getExtension(repeatedSint32Extension , 0)); assertEqualsExactType(206L , message.getExtension(repeatedSint64Extension , 0)); assertEqualsExactType(207 , message.getExtension(repeatedFixed32Extension , 0)); assertEqualsExactType(208L , message.getExtension(repeatedFixed64Extension , 0)); assertEqualsExactType(209 , message.getExtension(repeatedSfixed32Extension, 0)); assertEqualsExactType(210L , message.getExtension(repeatedSfixed64Extension, 0)); assertEqualsExactType(211F , message.getExtension(repeatedFloatExtension , 0)); assertEqualsExactType(212D , message.getExtension(repeatedDoubleExtension , 0)); assertEqualsExactType(true , message.getExtension(repeatedBoolExtension , 0)); assertEqualsExactType("215", message.getExtension(repeatedStringExtension , 0)); assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtension, 0)); assertEqualsExactType(217, message.getExtension(repeatedGroupExtension , 0).getA()); assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtension , 0).getBb()); assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtension, 0).getC()); assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtension , 0).getD()); assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtension , 0).getBb()); assertEqualsExactType(TestAllTypes.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtension, 0)); assertEqualsExactType(ForeignEnum.FOREIGN_BAR, message.getExtension(repeatedForeignEnumExtension, 0)); assertEqualsExactType(ImportEnum.IMPORT_BAR, message.getExtension(repeatedImportEnumExtension, 0)); assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtension, 0)); assertEqualsExactType("225", message.getExtension(repeatedCordExtension, 0)); // Actually verify the second (modified) elements now. assertEqualsExactType(501 , message.getExtension(repeatedInt32Extension , 1)); assertEqualsExactType(502L , message.getExtension(repeatedInt64Extension , 1)); assertEqualsExactType(503 , message.getExtension(repeatedUint32Extension , 1)); assertEqualsExactType(504L , message.getExtension(repeatedUint64Extension , 1)); assertEqualsExactType(505 , message.getExtension(repeatedSint32Extension , 1)); assertEqualsExactType(506L , message.getExtension(repeatedSint64Extension , 1)); assertEqualsExactType(507 , message.getExtension(repeatedFixed32Extension , 1)); assertEqualsExactType(508L , message.getExtension(repeatedFixed64Extension , 1)); assertEqualsExactType(509 , message.getExtension(repeatedSfixed32Extension, 1)); assertEqualsExactType(510L , message.getExtension(repeatedSfixed64Extension, 1)); assertEqualsExactType(511F , message.getExtension(repeatedFloatExtension , 1)); assertEqualsExactType(512D , message.getExtension(repeatedDoubleExtension , 1)); assertEqualsExactType(true , message.getExtension(repeatedBoolExtension , 1)); assertEqualsExactType("515", message.getExtension(repeatedStringExtension , 1)); assertEqualsExactType(toBytes("516"), message.getExtension(repeatedBytesExtension, 1)); assertEqualsExactType(517, message.getExtension(repeatedGroupExtension , 1).getA()); assertEqualsExactType(518, message.getExtension(repeatedNestedMessageExtension , 1).getBb()); assertEqualsExactType(519, message.getExtension(repeatedForeignMessageExtension, 1).getC()); assertEqualsExactType(520, message.getExtension(repeatedImportMessageExtension , 1).getD()); assertEqualsExactType(527, message.getExtension(repeatedLazyMessageExtension , 1).getBb()); assertEqualsExactType(TestAllTypes.NestedEnum.FOO, message.getExtension(repeatedNestedEnumExtension, 1)); assertEqualsExactType(ForeignEnum.FOREIGN_FOO, message.getExtension(repeatedForeignEnumExtension, 1)); assertEqualsExactType(ImportEnum.IMPORT_FOO, message.getExtension(repeatedImportEnumExtension, 1)); assertEqualsExactType("524", message.getExtension(repeatedStringPieceExtension, 1)); assertEqualsExactType("525", message.getExtension(repeatedCordExtension, 1)); } public static void setPackedExtensions(TestPackedExtensions.Builder message) { message.addExtension(packedInt32Extension , 601); message.addExtension(packedInt64Extension , 602L); message.addExtension(packedUint32Extension , 603); message.addExtension(packedUint64Extension , 604L); message.addExtension(packedSint32Extension , 605); message.addExtension(packedSint64Extension , 606L); message.addExtension(packedFixed32Extension , 607); message.addExtension(packedFixed64Extension , 608L); message.addExtension(packedSfixed32Extension, 609); message.addExtension(packedSfixed64Extension, 610L); message.addExtension(packedFloatExtension , 611F); message.addExtension(packedDoubleExtension , 612D); message.addExtension(packedBoolExtension , true); message.addExtension(packedEnumExtension, ForeignEnum.FOREIGN_BAR); // Add a second one of each field. message.addExtension(packedInt32Extension , 701); message.addExtension(packedInt64Extension , 702L); message.addExtension(packedUint32Extension , 703); message.addExtension(packedUint64Extension , 704L); message.addExtension(packedSint32Extension , 705); message.addExtension(packedSint64Extension , 706L); message.addExtension(packedFixed32Extension , 707); message.addExtension(packedFixed64Extension , 708L); message.addExtension(packedSfixed32Extension, 709); message.addExtension(packedSfixed64Extension, 710L); message.addExtension(packedFloatExtension , 711F); message.addExtension(packedDoubleExtension , 712D); message.addExtension(packedBoolExtension , false); message.addExtension(packedEnumExtension, ForeignEnum.FOREIGN_BAZ); } public static void assertPackedExtensionsSet(TestPackedExtensions message) { Assert.assertEquals(2, message.getExtensionCount(packedInt32Extension )); Assert.assertEquals(2, message.getExtensionCount(packedInt64Extension )); Assert.assertEquals(2, message.getExtensionCount(packedUint32Extension )); Assert.assertEquals(2, message.getExtensionCount(packedUint64Extension )); Assert.assertEquals(2, message.getExtensionCount(packedSint32Extension )); Assert.assertEquals(2, message.getExtensionCount(packedSint64Extension )); Assert.assertEquals(2, message.getExtensionCount(packedFixed32Extension )); Assert.assertEquals(2, message.getExtensionCount(packedFixed64Extension )); Assert.assertEquals(2, message.getExtensionCount(packedSfixed32Extension)); Assert.assertEquals(2, message.getExtensionCount(packedSfixed64Extension)); Assert.assertEquals(2, message.getExtensionCount(packedFloatExtension )); Assert.assertEquals(2, message.getExtensionCount(packedDoubleExtension )); Assert.assertEquals(2, message.getExtensionCount(packedBoolExtension )); Assert.assertEquals(2, message.getExtensionCount(packedEnumExtension)); assertEqualsExactType(601 , message.getExtension(packedInt32Extension , 0)); assertEqualsExactType(602L , message.getExtension(packedInt64Extension , 0)); assertEqualsExactType(603 , message.getExtension(packedUint32Extension , 0)); assertEqualsExactType(604L , message.getExtension(packedUint64Extension , 0)); assertEqualsExactType(605 , message.getExtension(packedSint32Extension , 0)); assertEqualsExactType(606L , message.getExtension(packedSint64Extension , 0)); assertEqualsExactType(607 , message.getExtension(packedFixed32Extension , 0)); assertEqualsExactType(608L , message.getExtension(packedFixed64Extension , 0)); assertEqualsExactType(609 , message.getExtension(packedSfixed32Extension, 0)); assertEqualsExactType(610L , message.getExtension(packedSfixed64Extension, 0)); assertEqualsExactType(611F , message.getExtension(packedFloatExtension , 0)); assertEqualsExactType(612D , message.getExtension(packedDoubleExtension , 0)); assertEqualsExactType(true , message.getExtension(packedBoolExtension , 0)); assertEqualsExactType(ForeignEnum.FOREIGN_BAR, message.getExtension(packedEnumExtension, 0)); assertEqualsExactType(701 , message.getExtension(packedInt32Extension , 1)); assertEqualsExactType(702L , message.getExtension(packedInt64Extension , 1)); assertEqualsExactType(703 , message.getExtension(packedUint32Extension , 1)); assertEqualsExactType(704L , message.getExtension(packedUint64Extension , 1)); assertEqualsExactType(705 , message.getExtension(packedSint32Extension , 1)); assertEqualsExactType(706L , message.getExtension(packedSint64Extension , 1)); assertEqualsExactType(707 , message.getExtension(packedFixed32Extension , 1)); assertEqualsExactType(708L , message.getExtension(packedFixed64Extension , 1)); assertEqualsExactType(709 , message.getExtension(packedSfixed32Extension, 1)); assertEqualsExactType(710L , message.getExtension(packedSfixed64Extension, 1)); assertEqualsExactType(711F , message.getExtension(packedFloatExtension , 1)); assertEqualsExactType(712D , message.getExtension(packedDoubleExtension , 1)); assertEqualsExactType(false, message.getExtension(packedBoolExtension , 1)); assertEqualsExactType(ForeignEnum.FOREIGN_BAZ, message.getExtension(packedEnumExtension, 1)); } // =================================================================== // Lite extensions /** * Set every field of {@code message} to the values expected by * {@code assertAllExtensionsSet()}. */ public static void setAllExtensions(TestAllExtensionsLite.Builder message) { message.setExtension(optionalInt32ExtensionLite , 101); message.setExtension(optionalInt64ExtensionLite , 102L); message.setExtension(optionalUint32ExtensionLite , 103); message.setExtension(optionalUint64ExtensionLite , 104L); message.setExtension(optionalSint32ExtensionLite , 105); message.setExtension(optionalSint64ExtensionLite , 106L); message.setExtension(optionalFixed32ExtensionLite , 107); message.setExtension(optionalFixed64ExtensionLite , 108L); message.setExtension(optionalSfixed32ExtensionLite, 109); message.setExtension(optionalSfixed64ExtensionLite, 110L); message.setExtension(optionalFloatExtensionLite , 111F); message.setExtension(optionalDoubleExtensionLite , 112D); message.setExtension(optionalBoolExtensionLite , true); message.setExtension(optionalStringExtensionLite , "115"); message.setExtension(optionalBytesExtensionLite , toBytes("116")); message.setExtension(optionalGroupExtensionLite, OptionalGroup_extension_lite.newBuilder().setA(117).build()); message.setExtension(optionalNestedMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build()); message.setExtension(optionalForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(119).build()); message.setExtension(optionalImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(120).build()); message.setExtension(optionalPublicImportMessageExtensionLite, PublicImportMessageLite.newBuilder().setE(126).build()); message.setExtension(optionalLazyMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build()); message.setExtension(optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ); message.setExtension(optionalForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ); message.setExtension(optionalImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_BAZ); message.setExtension(optionalStringPieceExtensionLite, "124"); message.setExtension(optionalCordExtensionLite, "125"); // ----------------------------------------------------------------- message.addExtension(repeatedInt32ExtensionLite , 201); message.addExtension(repeatedInt64ExtensionLite , 202L); message.addExtension(repeatedUint32ExtensionLite , 203); message.addExtension(repeatedUint64ExtensionLite , 204L); message.addExtension(repeatedSint32ExtensionLite , 205); message.addExtension(repeatedSint64ExtensionLite , 206L); message.addExtension(repeatedFixed32ExtensionLite , 207); message.addExtension(repeatedFixed64ExtensionLite , 208L); message.addExtension(repeatedSfixed32ExtensionLite, 209); message.addExtension(repeatedSfixed64ExtensionLite, 210L); message.addExtension(repeatedFloatExtensionLite , 211F); message.addExtension(repeatedDoubleExtensionLite , 212D); message.addExtension(repeatedBoolExtensionLite , true); message.addExtension(repeatedStringExtensionLite , "215"); message.addExtension(repeatedBytesExtensionLite , toBytes("216")); message.addExtension(repeatedGroupExtensionLite, RepeatedGroup_extension_lite.newBuilder().setA(217).build()); message.addExtension(repeatedNestedMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build()); message.addExtension(repeatedForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(219).build()); message.addExtension(repeatedImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(220).build()); message.addExtension(repeatedLazyMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build()); message.addExtension(repeatedNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAR); message.addExtension(repeatedForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAR); message.addExtension(repeatedImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_BAR); message.addExtension(repeatedStringPieceExtensionLite, "224"); message.addExtension(repeatedCordExtensionLite, "225"); // Add a second one of each field. message.addExtension(repeatedInt32ExtensionLite , 301); message.addExtension(repeatedInt64ExtensionLite , 302L); message.addExtension(repeatedUint32ExtensionLite , 303); message.addExtension(repeatedUint64ExtensionLite , 304L); message.addExtension(repeatedSint32ExtensionLite , 305); message.addExtension(repeatedSint64ExtensionLite , 306L); message.addExtension(repeatedFixed32ExtensionLite , 307); message.addExtension(repeatedFixed64ExtensionLite , 308L); message.addExtension(repeatedSfixed32ExtensionLite, 309); message.addExtension(repeatedSfixed64ExtensionLite, 310L); message.addExtension(repeatedFloatExtensionLite , 311F); message.addExtension(repeatedDoubleExtensionLite , 312D); message.addExtension(repeatedBoolExtensionLite , false); message.addExtension(repeatedStringExtensionLite , "315"); message.addExtension(repeatedBytesExtensionLite , toBytes("316")); message.addExtension(repeatedGroupExtensionLite, RepeatedGroup_extension_lite.newBuilder().setA(317).build()); message.addExtension(repeatedNestedMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build()); message.addExtension(repeatedForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(319).build()); message.addExtension(repeatedImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(320).build()); message.addExtension(repeatedLazyMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build()); message.addExtension(repeatedNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ); message.addExtension(repeatedForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ); message.addExtension(repeatedImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_BAZ); message.addExtension(repeatedStringPieceExtensionLite, "324"); message.addExtension(repeatedCordExtensionLite, "325"); // ----------------------------------------------------------------- message.setExtension(defaultInt32ExtensionLite , 401); message.setExtension(defaultInt64ExtensionLite , 402L); message.setExtension(defaultUint32ExtensionLite , 403); message.setExtension(defaultUint64ExtensionLite , 404L); message.setExtension(defaultSint32ExtensionLite , 405); message.setExtension(defaultSint64ExtensionLite , 406L); message.setExtension(defaultFixed32ExtensionLite , 407); message.setExtension(defaultFixed64ExtensionLite , 408L); message.setExtension(defaultSfixed32ExtensionLite, 409); message.setExtension(defaultSfixed64ExtensionLite, 410L); message.setExtension(defaultFloatExtensionLite , 411F); message.setExtension(defaultDoubleExtensionLite , 412D); message.setExtension(defaultBoolExtensionLite , false); message.setExtension(defaultStringExtensionLite , "415"); message.setExtension(defaultBytesExtensionLite , toBytes("416")); message.setExtension(defaultNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.FOO); message.setExtension(defaultForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_FOO); message.setExtension(defaultImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_FOO); message.setExtension(defaultStringPieceExtensionLite, "424"); message.setExtension(defaultCordExtensionLite, "425"); message.setExtension(oneofUint32ExtensionLite, 601); message.setExtension(oneofNestedMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build()); message.setExtension(oneofStringExtensionLite, "603"); message.setExtension(oneofBytesExtensionLite, toBytes("604")); } // ------------------------------------------------------------------- /** * Modify the repeated extensions of {@code message} to contain the values * expected by {@code assertRepeatedExtensionsModified()}. */ public static void modifyRepeatedExtensions( TestAllExtensionsLite.Builder message) { message.setExtension(repeatedInt32ExtensionLite , 1, 501); message.setExtension(repeatedInt64ExtensionLite , 1, 502L); message.setExtension(repeatedUint32ExtensionLite , 1, 503); message.setExtension(repeatedUint64ExtensionLite , 1, 504L); message.setExtension(repeatedSint32ExtensionLite , 1, 505); message.setExtension(repeatedSint64ExtensionLite , 1, 506L); message.setExtension(repeatedFixed32ExtensionLite , 1, 507); message.setExtension(repeatedFixed64ExtensionLite , 1, 508L); message.setExtension(repeatedSfixed32ExtensionLite, 1, 509); message.setExtension(repeatedSfixed64ExtensionLite, 1, 510L); message.setExtension(repeatedFloatExtensionLite , 1, 511F); message.setExtension(repeatedDoubleExtensionLite , 1, 512D); message.setExtension(repeatedBoolExtensionLite , 1, true); message.setExtension(repeatedStringExtensionLite , 1, "515"); message.setExtension(repeatedBytesExtensionLite , 1, toBytes("516")); message.setExtension(repeatedGroupExtensionLite, 1, RepeatedGroup_extension_lite.newBuilder().setA(517).build()); message.setExtension(repeatedNestedMessageExtensionLite, 1, TestAllTypesLite.NestedMessage.newBuilder().setBb(518).build()); message.setExtension(repeatedForeignMessageExtensionLite, 1, ForeignMessageLite.newBuilder().setC(519).build()); message.setExtension(repeatedImportMessageExtensionLite, 1, ImportMessageLite.newBuilder().setD(520).build()); message.setExtension(repeatedLazyMessageExtensionLite, 1, TestAllTypesLite.NestedMessage.newBuilder().setBb(527).build()); message.setExtension(repeatedNestedEnumExtensionLite , 1, TestAllTypesLite.NestedEnum.FOO); message.setExtension(repeatedForeignEnumExtensionLite, 1, ForeignEnumLite.FOREIGN_LITE_FOO); message.setExtension(repeatedImportEnumExtensionLite , 1, ImportEnumLite.IMPORT_LITE_FOO); message.setExtension(repeatedStringPieceExtensionLite, 1, "524"); message.setExtension(repeatedCordExtensionLite, 1, "525"); } // ------------------------------------------------------------------- /** * Assert (using {@code junit.framework.Assert}} that all extensions of * {@code message} are set to the values assigned by {@code setAllExtensions}. */ public static void assertAllExtensionsSet( TestAllExtensionsLiteOrBuilder message) { Assert.assertTrue(message.hasExtension(optionalInt32ExtensionLite )); Assert.assertTrue(message.hasExtension(optionalInt64ExtensionLite )); Assert.assertTrue(message.hasExtension(optionalUint32ExtensionLite )); Assert.assertTrue(message.hasExtension(optionalUint64ExtensionLite )); Assert.assertTrue(message.hasExtension(optionalSint32ExtensionLite )); Assert.assertTrue(message.hasExtension(optionalSint64ExtensionLite )); Assert.assertTrue(message.hasExtension(optionalFixed32ExtensionLite )); Assert.assertTrue(message.hasExtension(optionalFixed64ExtensionLite )); Assert.assertTrue(message.hasExtension(optionalSfixed32ExtensionLite)); Assert.assertTrue(message.hasExtension(optionalSfixed64ExtensionLite)); Assert.assertTrue(message.hasExtension(optionalFloatExtensionLite )); Assert.assertTrue(message.hasExtension(optionalDoubleExtensionLite )); Assert.assertTrue(message.hasExtension(optionalBoolExtensionLite )); Assert.assertTrue(message.hasExtension(optionalStringExtensionLite )); Assert.assertTrue(message.hasExtension(optionalBytesExtensionLite )); Assert.assertTrue(message.hasExtension(optionalGroupExtensionLite )); Assert.assertTrue(message.hasExtension(optionalNestedMessageExtensionLite )); Assert.assertTrue(message.hasExtension(optionalForeignMessageExtensionLite)); Assert.assertTrue(message.hasExtension(optionalImportMessageExtensionLite )); Assert.assertTrue(message.getExtension(optionalGroupExtensionLite ).hasA()); Assert.assertTrue(message.getExtension(optionalNestedMessageExtensionLite ).hasBb()); Assert.assertTrue(message.getExtension(optionalForeignMessageExtensionLite).hasC()); Assert.assertTrue(message.getExtension(optionalImportMessageExtensionLite ).hasD()); Assert.assertTrue(message.hasExtension(optionalNestedEnumExtensionLite )); Assert.assertTrue(message.hasExtension(optionalForeignEnumExtensionLite)); Assert.assertTrue(message.hasExtension(optionalImportEnumExtensionLite )); Assert.assertTrue(message.hasExtension(optionalStringPieceExtensionLite)); Assert.assertTrue(message.hasExtension(optionalCordExtensionLite)); assertEqualsExactType(101 , message.getExtension(optionalInt32ExtensionLite )); assertEqualsExactType(102L , message.getExtension(optionalInt64ExtensionLite )); assertEqualsExactType(103 , message.getExtension(optionalUint32ExtensionLite )); assertEqualsExactType(104L , message.getExtension(optionalUint64ExtensionLite )); assertEqualsExactType(105 , message.getExtension(optionalSint32ExtensionLite )); assertEqualsExactType(106L , message.getExtension(optionalSint64ExtensionLite )); assertEqualsExactType(107 , message.getExtension(optionalFixed32ExtensionLite )); assertEqualsExactType(108L , message.getExtension(optionalFixed64ExtensionLite )); assertEqualsExactType(109 , message.getExtension(optionalSfixed32ExtensionLite)); assertEqualsExactType(110L , message.getExtension(optionalSfixed64ExtensionLite)); assertEqualsExactType(111F , message.getExtension(optionalFloatExtensionLite )); assertEqualsExactType(112D , message.getExtension(optionalDoubleExtensionLite )); assertEqualsExactType(true , message.getExtension(optionalBoolExtensionLite )); assertEqualsExactType("115", message.getExtension(optionalStringExtensionLite )); assertEqualsExactType(toBytes("116"), message.getExtension(optionalBytesExtensionLite)); assertEqualsExactType(117, message.getExtension(optionalGroupExtensionLite ).getA()); assertEqualsExactType(118, message.getExtension(optionalNestedMessageExtensionLite ).getBb()); assertEqualsExactType(119, message.getExtension(optionalForeignMessageExtensionLite).getC()); assertEqualsExactType(120, message.getExtension(optionalImportMessageExtensionLite ).getD()); assertEqualsExactType(126, message.getExtension( optionalPublicImportMessageExtensionLite).getE()); assertEqualsExactType(127, message.getExtension(optionalLazyMessageExtensionLite).getBb()); assertEqualsExactType(TestAllTypesLite.NestedEnum.BAZ, message.getExtension(optionalNestedEnumExtensionLite)); assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAZ, message.getExtension(optionalForeignEnumExtensionLite)); assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAZ, message.getExtension(optionalImportEnumExtensionLite)); assertEqualsExactType("124", message.getExtension(optionalStringPieceExtensionLite)); assertEqualsExactType("125", message.getExtension(optionalCordExtensionLite)); // ----------------------------------------------------------------- Assert.assertEquals(2, message.getExtensionCount(repeatedInt32ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedInt64ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedUint32ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedUint64ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedSint32ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedSint64ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32ExtensionLite)); Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64ExtensionLite)); Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtensionLite)); Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtensionLite)); Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtensionLite)); assertEqualsExactType(201 , message.getExtension(repeatedInt32ExtensionLite , 0)); assertEqualsExactType(202L , message.getExtension(repeatedInt64ExtensionLite , 0)); assertEqualsExactType(203 , message.getExtension(repeatedUint32ExtensionLite , 0)); assertEqualsExactType(204L , message.getExtension(repeatedUint64ExtensionLite , 0)); assertEqualsExactType(205 , message.getExtension(repeatedSint32ExtensionLite , 0)); assertEqualsExactType(206L , message.getExtension(repeatedSint64ExtensionLite , 0)); assertEqualsExactType(207 , message.getExtension(repeatedFixed32ExtensionLite , 0)); assertEqualsExactType(208L , message.getExtension(repeatedFixed64ExtensionLite , 0)); assertEqualsExactType(209 , message.getExtension(repeatedSfixed32ExtensionLite, 0)); assertEqualsExactType(210L , message.getExtension(repeatedSfixed64ExtensionLite, 0)); assertEqualsExactType(211F , message.getExtension(repeatedFloatExtensionLite , 0)); assertEqualsExactType(212D , message.getExtension(repeatedDoubleExtensionLite , 0)); assertEqualsExactType(true , message.getExtension(repeatedBoolExtensionLite , 0)); assertEqualsExactType("215", message.getExtension(repeatedStringExtensionLite , 0)); assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtensionLite, 0)); assertEqualsExactType(217, message.getExtension(repeatedGroupExtensionLite ,0).getA()); assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtensionLite ,0).getBb()); assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtensionLite,0).getC()); assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtensionLite ,0).getD()); assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtensionLite ,0).getBb()); assertEqualsExactType(TestAllTypesLite.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtensionLite, 0)); assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAR, message.getExtension(repeatedForeignEnumExtensionLite, 0)); assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAR, message.getExtension(repeatedImportEnumExtensionLite, 0)); assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtensionLite, 0)); assertEqualsExactType("225", message.getExtension(repeatedCordExtensionLite, 0)); assertEqualsExactType(301 , message.getExtension(repeatedInt32ExtensionLite , 1)); assertEqualsExactType(302L , message.getExtension(repeatedInt64ExtensionLite , 1)); assertEqualsExactType(303 , message.getExtension(repeatedUint32ExtensionLite , 1)); assertEqualsExactType(304L , message.getExtension(repeatedUint64ExtensionLite , 1)); assertEqualsExactType(305 , message.getExtension(repeatedSint32ExtensionLite , 1)); assertEqualsExactType(306L , message.getExtension(repeatedSint64ExtensionLite , 1)); assertEqualsExactType(307 , message.getExtension(repeatedFixed32ExtensionLite , 1)); assertEqualsExactType(308L , message.getExtension(repeatedFixed64ExtensionLite , 1)); assertEqualsExactType(309 , message.getExtension(repeatedSfixed32ExtensionLite, 1)); assertEqualsExactType(310L , message.getExtension(repeatedSfixed64ExtensionLite, 1)); assertEqualsExactType(311F , message.getExtension(repeatedFloatExtensionLite , 1)); assertEqualsExactType(312D , message.getExtension(repeatedDoubleExtensionLite , 1)); assertEqualsExactType(false, message.getExtension(repeatedBoolExtensionLite , 1)); assertEqualsExactType("315", message.getExtension(repeatedStringExtensionLite , 1)); assertEqualsExactType(toBytes("316"), message.getExtension(repeatedBytesExtensionLite, 1)); assertEqualsExactType(317, message.getExtension(repeatedGroupExtensionLite ,1).getA()); assertEqualsExactType(318, message.getExtension(repeatedNestedMessageExtensionLite ,1).getBb()); assertEqualsExactType(319, message.getExtension(repeatedForeignMessageExtensionLite,1).getC()); assertEqualsExactType(320, message.getExtension(repeatedImportMessageExtensionLite ,1).getD()); assertEqualsExactType(327, message.getExtension(repeatedLazyMessageExtensionLite ,1).getBb()); assertEqualsExactType(TestAllTypesLite.NestedEnum.BAZ, message.getExtension(repeatedNestedEnumExtensionLite, 1)); assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAZ, message.getExtension(repeatedForeignEnumExtensionLite, 1)); assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAZ, message.getExtension(repeatedImportEnumExtensionLite, 1)); assertEqualsExactType("324", message.getExtension(repeatedStringPieceExtensionLite, 1)); assertEqualsExactType("325", message.getExtension(repeatedCordExtensionLite, 1)); // ----------------------------------------------------------------- Assert.assertTrue(message.hasExtension(defaultInt32ExtensionLite )); Assert.assertTrue(message.hasExtension(defaultInt64ExtensionLite )); Assert.assertTrue(message.hasExtension(defaultUint32ExtensionLite )); Assert.assertTrue(message.hasExtension(defaultUint64ExtensionLite )); Assert.assertTrue(message.hasExtension(defaultSint32ExtensionLite )); Assert.assertTrue(message.hasExtension(defaultSint64ExtensionLite )); Assert.assertTrue(message.hasExtension(defaultFixed32ExtensionLite )); Assert.assertTrue(message.hasExtension(defaultFixed64ExtensionLite )); Assert.assertTrue(message.hasExtension(defaultSfixed32ExtensionLite)); Assert.assertTrue(message.hasExtension(defaultSfixed64ExtensionLite)); Assert.assertTrue(message.hasExtension(defaultFloatExtensionLite )); Assert.assertTrue(message.hasExtension(defaultDoubleExtensionLite )); Assert.assertTrue(message.hasExtension(defaultBoolExtensionLite )); Assert.assertTrue(message.hasExtension(defaultStringExtensionLite )); Assert.assertTrue(message.hasExtension(defaultBytesExtensionLite )); Assert.assertTrue(message.hasExtension(defaultNestedEnumExtensionLite )); Assert.assertTrue(message.hasExtension(defaultForeignEnumExtensionLite)); Assert.assertTrue(message.hasExtension(defaultImportEnumExtensionLite )); Assert.assertTrue(message.hasExtension(defaultStringPieceExtensionLite)); Assert.assertTrue(message.hasExtension(defaultCordExtensionLite)); assertEqualsExactType(401 , message.getExtension(defaultInt32ExtensionLite )); assertEqualsExactType(402L , message.getExtension(defaultInt64ExtensionLite )); assertEqualsExactType(403 , message.getExtension(defaultUint32ExtensionLite )); assertEqualsExactType(404L , message.getExtension(defaultUint64ExtensionLite )); assertEqualsExactType(405 , message.getExtension(defaultSint32ExtensionLite )); assertEqualsExactType(406L , message.getExtension(defaultSint64ExtensionLite )); assertEqualsExactType(407 , message.getExtension(defaultFixed32ExtensionLite )); assertEqualsExactType(408L , message.getExtension(defaultFixed64ExtensionLite )); assertEqualsExactType(409 , message.getExtension(defaultSfixed32ExtensionLite)); assertEqualsExactType(410L , message.getExtension(defaultSfixed64ExtensionLite)); assertEqualsExactType(411F , message.getExtension(defaultFloatExtensionLite )); assertEqualsExactType(412D , message.getExtension(defaultDoubleExtensionLite )); assertEqualsExactType(false, message.getExtension(defaultBoolExtensionLite )); assertEqualsExactType("415", message.getExtension(defaultStringExtensionLite )); assertEqualsExactType(toBytes("416"), message.getExtension(defaultBytesExtensionLite)); assertEqualsExactType(TestAllTypesLite.NestedEnum.FOO, message.getExtension(defaultNestedEnumExtensionLite )); assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_FOO, message.getExtension(defaultForeignEnumExtensionLite)); assertEqualsExactType(ImportEnumLite.IMPORT_LITE_FOO, message.getExtension(defaultImportEnumExtensionLite)); assertEqualsExactType("424", message.getExtension(defaultStringPieceExtensionLite)); assertEqualsExactType("425", message.getExtension(defaultCordExtensionLite)); Assert.assertTrue(message.hasExtension(oneofBytesExtensionLite)); assertEqualsExactType(toBytes("604"), message.getExtension(oneofBytesExtensionLite)); } // ------------------------------------------------------------------- /** * Assert (using {@code junit.framework.Assert}} that all extensions of * {@code message} are cleared, and that getting the extensions returns their * default values. */ public static void assertExtensionsClear( TestAllExtensionsLiteOrBuilder message) { // hasBlah() should initially be false for all optional fields. Assert.assertFalse(message.hasExtension(optionalInt32ExtensionLite )); Assert.assertFalse(message.hasExtension(optionalInt64ExtensionLite )); Assert.assertFalse(message.hasExtension(optionalUint32ExtensionLite )); Assert.assertFalse(message.hasExtension(optionalUint64ExtensionLite )); Assert.assertFalse(message.hasExtension(optionalSint32ExtensionLite )); Assert.assertFalse(message.hasExtension(optionalSint64ExtensionLite )); Assert.assertFalse(message.hasExtension(optionalFixed32ExtensionLite )); Assert.assertFalse(message.hasExtension(optionalFixed64ExtensionLite )); Assert.assertFalse(message.hasExtension(optionalSfixed32ExtensionLite)); Assert.assertFalse(message.hasExtension(optionalSfixed64ExtensionLite)); Assert.assertFalse(message.hasExtension(optionalFloatExtensionLite )); Assert.assertFalse(message.hasExtension(optionalDoubleExtensionLite )); Assert.assertFalse(message.hasExtension(optionalBoolExtensionLite )); Assert.assertFalse(message.hasExtension(optionalStringExtensionLite )); Assert.assertFalse(message.hasExtension(optionalBytesExtensionLite )); Assert.assertFalse(message.hasExtension(optionalGroupExtensionLite )); Assert.assertFalse(message.hasExtension(optionalNestedMessageExtensionLite )); Assert.assertFalse(message.hasExtension(optionalForeignMessageExtensionLite )); Assert.assertFalse(message.hasExtension(optionalImportMessageExtensionLite )); Assert.assertFalse(message.hasExtension(optionalPublicImportMessageExtensionLite)); Assert.assertFalse(message.hasExtension(optionalLazyMessageExtensionLite )); Assert.assertFalse(message.hasExtension(optionalNestedEnumExtensionLite )); Assert.assertFalse(message.hasExtension(optionalForeignEnumExtensionLite)); Assert.assertFalse(message.hasExtension(optionalImportEnumExtensionLite )); Assert.assertFalse(message.hasExtension(optionalStringPieceExtensionLite)); Assert.assertFalse(message.hasExtension(optionalCordExtensionLite)); // Optional fields without defaults are set to zero or something like it. assertEqualsExactType(0 , message.getExtension(optionalInt32ExtensionLite )); assertEqualsExactType(0L , message.getExtension(optionalInt64ExtensionLite )); assertEqualsExactType(0 , message.getExtension(optionalUint32ExtensionLite )); assertEqualsExactType(0L , message.getExtension(optionalUint64ExtensionLite )); assertEqualsExactType(0 , message.getExtension(optionalSint32ExtensionLite )); assertEqualsExactType(0L , message.getExtension(optionalSint64ExtensionLite )); assertEqualsExactType(0 , message.getExtension(optionalFixed32ExtensionLite )); assertEqualsExactType(0L , message.getExtension(optionalFixed64ExtensionLite )); assertEqualsExactType(0 , message.getExtension(optionalSfixed32ExtensionLite)); assertEqualsExactType(0L , message.getExtension(optionalSfixed64ExtensionLite)); assertEqualsExactType(0F , message.getExtension(optionalFloatExtensionLite )); assertEqualsExactType(0D , message.getExtension(optionalDoubleExtensionLite )); assertEqualsExactType(false, message.getExtension(optionalBoolExtensionLite )); assertEqualsExactType("" , message.getExtension(optionalStringExtensionLite )); assertEqualsExactType(ByteString.EMPTY, message.getExtension(optionalBytesExtensionLite)); // Embedded messages should also be clear. Assert.assertFalse(message.getExtension(optionalGroupExtensionLite ).hasA()); Assert.assertFalse(message.getExtension(optionalNestedMessageExtensionLite ).hasBb()); Assert.assertFalse(message.getExtension(optionalForeignMessageExtensionLite ).hasC()); Assert.assertFalse(message.getExtension(optionalImportMessageExtensionLite ).hasD()); Assert.assertFalse(message.getExtension(optionalPublicImportMessageExtensionLite).hasE()); Assert.assertFalse(message.getExtension(optionalLazyMessageExtensionLite ).hasBb()); assertEqualsExactType(0, message.getExtension(optionalGroupExtensionLite ).getA()); assertEqualsExactType(0, message.getExtension(optionalNestedMessageExtensionLite ).getBb()); assertEqualsExactType(0, message.getExtension(optionalForeignMessageExtensionLite).getC()); assertEqualsExactType(0, message.getExtension(optionalImportMessageExtensionLite ).getD()); assertEqualsExactType(0, message.getExtension( optionalPublicImportMessageExtensionLite).getE()); assertEqualsExactType(0, message.getExtension(optionalLazyMessageExtensionLite ).getBb()); // Enums without defaults are set to the first value in the enum. assertEqualsExactType(TestAllTypesLite.NestedEnum.FOO, message.getExtension(optionalNestedEnumExtensionLite )); assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_FOO, message.getExtension(optionalForeignEnumExtensionLite)); assertEqualsExactType(ImportEnumLite.IMPORT_LITE_FOO, message.getExtension(optionalImportEnumExtensionLite)); assertEqualsExactType("", message.getExtension(optionalStringPieceExtensionLite)); assertEqualsExactType("", message.getExtension(optionalCordExtensionLite)); // Repeated fields are empty. Assert.assertEquals(0, message.getExtensionCount(repeatedInt32ExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedInt64ExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedUint32ExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedUint64ExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedSint32ExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedSint64ExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedFixed32ExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedFixed64ExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed32ExtensionLite)); Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed64ExtensionLite)); Assert.assertEquals(0, message.getExtensionCount(repeatedFloatExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedDoubleExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedBoolExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedStringExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedBytesExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedGroupExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedNestedMessageExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedForeignMessageExtensionLite)); Assert.assertEquals(0, message.getExtensionCount(repeatedImportMessageExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedLazyMessageExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedNestedEnumExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedForeignEnumExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedImportEnumExtensionLite )); Assert.assertEquals(0, message.getExtensionCount(repeatedStringPieceExtensionLite)); Assert.assertEquals(0, message.getExtensionCount(repeatedCordExtensionLite)); // hasBlah() should also be false for all default fields. Assert.assertFalse(message.hasExtension(defaultInt32ExtensionLite )); Assert.assertFalse(message.hasExtension(defaultInt64ExtensionLite )); Assert.assertFalse(message.hasExtension(defaultUint32ExtensionLite )); Assert.assertFalse(message.hasExtension(defaultUint64ExtensionLite )); Assert.assertFalse(message.hasExtension(defaultSint32ExtensionLite )); Assert.assertFalse(message.hasExtension(defaultSint64ExtensionLite )); Assert.assertFalse(message.hasExtension(defaultFixed32ExtensionLite )); Assert.assertFalse(message.hasExtension(defaultFixed64ExtensionLite )); Assert.assertFalse(message.hasExtension(defaultSfixed32ExtensionLite)); Assert.assertFalse(message.hasExtension(defaultSfixed64ExtensionLite)); Assert.assertFalse(message.hasExtension(defaultFloatExtensionLite )); Assert.assertFalse(message.hasExtension(defaultDoubleExtensionLite )); Assert.assertFalse(message.hasExtension(defaultBoolExtensionLite )); Assert.assertFalse(message.hasExtension(defaultStringExtensionLite )); Assert.assertFalse(message.hasExtension(defaultBytesExtensionLite )); Assert.assertFalse(message.hasExtension(defaultNestedEnumExtensionLite )); Assert.assertFalse(message.hasExtension(defaultForeignEnumExtensionLite)); Assert.assertFalse(message.hasExtension(defaultImportEnumExtensionLite )); Assert.assertFalse(message.hasExtension(defaultStringPieceExtensionLite)); Assert.assertFalse(message.hasExtension(defaultCordExtensionLite)); // Fields with defaults have their default values (duh). assertEqualsExactType( 41 , message.getExtension(defaultInt32ExtensionLite )); assertEqualsExactType( 42L , message.getExtension(defaultInt64ExtensionLite )); assertEqualsExactType( 43 , message.getExtension(defaultUint32ExtensionLite )); assertEqualsExactType( 44L , message.getExtension(defaultUint64ExtensionLite )); assertEqualsExactType(-45 , message.getExtension(defaultSint32ExtensionLite )); assertEqualsExactType( 46L , message.getExtension(defaultSint64ExtensionLite )); assertEqualsExactType( 47 , message.getExtension(defaultFixed32ExtensionLite )); assertEqualsExactType( 48L , message.getExtension(defaultFixed64ExtensionLite )); assertEqualsExactType( 49 , message.getExtension(defaultSfixed32ExtensionLite)); assertEqualsExactType(-50L , message.getExtension(defaultSfixed64ExtensionLite)); assertEqualsExactType( 51.5F , message.getExtension(defaultFloatExtensionLite )); assertEqualsExactType( 52e3D , message.getExtension(defaultDoubleExtensionLite )); assertEqualsExactType(true , message.getExtension(defaultBoolExtensionLite )); assertEqualsExactType("hello", message.getExtension(defaultStringExtensionLite )); assertEqualsExactType(toBytes("world"), message.getExtension(defaultBytesExtensionLite)); assertEqualsExactType(TestAllTypesLite.NestedEnum.BAR, message.getExtension(defaultNestedEnumExtensionLite )); assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAR, message.getExtension(defaultForeignEnumExtensionLite)); assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAR, message.getExtension(defaultImportEnumExtensionLite)); assertEqualsExactType("abc", message.getExtension(defaultStringPieceExtensionLite)); assertEqualsExactType("123", message.getExtension(defaultCordExtensionLite)); Assert.assertFalse(message.hasExtension(oneofUint32ExtensionLite)); Assert.assertFalse(message.hasExtension(oneofNestedMessageExtensionLite)); Assert.assertFalse(message.hasExtension(oneofStringExtensionLite)); Assert.assertFalse(message.hasExtension(oneofBytesExtensionLite)); } // ------------------------------------------------------------------- /** * Assert (using {@code junit.framework.Assert}} that all extensions of * {@code message} are set to the values assigned by {@code setAllExtensions} * followed by {@code modifyRepeatedExtensions}. */ public static void assertRepeatedExtensionsModified( TestAllExtensionsLiteOrBuilder message) { // ModifyRepeatedFields only sets the second repeated element of each // field. In addition to verifying this, we also verify that the first // element and size were *not* modified. Assert.assertEquals(2, message.getExtensionCount(repeatedInt32ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedInt64ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedUint32ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedUint64ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedSint32ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedSint64ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32ExtensionLite)); Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64ExtensionLite)); Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtensionLite)); Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtensionLite)); Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtensionLite)); assertEqualsExactType(201 , message.getExtension(repeatedInt32ExtensionLite , 0)); assertEqualsExactType(202L , message.getExtension(repeatedInt64ExtensionLite , 0)); assertEqualsExactType(203 , message.getExtension(repeatedUint32ExtensionLite , 0)); assertEqualsExactType(204L , message.getExtension(repeatedUint64ExtensionLite , 0)); assertEqualsExactType(205 , message.getExtension(repeatedSint32ExtensionLite , 0)); assertEqualsExactType(206L , message.getExtension(repeatedSint64ExtensionLite , 0)); assertEqualsExactType(207 , message.getExtension(repeatedFixed32ExtensionLite , 0)); assertEqualsExactType(208L , message.getExtension(repeatedFixed64ExtensionLite , 0)); assertEqualsExactType(209 , message.getExtension(repeatedSfixed32ExtensionLite, 0)); assertEqualsExactType(210L , message.getExtension(repeatedSfixed64ExtensionLite, 0)); assertEqualsExactType(211F , message.getExtension(repeatedFloatExtensionLite , 0)); assertEqualsExactType(212D , message.getExtension(repeatedDoubleExtensionLite , 0)); assertEqualsExactType(true , message.getExtension(repeatedBoolExtensionLite , 0)); assertEqualsExactType("215", message.getExtension(repeatedStringExtensionLite , 0)); assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtensionLite, 0)); assertEqualsExactType(217, message.getExtension(repeatedGroupExtensionLite ,0).getA()); assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtensionLite ,0).getBb()); assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtensionLite,0).getC()); assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtensionLite ,0).getD()); assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtensionLite ,0).getBb()); assertEqualsExactType(TestAllTypesLite.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtensionLite, 0)); assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAR, message.getExtension(repeatedForeignEnumExtensionLite, 0)); assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAR, message.getExtension(repeatedImportEnumExtensionLite, 0)); assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtensionLite, 0)); assertEqualsExactType("225", message.getExtension(repeatedCordExtensionLite, 0)); // Actually verify the second (modified) elements now. assertEqualsExactType(501 , message.getExtension(repeatedInt32ExtensionLite , 1)); assertEqualsExactType(502L , message.getExtension(repeatedInt64ExtensionLite , 1)); assertEqualsExactType(503 , message.getExtension(repeatedUint32ExtensionLite , 1)); assertEqualsExactType(504L , message.getExtension(repeatedUint64ExtensionLite , 1)); assertEqualsExactType(505 , message.getExtension(repeatedSint32ExtensionLite , 1)); assertEqualsExactType(506L , message.getExtension(repeatedSint64ExtensionLite , 1)); assertEqualsExactType(507 , message.getExtension(repeatedFixed32ExtensionLite , 1)); assertEqualsExactType(508L , message.getExtension(repeatedFixed64ExtensionLite , 1)); assertEqualsExactType(509 , message.getExtension(repeatedSfixed32ExtensionLite, 1)); assertEqualsExactType(510L , message.getExtension(repeatedSfixed64ExtensionLite, 1)); assertEqualsExactType(511F , message.getExtension(repeatedFloatExtensionLite , 1)); assertEqualsExactType(512D , message.getExtension(repeatedDoubleExtensionLite , 1)); assertEqualsExactType(true , message.getExtension(repeatedBoolExtensionLite , 1)); assertEqualsExactType("515", message.getExtension(repeatedStringExtensionLite , 1)); assertEqualsExactType(toBytes("516"), message.getExtension(repeatedBytesExtensionLite, 1)); assertEqualsExactType(517, message.getExtension(repeatedGroupExtensionLite ,1).getA()); assertEqualsExactType(518, message.getExtension(repeatedNestedMessageExtensionLite ,1).getBb()); assertEqualsExactType(519, message.getExtension(repeatedForeignMessageExtensionLite,1).getC()); assertEqualsExactType(520, message.getExtension(repeatedImportMessageExtensionLite ,1).getD()); assertEqualsExactType(527, message.getExtension(repeatedLazyMessageExtensionLite ,1).getBb()); assertEqualsExactType(TestAllTypesLite.NestedEnum.FOO, message.getExtension(repeatedNestedEnumExtensionLite, 1)); assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_FOO, message.getExtension(repeatedForeignEnumExtensionLite, 1)); assertEqualsExactType(ImportEnumLite.IMPORT_LITE_FOO, message.getExtension(repeatedImportEnumExtensionLite, 1)); assertEqualsExactType("524", message.getExtension(repeatedStringPieceExtensionLite, 1)); assertEqualsExactType("525", message.getExtension(repeatedCordExtensionLite, 1)); } public static void setPackedExtensions(TestPackedExtensionsLite.Builder message) { message.addExtension(packedInt32ExtensionLite , 601); message.addExtension(packedInt64ExtensionLite , 602L); message.addExtension(packedUint32ExtensionLite , 603); message.addExtension(packedUint64ExtensionLite , 604L); message.addExtension(packedSint32ExtensionLite , 605); message.addExtension(packedSint64ExtensionLite , 606L); message.addExtension(packedFixed32ExtensionLite , 607); message.addExtension(packedFixed64ExtensionLite , 608L); message.addExtension(packedSfixed32ExtensionLite, 609); message.addExtension(packedSfixed64ExtensionLite, 610L); message.addExtension(packedFloatExtensionLite , 611F); message.addExtension(packedDoubleExtensionLite , 612D); message.addExtension(packedBoolExtensionLite , true); message.addExtension(packedEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAR); // Add a second one of each field. message.addExtension(packedInt32ExtensionLite , 701); message.addExtension(packedInt64ExtensionLite , 702L); message.addExtension(packedUint32ExtensionLite , 703); message.addExtension(packedUint64ExtensionLite , 704L); message.addExtension(packedSint32ExtensionLite , 705); message.addExtension(packedSint64ExtensionLite , 706L); message.addExtension(packedFixed32ExtensionLite , 707); message.addExtension(packedFixed64ExtensionLite , 708L); message.addExtension(packedSfixed32ExtensionLite, 709); message.addExtension(packedSfixed64ExtensionLite, 710L); message.addExtension(packedFloatExtensionLite , 711F); message.addExtension(packedDoubleExtensionLite , 712D); message.addExtension(packedBoolExtensionLite , false); message.addExtension(packedEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ); } public static void assertPackedExtensionsSet(TestPackedExtensionsLite message) { Assert.assertEquals(2, message.getExtensionCount(packedInt32ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(packedInt64ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(packedUint32ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(packedUint64ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(packedSint32ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(packedSint64ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(packedFixed32ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(packedFixed64ExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(packedSfixed32ExtensionLite)); Assert.assertEquals(2, message.getExtensionCount(packedSfixed64ExtensionLite)); Assert.assertEquals(2, message.getExtensionCount(packedFloatExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(packedDoubleExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(packedBoolExtensionLite )); Assert.assertEquals(2, message.getExtensionCount(packedEnumExtensionLite)); assertEqualsExactType(601 , message.getExtension(packedInt32ExtensionLite , 0)); assertEqualsExactType(602L , message.getExtension(packedInt64ExtensionLite , 0)); assertEqualsExactType(603 , message.getExtension(packedUint32ExtensionLite , 0)); assertEqualsExactType(604L , message.getExtension(packedUint64ExtensionLite , 0)); assertEqualsExactType(605 , message.getExtension(packedSint32ExtensionLite , 0)); assertEqualsExactType(606L , message.getExtension(packedSint64ExtensionLite , 0)); assertEqualsExactType(607 , message.getExtension(packedFixed32ExtensionLite , 0)); assertEqualsExactType(608L , message.getExtension(packedFixed64ExtensionLite , 0)); assertEqualsExactType(609 , message.getExtension(packedSfixed32ExtensionLite, 0)); assertEqualsExactType(610L , message.getExtension(packedSfixed64ExtensionLite, 0)); assertEqualsExactType(611F , message.getExtension(packedFloatExtensionLite , 0)); assertEqualsExactType(612D , message.getExtension(packedDoubleExtensionLite , 0)); assertEqualsExactType(true , message.getExtension(packedBoolExtensionLite , 0)); assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAR, message.getExtension(packedEnumExtensionLite, 0)); assertEqualsExactType(701 , message.getExtension(packedInt32ExtensionLite , 1)); assertEqualsExactType(702L , message.getExtension(packedInt64ExtensionLite , 1)); assertEqualsExactType(703 , message.getExtension(packedUint32ExtensionLite , 1)); assertEqualsExactType(704L , message.getExtension(packedUint64ExtensionLite , 1)); assertEqualsExactType(705 , message.getExtension(packedSint32ExtensionLite , 1)); assertEqualsExactType(706L , message.getExtension(packedSint64ExtensionLite , 1)); assertEqualsExactType(707 , message.getExtension(packedFixed32ExtensionLite , 1)); assertEqualsExactType(708L , message.getExtension(packedFixed64ExtensionLite , 1)); assertEqualsExactType(709 , message.getExtension(packedSfixed32ExtensionLite, 1)); assertEqualsExactType(710L , message.getExtension(packedSfixed64ExtensionLite, 1)); assertEqualsExactType(711F , message.getExtension(packedFloatExtensionLite , 1)); assertEqualsExactType(712D , message.getExtension(packedDoubleExtensionLite , 1)); assertEqualsExactType(false, message.getExtension(packedBoolExtensionLite , 1)); assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAZ, message.getExtension(packedEnumExtensionLite, 1)); } // =================================================================== // oneof public static void setOneof(TestOneof2.Builder message) { message.setFooLazyMessage( TestOneof2.NestedMessage.newBuilder().setQuxInt(100).build()); message.setBarString("101"); message.setBazInt(102); message.setBazString("103"); } public static void assertOneofSet(TestOneof2 message) { Assert.assertTrue(message.hasFooLazyMessage ()); Assert.assertTrue(message.getFooLazyMessage().hasQuxInt()); Assert.assertTrue(message.hasBarString()); Assert.assertTrue(message.hasBazInt ()); Assert.assertTrue(message.hasBazString()); Assert.assertEquals(100 , message.getFooLazyMessage().getQuxInt()); Assert.assertEquals("101", message.getBarString ()); Assert.assertEquals(102 , message.getBazInt ()); Assert.assertEquals("103", message.getBazString ()); } public static void assertAtMostOneFieldSetOneof(TestOneof2 message) { int count = 0; if (message.hasFooInt()) { ++count; } if (message.hasFooString()) { ++count; } if (message.hasFooCord()) { ++count; } if (message.hasFooStringPiece()) { ++count; } if (message.hasFooBytes()) { ++count; } if (message.hasFooEnum()) { ++count; } if (message.hasFooMessage()) { ++count; } if (message.hasFooGroup()) { ++count; } if (message.hasFooLazyMessage()) { ++count; } Assert.assertTrue(count <= 1); count = 0; if (message.hasBarInt()) { ++count; } if (message.hasBarString()) { ++count; } if (message.hasBarCord()) { ++count; } if (message.hasBarStringPiece()) { ++count; } if (message.hasBarBytes()) { ++count; } if (message.hasBarEnum()) { ++count; } Assert.assertTrue(count <= 1); switch (message.getFooCase()) { case FOO_INT: Assert.assertTrue(message.hasFooInt()); break; case FOO_STRING: Assert.assertTrue(message.hasFooString()); break; case FOO_CORD: Assert.assertTrue(message.hasFooCord()); break; case FOO_BYTES: Assert.assertTrue(message.hasFooBytes()); break; case FOO_ENUM: Assert.assertTrue(message.hasFooEnum()); break; case FOO_MESSAGE: Assert.assertTrue(message.hasFooMessage()); break; case FOOGROUP: Assert.assertTrue(message.hasFooGroup()); break; case FOO_LAZY_MESSAGE: Assert.assertTrue(message.hasFooLazyMessage()); break; case FOO_NOT_SET: break; } } // ================================================================= /** * Performs the same things that the methods of {@code TestUtil} do, but * via the reflection interface. This is its own class because it needs * to know what descriptor to use. */ public static class ReflectionTester { private final Descriptors.Descriptor baseDescriptor; private final ExtensionRegistry extensionRegistry; private final Descriptors.FileDescriptor file; private final Descriptors.FileDescriptor importFile; private final Descriptors.FileDescriptor publicImportFile; private final Descriptors.Descriptor optionalGroup; private final Descriptors.Descriptor repeatedGroup; private final Descriptors.Descriptor nestedMessage; private final Descriptors.Descriptor foreignMessage; private final Descriptors.Descriptor importMessage; private final Descriptors.Descriptor publicImportMessage; private final Descriptors.FieldDescriptor groupA; private final Descriptors.FieldDescriptor repeatedGroupA; private final Descriptors.FieldDescriptor nestedB; private final Descriptors.FieldDescriptor foreignC; private final Descriptors.FieldDescriptor importD; private final Descriptors.FieldDescriptor importE; private final Descriptors.EnumDescriptor nestedEnum; private final Descriptors.EnumDescriptor foreignEnum; private final Descriptors.EnumDescriptor importEnum; private final Descriptors.EnumValueDescriptor nestedFoo; private final Descriptors.EnumValueDescriptor nestedBar; private final Descriptors.EnumValueDescriptor nestedBaz; private final Descriptors.EnumValueDescriptor foreignFoo; private final Descriptors.EnumValueDescriptor foreignBar; private final Descriptors.EnumValueDescriptor foreignBaz; private final Descriptors.EnumValueDescriptor importFoo; private final Descriptors.EnumValueDescriptor importBar; private final Descriptors.EnumValueDescriptor importBaz; /** * Construct a {@code ReflectionTester} that will expect messages using * the given descriptor. * * Normally {@code baseDescriptor} should be a descriptor for the type * {@code TestAllTypes}, defined in * {@code google/protobuf/unittest.proto}. However, if * {@code extensionRegistry} is non-null, then {@code baseDescriptor} should * be for {@code TestAllExtensions} instead, and instead of reading and * writing normal fields, the tester will read and write extensions. * All of {@code TestAllExtensions}' extensions must be registered in the * registry. */ public ReflectionTester(Descriptors.Descriptor baseDescriptor, ExtensionRegistry extensionRegistry) { this.baseDescriptor = baseDescriptor; this.extensionRegistry = extensionRegistry; this.file = baseDescriptor.getFile(); Assert.assertEquals(1, file.getDependencies().size()); this.importFile = file.getDependencies().get(0); this.publicImportFile = importFile.getDependencies().get(0); Descriptors.Descriptor testAllTypes; if (baseDescriptor.getName() == "TestAllTypes") { testAllTypes = baseDescriptor; } else { testAllTypes = file.findMessageTypeByName("TestAllTypes"); Assert.assertNotNull(testAllTypes); } if (extensionRegistry == null) { // Use testAllTypes, rather than baseDescriptor, to allow // initialization using TestPackedTypes descriptors. These objects // won't be used by the methods for packed fields. this.optionalGroup = testAllTypes.findNestedTypeByName("OptionalGroup"); this.repeatedGroup = testAllTypes.findNestedTypeByName("RepeatedGroup"); } else { this.optionalGroup = file.findMessageTypeByName("OptionalGroup_extension"); this.repeatedGroup = file.findMessageTypeByName("RepeatedGroup_extension"); } this.nestedMessage = testAllTypes.findNestedTypeByName("NestedMessage"); this.foreignMessage = file.findMessageTypeByName("ForeignMessage"); this.importMessage = importFile.findMessageTypeByName("ImportMessage"); this.publicImportMessage = publicImportFile.findMessageTypeByName( "PublicImportMessage"); this.nestedEnum = testAllTypes.findEnumTypeByName("NestedEnum"); this.foreignEnum = file.findEnumTypeByName("ForeignEnum"); this.importEnum = importFile.findEnumTypeByName("ImportEnum"); Assert.assertNotNull(optionalGroup ); Assert.assertNotNull(repeatedGroup ); Assert.assertNotNull(nestedMessage ); Assert.assertNotNull(foreignMessage); Assert.assertNotNull(importMessage ); Assert.assertNotNull(nestedEnum ); Assert.assertNotNull(foreignEnum ); Assert.assertNotNull(importEnum ); this.nestedB = nestedMessage .findFieldByName("bb"); this.foreignC = foreignMessage.findFieldByName("c"); this.importD = importMessage .findFieldByName("d"); this.importE = publicImportMessage.findFieldByName("e"); this.nestedFoo = nestedEnum.findValueByName("FOO"); this.nestedBar = nestedEnum.findValueByName("BAR"); this.nestedBaz = nestedEnum.findValueByName("BAZ"); this.foreignFoo = foreignEnum.findValueByName("FOREIGN_FOO"); this.foreignBar = foreignEnum.findValueByName("FOREIGN_BAR"); this.foreignBaz = foreignEnum.findValueByName("FOREIGN_BAZ"); this.importFoo = importEnum.findValueByName("IMPORT_FOO"); this.importBar = importEnum.findValueByName("IMPORT_BAR"); this.importBaz = importEnum.findValueByName("IMPORT_BAZ"); this.groupA = optionalGroup.findFieldByName("a"); this.repeatedGroupA = repeatedGroup.findFieldByName("a"); Assert.assertNotNull(groupA ); Assert.assertNotNull(repeatedGroupA); Assert.assertNotNull(nestedB ); Assert.assertNotNull(foreignC ); Assert.assertNotNull(importD ); Assert.assertNotNull(importE ); Assert.assertNotNull(nestedFoo ); Assert.assertNotNull(nestedBar ); Assert.assertNotNull(nestedBaz ); Assert.assertNotNull(foreignFoo ); Assert.assertNotNull(foreignBar ); Assert.assertNotNull(foreignBaz ); Assert.assertNotNull(importFoo ); Assert.assertNotNull(importBar ); Assert.assertNotNull(importBaz ); } /** * Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes. */ private Descriptors.FieldDescriptor f(String name) { Descriptors.FieldDescriptor result; if (extensionRegistry == null) { result = baseDescriptor.findFieldByName(name); } else { result = file.findExtensionByName(name + "_extension"); } Assert.assertNotNull(result); return result; } /** * Calls {@code parent.newBuilderForField()} or uses the * {@code ExtensionRegistry} to find an appropriate builder, depending * on what type is being tested. */ private Message.Builder newBuilderForField( Message.Builder parent, Descriptors.FieldDescriptor field) { if (extensionRegistry == null) { return parent.newBuilderForField(field); } else { ExtensionRegistry.ExtensionInfo extension = extensionRegistry.findImmutableExtensionByNumber( field.getContainingType(), field.getNumber()); Assert.assertNotNull(extension); Assert.assertNotNull(extension.defaultInstance); return extension.defaultInstance.newBuilderForType(); } } // ------------------------------------------------------------------- /** * Set every field of {@code message} to the values expected by * {@code assertAllFieldsSet()}, using the {@link Message.Builder} * reflection interface. */ void setAllFieldsViaReflection(Message.Builder message) { message.setField(f("optional_int32" ), 101 ); message.setField(f("optional_int64" ), 102L); message.setField(f("optional_uint32" ), 103 ); message.setField(f("optional_uint64" ), 104L); message.setField(f("optional_sint32" ), 105 ); message.setField(f("optional_sint64" ), 106L); message.setField(f("optional_fixed32" ), 107 ); message.setField(f("optional_fixed64" ), 108L); message.setField(f("optional_sfixed32"), 109 ); message.setField(f("optional_sfixed64"), 110L); message.setField(f("optional_float" ), 111F); message.setField(f("optional_double" ), 112D); message.setField(f("optional_bool" ), true); message.setField(f("optional_string" ), "115"); message.setField(f("optional_bytes" ), toBytes("116")); message.setField(f("optionalgroup"), newBuilderForField(message, f("optionalgroup")) .setField(groupA, 117).build()); message.setField(f("optional_nested_message"), newBuilderForField(message, f("optional_nested_message")) .setField(nestedB, 118).build()); message.setField(f("optional_foreign_message"), newBuilderForField(message, f("optional_foreign_message")) .setField(foreignC, 119).build()); message.setField(f("optional_import_message"), newBuilderForField(message, f("optional_import_message")) .setField(importD, 120).build()); message.setField(f("optional_public_import_message"), newBuilderForField(message, f("optional_public_import_message")) .setField(importE, 126).build()); message.setField(f("optional_lazy_message"), newBuilderForField(message, f("optional_lazy_message")) .setField(nestedB, 127).build()); message.setField(f("optional_nested_enum" ), nestedBaz); message.setField(f("optional_foreign_enum"), foreignBaz); message.setField(f("optional_import_enum" ), importBaz); message.setField(f("optional_string_piece" ), "124"); message.setField(f("optional_cord" ), "125"); // ----------------------------------------------------------------- message.addRepeatedField(f("repeated_int32" ), 201 ); message.addRepeatedField(f("repeated_int64" ), 202L); message.addRepeatedField(f("repeated_uint32" ), 203 ); message.addRepeatedField(f("repeated_uint64" ), 204L); message.addRepeatedField(f("repeated_sint32" ), 205 ); message.addRepeatedField(f("repeated_sint64" ), 206L); message.addRepeatedField(f("repeated_fixed32" ), 207 ); message.addRepeatedField(f("repeated_fixed64" ), 208L); message.addRepeatedField(f("repeated_sfixed32"), 209 ); message.addRepeatedField(f("repeated_sfixed64"), 210L); message.addRepeatedField(f("repeated_float" ), 211F); message.addRepeatedField(f("repeated_double" ), 212D); message.addRepeatedField(f("repeated_bool" ), true); message.addRepeatedField(f("repeated_string" ), "215"); message.addRepeatedField(f("repeated_bytes" ), toBytes("216")); message.addRepeatedField(f("repeatedgroup"), newBuilderForField(message, f("repeatedgroup")) .setField(repeatedGroupA, 217).build()); message.addRepeatedField(f("repeated_nested_message"), newBuilderForField(message, f("repeated_nested_message")) .setField(nestedB, 218).build()); message.addRepeatedField(f("repeated_foreign_message"), newBuilderForField(message, f("repeated_foreign_message")) .setField(foreignC, 219).build()); message.addRepeatedField(f("repeated_import_message"), newBuilderForField(message, f("repeated_import_message")) .setField(importD, 220).build()); message.addRepeatedField(f("repeated_lazy_message"), newBuilderForField(message, f("repeated_lazy_message")) .setField(nestedB, 227).build()); message.addRepeatedField(f("repeated_nested_enum" ), nestedBar); message.addRepeatedField(f("repeated_foreign_enum"), foreignBar); message.addRepeatedField(f("repeated_import_enum" ), importBar); message.addRepeatedField(f("repeated_string_piece" ), "224"); message.addRepeatedField(f("repeated_cord" ), "225"); // Add a second one of each field. message.addRepeatedField(f("repeated_int32" ), 301 ); message.addRepeatedField(f("repeated_int64" ), 302L); message.addRepeatedField(f("repeated_uint32" ), 303 ); message.addRepeatedField(f("repeated_uint64" ), 304L); message.addRepeatedField(f("repeated_sint32" ), 305 ); message.addRepeatedField(f("repeated_sint64" ), 306L); message.addRepeatedField(f("repeated_fixed32" ), 307 ); message.addRepeatedField(f("repeated_fixed64" ), 308L); message.addRepeatedField(f("repeated_sfixed32"), 309 ); message.addRepeatedField(f("repeated_sfixed64"), 310L); message.addRepeatedField(f("repeated_float" ), 311F); message.addRepeatedField(f("repeated_double" ), 312D); message.addRepeatedField(f("repeated_bool" ), false); message.addRepeatedField(f("repeated_string" ), "315"); message.addRepeatedField(f("repeated_bytes" ), toBytes("316")); message.addRepeatedField(f("repeatedgroup"), newBuilderForField(message, f("repeatedgroup")) .setField(repeatedGroupA, 317).build()); message.addRepeatedField(f("repeated_nested_message"), newBuilderForField(message, f("repeated_nested_message")) .setField(nestedB, 318).build()); message.addRepeatedField(f("repeated_foreign_message"), newBuilderForField(message, f("repeated_foreign_message")) .setField(foreignC, 319).build()); message.addRepeatedField(f("repeated_import_message"), newBuilderForField(message, f("repeated_import_message")) .setField(importD, 320).build()); message.addRepeatedField(f("repeated_lazy_message"), newBuilderForField(message, f("repeated_lazy_message")) .setField(nestedB, 327).build()); message.addRepeatedField(f("repeated_nested_enum" ), nestedBaz); message.addRepeatedField(f("repeated_foreign_enum"), foreignBaz); message.addRepeatedField(f("repeated_import_enum" ), importBaz); message.addRepeatedField(f("repeated_string_piece" ), "324"); message.addRepeatedField(f("repeated_cord" ), "325"); // ----------------------------------------------------------------- message.setField(f("default_int32" ), 401 ); message.setField(f("default_int64" ), 402L); message.setField(f("default_uint32" ), 403 ); message.setField(f("default_uint64" ), 404L); message.setField(f("default_sint32" ), 405 ); message.setField(f("default_sint64" ), 406L); message.setField(f("default_fixed32" ), 407 ); message.setField(f("default_fixed64" ), 408L); message.setField(f("default_sfixed32"), 409 ); message.setField(f("default_sfixed64"), 410L); message.setField(f("default_float" ), 411F); message.setField(f("default_double" ), 412D); message.setField(f("default_bool" ), false); message.setField(f("default_string" ), "415"); message.setField(f("default_bytes" ), toBytes("416")); message.setField(f("default_nested_enum" ), nestedFoo); message.setField(f("default_foreign_enum"), foreignFoo); message.setField(f("default_import_enum" ), importFoo); message.setField(f("default_string_piece" ), "424"); message.setField(f("default_cord" ), "425"); message.setField(f("oneof_uint32" ), 601); message.setField(f("oneof_nested_message"), newBuilderForField(message, f("oneof_nested_message")) .setField(nestedB, 602).build()); message.setField(f("oneof_string" ), "603"); message.setField(f("oneof_bytes" ), toBytes("604")); } // ------------------------------------------------------------------- /** * Modify the repeated fields of {@code message} to contain the values * expected by {@code assertRepeatedFieldsModified()}, using the * {@link Message.Builder} reflection interface. */ void modifyRepeatedFieldsViaReflection(Message.Builder message) { message.setRepeatedField(f("repeated_int32" ), 1, 501 ); message.setRepeatedField(f("repeated_int64" ), 1, 502L); message.setRepeatedField(f("repeated_uint32" ), 1, 503 ); message.setRepeatedField(f("repeated_uint64" ), 1, 504L); message.setRepeatedField(f("repeated_sint32" ), 1, 505 ); message.setRepeatedField(f("repeated_sint64" ), 1, 506L); message.setRepeatedField(f("repeated_fixed32" ), 1, 507 ); message.setRepeatedField(f("repeated_fixed64" ), 1, 508L); message.setRepeatedField(f("repeated_sfixed32"), 1, 509 ); message.setRepeatedField(f("repeated_sfixed64"), 1, 510L); message.setRepeatedField(f("repeated_float" ), 1, 511F); message.setRepeatedField(f("repeated_double" ), 1, 512D); message.setRepeatedField(f("repeated_bool" ), 1, true); message.setRepeatedField(f("repeated_string" ), 1, "515"); message.setRepeatedField(f("repeated_bytes" ), 1, toBytes("516")); message.setRepeatedField(f("repeatedgroup"), 1, newBuilderForField(message, f("repeatedgroup")) .setField(repeatedGroupA, 517).build()); message.setRepeatedField(f("repeated_nested_message"), 1, newBuilderForField(message, f("repeated_nested_message")) .setField(nestedB, 518).build()); message.setRepeatedField(f("repeated_foreign_message"), 1, newBuilderForField(message, f("repeated_foreign_message")) .setField(foreignC, 519).build()); message.setRepeatedField(f("repeated_import_message"), 1, newBuilderForField(message, f("repeated_import_message")) .setField(importD, 520).build()); message.setRepeatedField(f("repeated_lazy_message"), 1, newBuilderForField(message, f("repeated_lazy_message")) .setField(nestedB, 527).build()); message.setRepeatedField(f("repeated_nested_enum" ), 1, nestedFoo); message.setRepeatedField(f("repeated_foreign_enum"), 1, foreignFoo); message.setRepeatedField(f("repeated_import_enum" ), 1, importFoo); message.setRepeatedField(f("repeated_string_piece"), 1, "524"); message.setRepeatedField(f("repeated_cord"), 1, "525"); } // ------------------------------------------------------------------- /** * Assert (using {@code junit.framework.Assert}} that all fields of * {@code message} are set to the values assigned by {@code setAllFields}, * using the {@link Message} reflection interface. */ public void assertAllFieldsSetViaReflection(MessageOrBuilder message) { Assert.assertTrue(message.hasField(f("optional_int32" ))); Assert.assertTrue(message.hasField(f("optional_int64" ))); Assert.assertTrue(message.hasField(f("optional_uint32" ))); Assert.assertTrue(message.hasField(f("optional_uint64" ))); Assert.assertTrue(message.hasField(f("optional_sint32" ))); Assert.assertTrue(message.hasField(f("optional_sint64" ))); Assert.assertTrue(message.hasField(f("optional_fixed32" ))); Assert.assertTrue(message.hasField(f("optional_fixed64" ))); Assert.assertTrue(message.hasField(f("optional_sfixed32"))); Assert.assertTrue(message.hasField(f("optional_sfixed64"))); Assert.assertTrue(message.hasField(f("optional_float" ))); Assert.assertTrue(message.hasField(f("optional_double" ))); Assert.assertTrue(message.hasField(f("optional_bool" ))); Assert.assertTrue(message.hasField(f("optional_string" ))); Assert.assertTrue(message.hasField(f("optional_bytes" ))); Assert.assertTrue(message.hasField(f("optionalgroup" ))); Assert.assertTrue(message.hasField(f("optional_nested_message" ))); Assert.assertTrue(message.hasField(f("optional_foreign_message"))); Assert.assertTrue(message.hasField(f("optional_import_message" ))); Assert.assertTrue( ((Message)message.getField(f("optionalgroup"))).hasField(groupA)); Assert.assertTrue( ((Message)message.getField(f("optional_nested_message"))) .hasField(nestedB)); Assert.assertTrue( ((Message)message.getField(f("optional_foreign_message"))) .hasField(foreignC)); Assert.assertTrue( ((Message)message.getField(f("optional_import_message"))) .hasField(importD)); Assert.assertTrue(message.hasField(f("optional_nested_enum" ))); Assert.assertTrue(message.hasField(f("optional_foreign_enum"))); Assert.assertTrue(message.hasField(f("optional_import_enum" ))); Assert.assertTrue(message.hasField(f("optional_string_piece"))); Assert.assertTrue(message.hasField(f("optional_cord"))); Assert.assertEquals(101 , message.getField(f("optional_int32" ))); Assert.assertEquals(102L , message.getField(f("optional_int64" ))); Assert.assertEquals(103 , message.getField(f("optional_uint32" ))); Assert.assertEquals(104L , message.getField(f("optional_uint64" ))); Assert.assertEquals(105 , message.getField(f("optional_sint32" ))); Assert.assertEquals(106L , message.getField(f("optional_sint64" ))); Assert.assertEquals(107 , message.getField(f("optional_fixed32" ))); Assert.assertEquals(108L , message.getField(f("optional_fixed64" ))); Assert.assertEquals(109 , message.getField(f("optional_sfixed32"))); Assert.assertEquals(110L , message.getField(f("optional_sfixed64"))); Assert.assertEquals(111F , message.getField(f("optional_float" ))); Assert.assertEquals(112D , message.getField(f("optional_double" ))); Assert.assertEquals(true , message.getField(f("optional_bool" ))); Assert.assertEquals("115", message.getField(f("optional_string" ))); Assert.assertEquals(toBytes("116"), message.getField(f("optional_bytes"))); Assert.assertEquals(117, ((Message)message.getField(f("optionalgroup"))).getField(groupA)); Assert.assertEquals(118, ((Message)message.getField(f("optional_nested_message"))) .getField(nestedB)); Assert.assertEquals(119, ((Message)message.getField(f("optional_foreign_message"))) .getField(foreignC)); Assert.assertEquals(120, ((Message)message.getField(f("optional_import_message"))) .getField(importD)); Assert.assertEquals(126, ((Message)message.getField(f("optional_public_import_message"))) .getField(importE)); Assert.assertEquals(127, ((Message)message.getField(f("optional_lazy_message"))) .getField(nestedB)); Assert.assertEquals( nestedBaz, message.getField(f("optional_nested_enum" ))); Assert.assertEquals(foreignBaz, message.getField(f("optional_foreign_enum"))); Assert.assertEquals( importBaz, message.getField(f("optional_import_enum" ))); Assert.assertEquals("124", message.getField(f("optional_string_piece"))); Assert.assertEquals("125", message.getField(f("optional_cord"))); // ----------------------------------------------------------------- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed32"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed64"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_message"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string_piece"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_cord"))); Assert.assertEquals(201 , message.getRepeatedField(f("repeated_int32" ), 0)); Assert.assertEquals(202L , message.getRepeatedField(f("repeated_int64" ), 0)); Assert.assertEquals(203 , message.getRepeatedField(f("repeated_uint32" ), 0)); Assert.assertEquals(204L , message.getRepeatedField(f("repeated_uint64" ), 0)); Assert.assertEquals(205 , message.getRepeatedField(f("repeated_sint32" ), 0)); Assert.assertEquals(206L , message.getRepeatedField(f("repeated_sint64" ), 0)); Assert.assertEquals(207 , message.getRepeatedField(f("repeated_fixed32" ), 0)); Assert.assertEquals(208L , message.getRepeatedField(f("repeated_fixed64" ), 0)); Assert.assertEquals(209 , message.getRepeatedField(f("repeated_sfixed32"), 0)); Assert.assertEquals(210L , message.getRepeatedField(f("repeated_sfixed64"), 0)); Assert.assertEquals(211F , message.getRepeatedField(f("repeated_float" ), 0)); Assert.assertEquals(212D , message.getRepeatedField(f("repeated_double" ), 0)); Assert.assertEquals(true , message.getRepeatedField(f("repeated_bool" ), 0)); Assert.assertEquals("215", message.getRepeatedField(f("repeated_string" ), 0)); Assert.assertEquals(toBytes("216"), message.getRepeatedField(f("repeated_bytes"), 0)); Assert.assertEquals(217, ((Message)message.getRepeatedField(f("repeatedgroup"), 0)) .getField(repeatedGroupA)); Assert.assertEquals(218, ((Message)message.getRepeatedField(f("repeated_nested_message"), 0)) .getField(nestedB)); Assert.assertEquals(219, ((Message)message.getRepeatedField(f("repeated_foreign_message"), 0)) .getField(foreignC)); Assert.assertEquals(220, ((Message)message.getRepeatedField(f("repeated_import_message"), 0)) .getField(importD)); Assert.assertEquals(227, ((Message)message.getRepeatedField(f("repeated_lazy_message"), 0)) .getField(nestedB)); Assert.assertEquals( nestedBar, message.getRepeatedField(f("repeated_nested_enum" ),0)); Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"),0)); Assert.assertEquals( importBar, message.getRepeatedField(f("repeated_import_enum" ),0)); Assert.assertEquals("224", message.getRepeatedField(f("repeated_string_piece"), 0)); Assert.assertEquals("225", message.getRepeatedField(f("repeated_cord"), 0)); Assert.assertEquals(301 , message.getRepeatedField(f("repeated_int32" ), 1)); Assert.assertEquals(302L , message.getRepeatedField(f("repeated_int64" ), 1)); Assert.assertEquals(303 , message.getRepeatedField(f("repeated_uint32" ), 1)); Assert.assertEquals(304L , message.getRepeatedField(f("repeated_uint64" ), 1)); Assert.assertEquals(305 , message.getRepeatedField(f("repeated_sint32" ), 1)); Assert.assertEquals(306L , message.getRepeatedField(f("repeated_sint64" ), 1)); Assert.assertEquals(307 , message.getRepeatedField(f("repeated_fixed32" ), 1)); Assert.assertEquals(308L , message.getRepeatedField(f("repeated_fixed64" ), 1)); Assert.assertEquals(309 , message.getRepeatedField(f("repeated_sfixed32"), 1)); Assert.assertEquals(310L , message.getRepeatedField(f("repeated_sfixed64"), 1)); Assert.assertEquals(311F , message.getRepeatedField(f("repeated_float" ), 1)); Assert.assertEquals(312D , message.getRepeatedField(f("repeated_double" ), 1)); Assert.assertEquals(false, message.getRepeatedField(f("repeated_bool" ), 1)); Assert.assertEquals("315", message.getRepeatedField(f("repeated_string" ), 1)); Assert.assertEquals(toBytes("316"), message.getRepeatedField(f("repeated_bytes"), 1)); Assert.assertEquals(317, ((Message)message.getRepeatedField(f("repeatedgroup"), 1)) .getField(repeatedGroupA)); Assert.assertEquals(318, ((Message)message.getRepeatedField(f("repeated_nested_message"), 1)) .getField(nestedB)); Assert.assertEquals(319, ((Message)message.getRepeatedField(f("repeated_foreign_message"), 1)) .getField(foreignC)); Assert.assertEquals(320, ((Message)message.getRepeatedField(f("repeated_import_message"), 1)) .getField(importD)); Assert.assertEquals(327, ((Message)message.getRepeatedField(f("repeated_lazy_message"), 1)) .getField(nestedB)); Assert.assertEquals( nestedBaz, message.getRepeatedField(f("repeated_nested_enum" ),1)); Assert.assertEquals(foreignBaz, message.getRepeatedField(f("repeated_foreign_enum"),1)); Assert.assertEquals( importBaz, message.getRepeatedField(f("repeated_import_enum" ),1)); Assert.assertEquals("324", message.getRepeatedField(f("repeated_string_piece"), 1)); Assert.assertEquals("325", message.getRepeatedField(f("repeated_cord"), 1)); // ----------------------------------------------------------------- Assert.assertTrue(message.hasField(f("default_int32" ))); Assert.assertTrue(message.hasField(f("default_int64" ))); Assert.assertTrue(message.hasField(f("default_uint32" ))); Assert.assertTrue(message.hasField(f("default_uint64" ))); Assert.assertTrue(message.hasField(f("default_sint32" ))); Assert.assertTrue(message.hasField(f("default_sint64" ))); Assert.assertTrue(message.hasField(f("default_fixed32" ))); Assert.assertTrue(message.hasField(f("default_fixed64" ))); Assert.assertTrue(message.hasField(f("default_sfixed32"))); Assert.assertTrue(message.hasField(f("default_sfixed64"))); Assert.assertTrue(message.hasField(f("default_float" ))); Assert.assertTrue(message.hasField(f("default_double" ))); Assert.assertTrue(message.hasField(f("default_bool" ))); Assert.assertTrue(message.hasField(f("default_string" ))); Assert.assertTrue(message.hasField(f("default_bytes" ))); Assert.assertTrue(message.hasField(f("default_nested_enum" ))); Assert.assertTrue(message.hasField(f("default_foreign_enum"))); Assert.assertTrue(message.hasField(f("default_import_enum" ))); Assert.assertTrue(message.hasField(f("default_string_piece"))); Assert.assertTrue(message.hasField(f("default_cord"))); Assert.assertEquals(401 , message.getField(f("default_int32" ))); Assert.assertEquals(402L , message.getField(f("default_int64" ))); Assert.assertEquals(403 , message.getField(f("default_uint32" ))); Assert.assertEquals(404L , message.getField(f("default_uint64" ))); Assert.assertEquals(405 , message.getField(f("default_sint32" ))); Assert.assertEquals(406L , message.getField(f("default_sint64" ))); Assert.assertEquals(407 , message.getField(f("default_fixed32" ))); Assert.assertEquals(408L , message.getField(f("default_fixed64" ))); Assert.assertEquals(409 , message.getField(f("default_sfixed32"))); Assert.assertEquals(410L , message.getField(f("default_sfixed64"))); Assert.assertEquals(411F , message.getField(f("default_float" ))); Assert.assertEquals(412D , message.getField(f("default_double" ))); Assert.assertEquals(false, message.getField(f("default_bool" ))); Assert.assertEquals("415", message.getField(f("default_string" ))); Assert.assertEquals(toBytes("416"), message.getField(f("default_bytes"))); Assert.assertEquals( nestedFoo, message.getField(f("default_nested_enum" ))); Assert.assertEquals(foreignFoo, message.getField(f("default_foreign_enum"))); Assert.assertEquals( importFoo, message.getField(f("default_import_enum" ))); Assert.assertEquals("424", message.getField(f("default_string_piece"))); Assert.assertEquals("425", message.getField(f("default_cord"))); Assert.assertTrue(message.hasField(f("oneof_bytes"))); Assert.assertEquals(toBytes("604"), message.getField(f("oneof_bytes"))); if (extensionRegistry == null) { Assert.assertFalse(message.hasField(f("oneof_uint32"))); Assert.assertFalse(message.hasField(f("oneof_nested_message"))); Assert.assertFalse(message.hasField(f("oneof_string"))); } else { Assert.assertTrue(message.hasField(f("oneof_uint32"))); Assert.assertTrue(message.hasField(f("oneof_nested_message"))); Assert.assertTrue(message.hasField(f("oneof_string"))); Assert.assertEquals(601, message.getField(f("oneof_uint32"))); Assert.assertEquals(602, ((MessageOrBuilder) message.getField(f("oneof_nested_message"))) .getField(nestedB)); Assert.assertEquals("603", message.getField(f("oneof_string"))); } } // ------------------------------------------------------------------- /** * Assert (using {@code junit.framework.Assert}} that all fields of * {@code message} are cleared, and that getting the fields returns their * default values, using the {@link Message} reflection interface. */ public void assertClearViaReflection(MessageOrBuilder message) { // has_blah() should initially be false for all optional fields. Assert.assertFalse(message.hasField(f("optional_int32" ))); Assert.assertFalse(message.hasField(f("optional_int64" ))); Assert.assertFalse(message.hasField(f("optional_uint32" ))); Assert.assertFalse(message.hasField(f("optional_uint64" ))); Assert.assertFalse(message.hasField(f("optional_sint32" ))); Assert.assertFalse(message.hasField(f("optional_sint64" ))); Assert.assertFalse(message.hasField(f("optional_fixed32" ))); Assert.assertFalse(message.hasField(f("optional_fixed64" ))); Assert.assertFalse(message.hasField(f("optional_sfixed32"))); Assert.assertFalse(message.hasField(f("optional_sfixed64"))); Assert.assertFalse(message.hasField(f("optional_float" ))); Assert.assertFalse(message.hasField(f("optional_double" ))); Assert.assertFalse(message.hasField(f("optional_bool" ))); Assert.assertFalse(message.hasField(f("optional_string" ))); Assert.assertFalse(message.hasField(f("optional_bytes" ))); Assert.assertFalse(message.hasField(f("optionalgroup" ))); Assert.assertFalse(message.hasField(f("optional_nested_message" ))); Assert.assertFalse(message.hasField(f("optional_foreign_message"))); Assert.assertFalse(message.hasField(f("optional_import_message" ))); Assert.assertFalse(message.hasField(f("optional_nested_enum" ))); Assert.assertFalse(message.hasField(f("optional_foreign_enum"))); Assert.assertFalse(message.hasField(f("optional_import_enum" ))); Assert.assertFalse(message.hasField(f("optional_string_piece"))); Assert.assertFalse(message.hasField(f("optional_cord"))); // Optional fields without defaults are set to zero or something like it. Assert.assertEquals(0 , message.getField(f("optional_int32" ))); Assert.assertEquals(0L , message.getField(f("optional_int64" ))); Assert.assertEquals(0 , message.getField(f("optional_uint32" ))); Assert.assertEquals(0L , message.getField(f("optional_uint64" ))); Assert.assertEquals(0 , message.getField(f("optional_sint32" ))); Assert.assertEquals(0L , message.getField(f("optional_sint64" ))); Assert.assertEquals(0 , message.getField(f("optional_fixed32" ))); Assert.assertEquals(0L , message.getField(f("optional_fixed64" ))); Assert.assertEquals(0 , message.getField(f("optional_sfixed32"))); Assert.assertEquals(0L , message.getField(f("optional_sfixed64"))); Assert.assertEquals(0F , message.getField(f("optional_float" ))); Assert.assertEquals(0D , message.getField(f("optional_double" ))); Assert.assertEquals(false, message.getField(f("optional_bool" ))); Assert.assertEquals("" , message.getField(f("optional_string" ))); Assert.assertEquals(ByteString.EMPTY, message.getField(f("optional_bytes"))); // Embedded messages should also be clear. Assert.assertFalse( ((Message)message.getField(f("optionalgroup"))).hasField(groupA)); Assert.assertFalse( ((Message)message.getField(f("optional_nested_message"))) .hasField(nestedB)); Assert.assertFalse( ((Message)message.getField(f("optional_foreign_message"))) .hasField(foreignC)); Assert.assertFalse( ((Message)message.getField(f("optional_import_message"))) .hasField(importD)); Assert.assertFalse( ((Message)message.getField(f("optional_public_import_message"))) .hasField(importE)); Assert.assertFalse( ((Message)message.getField(f("optional_lazy_message"))) .hasField(nestedB)); Assert.assertEquals(0, ((Message)message.getField(f("optionalgroup"))).getField(groupA)); Assert.assertEquals(0, ((Message)message.getField(f("optional_nested_message"))) .getField(nestedB)); Assert.assertEquals(0, ((Message)message.getField(f("optional_foreign_message"))) .getField(foreignC)); Assert.assertEquals(0, ((Message)message.getField(f("optional_import_message"))) .getField(importD)); Assert.assertEquals(0, ((Message)message.getField(f("optional_public_import_message"))) .getField(importE)); Assert.assertEquals(0, ((Message)message.getField(f("optional_lazy_message"))) .getField(nestedB)); // Enums without defaults are set to the first value in the enum. Assert.assertEquals( nestedFoo, message.getField(f("optional_nested_enum" ))); Assert.assertEquals(foreignFoo, message.getField(f("optional_foreign_enum"))); Assert.assertEquals( importFoo, message.getField(f("optional_import_enum" ))); Assert.assertEquals("", message.getField(f("optional_string_piece"))); Assert.assertEquals("", message.getField(f("optional_cord"))); // Repeated fields are empty. Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int32" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int64" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint32" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint64" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint32" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint64" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed32" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed64" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sfixed32"))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sfixed64"))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_float" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_double" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bool" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_string" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bytes" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeatedgroup" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_message" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_foreign_message"))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_message" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_lazy_message" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_enum" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_foreign_enum" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_enum" ))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_string_piece"))); Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_cord"))); // has_blah() should also be false for all default fields. Assert.assertFalse(message.hasField(f("default_int32" ))); Assert.assertFalse(message.hasField(f("default_int64" ))); Assert.assertFalse(message.hasField(f("default_uint32" ))); Assert.assertFalse(message.hasField(f("default_uint64" ))); Assert.assertFalse(message.hasField(f("default_sint32" ))); Assert.assertFalse(message.hasField(f("default_sint64" ))); Assert.assertFalse(message.hasField(f("default_fixed32" ))); Assert.assertFalse(message.hasField(f("default_fixed64" ))); Assert.assertFalse(message.hasField(f("default_sfixed32"))); Assert.assertFalse(message.hasField(f("default_sfixed64"))); Assert.assertFalse(message.hasField(f("default_float" ))); Assert.assertFalse(message.hasField(f("default_double" ))); Assert.assertFalse(message.hasField(f("default_bool" ))); Assert.assertFalse(message.hasField(f("default_string" ))); Assert.assertFalse(message.hasField(f("default_bytes" ))); Assert.assertFalse(message.hasField(f("default_nested_enum" ))); Assert.assertFalse(message.hasField(f("default_foreign_enum"))); Assert.assertFalse(message.hasField(f("default_import_enum" ))); Assert.assertFalse(message.hasField(f("default_string_piece" ))); Assert.assertFalse(message.hasField(f("default_cord" ))); // Fields with defaults have their default values (duh). Assert.assertEquals( 41 , message.getField(f("default_int32" ))); Assert.assertEquals( 42L , message.getField(f("default_int64" ))); Assert.assertEquals( 43 , message.getField(f("default_uint32" ))); Assert.assertEquals( 44L , message.getField(f("default_uint64" ))); Assert.assertEquals(-45 , message.getField(f("default_sint32" ))); Assert.assertEquals( 46L , message.getField(f("default_sint64" ))); Assert.assertEquals( 47 , message.getField(f("default_fixed32" ))); Assert.assertEquals( 48L , message.getField(f("default_fixed64" ))); Assert.assertEquals( 49 , message.getField(f("default_sfixed32"))); Assert.assertEquals(-50L , message.getField(f("default_sfixed64"))); Assert.assertEquals( 51.5F , message.getField(f("default_float" ))); Assert.assertEquals( 52e3D , message.getField(f("default_double" ))); Assert.assertEquals(true , message.getField(f("default_bool" ))); Assert.assertEquals("hello", message.getField(f("default_string" ))); Assert.assertEquals(toBytes("world"), message.getField(f("default_bytes"))); Assert.assertEquals( nestedBar, message.getField(f("default_nested_enum" ))); Assert.assertEquals(foreignBar, message.getField(f("default_foreign_enum"))); Assert.assertEquals( importBar, message.getField(f("default_import_enum" ))); Assert.assertEquals("abc", message.getField(f("default_string_piece"))); Assert.assertEquals("123", message.getField(f("default_cord"))); Assert.assertFalse(message.hasField(f("oneof_uint32"))); Assert.assertFalse(message.hasField(f("oneof_nested_message"))); Assert.assertFalse(message.hasField(f("oneof_string"))); Assert.assertFalse(message.hasField(f("oneof_bytes"))); Assert.assertEquals(0, message.getField(f("oneof_uint32"))); Assert.assertEquals("", message.getField(f("oneof_string"))); Assert.assertEquals(toBytes(""), message.getField(f("oneof_bytes"))); } // --------------------------------------------------------------- public void assertRepeatedFieldsModifiedViaReflection( MessageOrBuilder message) { // ModifyRepeatedFields only sets the second repeated element of each // field. In addition to verifying this, we also verify that the first // element and size were *not* modified. Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed32"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed64"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_message"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string_piece"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_cord"))); Assert.assertEquals(201 , message.getRepeatedField(f("repeated_int32" ), 0)); Assert.assertEquals(202L , message.getRepeatedField(f("repeated_int64" ), 0)); Assert.assertEquals(203 , message.getRepeatedField(f("repeated_uint32" ), 0)); Assert.assertEquals(204L , message.getRepeatedField(f("repeated_uint64" ), 0)); Assert.assertEquals(205 , message.getRepeatedField(f("repeated_sint32" ), 0)); Assert.assertEquals(206L , message.getRepeatedField(f("repeated_sint64" ), 0)); Assert.assertEquals(207 , message.getRepeatedField(f("repeated_fixed32" ), 0)); Assert.assertEquals(208L , message.getRepeatedField(f("repeated_fixed64" ), 0)); Assert.assertEquals(209 , message.getRepeatedField(f("repeated_sfixed32"), 0)); Assert.assertEquals(210L , message.getRepeatedField(f("repeated_sfixed64"), 0)); Assert.assertEquals(211F , message.getRepeatedField(f("repeated_float" ), 0)); Assert.assertEquals(212D , message.getRepeatedField(f("repeated_double" ), 0)); Assert.assertEquals(true , message.getRepeatedField(f("repeated_bool" ), 0)); Assert.assertEquals("215", message.getRepeatedField(f("repeated_string" ), 0)); Assert.assertEquals(toBytes("216"), message.getRepeatedField(f("repeated_bytes"), 0)); Assert.assertEquals(217, ((Message)message.getRepeatedField(f("repeatedgroup"), 0)) .getField(repeatedGroupA)); Assert.assertEquals(218, ((Message)message.getRepeatedField(f("repeated_nested_message"), 0)) .getField(nestedB)); Assert.assertEquals(219, ((Message)message.getRepeatedField(f("repeated_foreign_message"), 0)) .getField(foreignC)); Assert.assertEquals(220, ((Message)message.getRepeatedField(f("repeated_import_message"), 0)) .getField(importD)); Assert.assertEquals(227, ((Message)message.getRepeatedField(f("repeated_lazy_message"), 0)) .getField(nestedB)); Assert.assertEquals( nestedBar, message.getRepeatedField(f("repeated_nested_enum" ),0)); Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"),0)); Assert.assertEquals( importBar, message.getRepeatedField(f("repeated_import_enum" ),0)); Assert.assertEquals("224", message.getRepeatedField(f("repeated_string_piece"), 0)); Assert.assertEquals("225", message.getRepeatedField(f("repeated_cord"), 0)); Assert.assertEquals(501 , message.getRepeatedField(f("repeated_int32" ), 1)); Assert.assertEquals(502L , message.getRepeatedField(f("repeated_int64" ), 1)); Assert.assertEquals(503 , message.getRepeatedField(f("repeated_uint32" ), 1)); Assert.assertEquals(504L , message.getRepeatedField(f("repeated_uint64" ), 1)); Assert.assertEquals(505 , message.getRepeatedField(f("repeated_sint32" ), 1)); Assert.assertEquals(506L , message.getRepeatedField(f("repeated_sint64" ), 1)); Assert.assertEquals(507 , message.getRepeatedField(f("repeated_fixed32" ), 1)); Assert.assertEquals(508L , message.getRepeatedField(f("repeated_fixed64" ), 1)); Assert.assertEquals(509 , message.getRepeatedField(f("repeated_sfixed32"), 1)); Assert.assertEquals(510L , message.getRepeatedField(f("repeated_sfixed64"), 1)); Assert.assertEquals(511F , message.getRepeatedField(f("repeated_float" ), 1)); Assert.assertEquals(512D , message.getRepeatedField(f("repeated_double" ), 1)); Assert.assertEquals(true , message.getRepeatedField(f("repeated_bool" ), 1)); Assert.assertEquals("515", message.getRepeatedField(f("repeated_string" ), 1)); Assert.assertEquals(toBytes("516"), message.getRepeatedField(f("repeated_bytes"), 1)); Assert.assertEquals(517, ((Message)message.getRepeatedField(f("repeatedgroup"), 1)) .getField(repeatedGroupA)); Assert.assertEquals(518, ((Message)message.getRepeatedField(f("repeated_nested_message"), 1)) .getField(nestedB)); Assert.assertEquals(519, ((Message)message.getRepeatedField(f("repeated_foreign_message"), 1)) .getField(foreignC)); Assert.assertEquals(520, ((Message)message.getRepeatedField(f("repeated_import_message"), 1)) .getField(importD)); Assert.assertEquals(527, ((Message)message.getRepeatedField(f("repeated_lazy_message"), 1)) .getField(nestedB)); Assert.assertEquals( nestedFoo, message.getRepeatedField(f("repeated_nested_enum" ),1)); Assert.assertEquals(foreignFoo, message.getRepeatedField(f("repeated_foreign_enum"),1)); Assert.assertEquals( importFoo, message.getRepeatedField(f("repeated_import_enum" ),1)); Assert.assertEquals("524", message.getRepeatedField(f("repeated_string_piece"), 1)); Assert.assertEquals("525", message.getRepeatedField(f("repeated_cord"), 1)); } public void setPackedFieldsViaReflection(Message.Builder message) { message.addRepeatedField(f("packed_int32" ), 601 ); message.addRepeatedField(f("packed_int64" ), 602L); message.addRepeatedField(f("packed_uint32" ), 603 ); message.addRepeatedField(f("packed_uint64" ), 604L); message.addRepeatedField(f("packed_sint32" ), 605 ); message.addRepeatedField(f("packed_sint64" ), 606L); message.addRepeatedField(f("packed_fixed32" ), 607 ); message.addRepeatedField(f("packed_fixed64" ), 608L); message.addRepeatedField(f("packed_sfixed32"), 609 ); message.addRepeatedField(f("packed_sfixed64"), 610L); message.addRepeatedField(f("packed_float" ), 611F); message.addRepeatedField(f("packed_double" ), 612D); message.addRepeatedField(f("packed_bool" ), true); message.addRepeatedField(f("packed_enum" ), foreignBar); // Add a second one of each field. message.addRepeatedField(f("packed_int32" ), 701 ); message.addRepeatedField(f("packed_int64" ), 702L); message.addRepeatedField(f("packed_uint32" ), 703 ); message.addRepeatedField(f("packed_uint64" ), 704L); message.addRepeatedField(f("packed_sint32" ), 705 ); message.addRepeatedField(f("packed_sint64" ), 706L); message.addRepeatedField(f("packed_fixed32" ), 707 ); message.addRepeatedField(f("packed_fixed64" ), 708L); message.addRepeatedField(f("packed_sfixed32"), 709 ); message.addRepeatedField(f("packed_sfixed64"), 710L); message.addRepeatedField(f("packed_float" ), 711F); message.addRepeatedField(f("packed_double" ), 712D); message.addRepeatedField(f("packed_bool" ), false); message.addRepeatedField(f("packed_enum" ), foreignBaz); } public void assertPackedFieldsSetViaReflection(MessageOrBuilder message) { Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int32" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int64" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint32" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint64" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint32" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint64" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed32" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed64" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sfixed32"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sfixed64"))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_float" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_double" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_bool" ))); Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_enum" ))); Assert.assertEquals(601 , message.getRepeatedField(f("packed_int32" ), 0)); Assert.assertEquals(602L , message.getRepeatedField(f("packed_int64" ), 0)); Assert.assertEquals(603 , message.getRepeatedField(f("packed_uint32" ), 0)); Assert.assertEquals(604L , message.getRepeatedField(f("packed_uint64" ), 0)); Assert.assertEquals(605 , message.getRepeatedField(f("packed_sint32" ), 0)); Assert.assertEquals(606L , message.getRepeatedField(f("packed_sint64" ), 0)); Assert.assertEquals(607 , message.getRepeatedField(f("packed_fixed32" ), 0)); Assert.assertEquals(608L , message.getRepeatedField(f("packed_fixed64" ), 0)); Assert.assertEquals(609 , message.getRepeatedField(f("packed_sfixed32"), 0)); Assert.assertEquals(610L , message.getRepeatedField(f("packed_sfixed64"), 0)); Assert.assertEquals(611F , message.getRepeatedField(f("packed_float" ), 0)); Assert.assertEquals(612D , message.getRepeatedField(f("packed_double" ), 0)); Assert.assertEquals(true , message.getRepeatedField(f("packed_bool" ), 0)); Assert.assertEquals(foreignBar, message.getRepeatedField(f("packed_enum" ),0)); Assert.assertEquals(701 , message.getRepeatedField(f("packed_int32" ), 1)); Assert.assertEquals(702L , message.getRepeatedField(f("packed_int64" ), 1)); Assert.assertEquals(703 , message.getRepeatedField(f("packed_uint32" ), 1)); Assert.assertEquals(704L , message.getRepeatedField(f("packed_uint64" ), 1)); Assert.assertEquals(705 , message.getRepeatedField(f("packed_sint32" ), 1)); Assert.assertEquals(706L , message.getRepeatedField(f("packed_sint64" ), 1)); Assert.assertEquals(707 , message.getRepeatedField(f("packed_fixed32" ), 1)); Assert.assertEquals(708L , message.getRepeatedField(f("packed_fixed64" ), 1)); Assert.assertEquals(709 , message.getRepeatedField(f("packed_sfixed32"), 1)); Assert.assertEquals(710L , message.getRepeatedField(f("packed_sfixed64"), 1)); Assert.assertEquals(711F , message.getRepeatedField(f("packed_float" ), 1)); Assert.assertEquals(712D , message.getRepeatedField(f("packed_double" ), 1)); Assert.assertEquals(false, message.getRepeatedField(f("packed_bool" ), 1)); Assert.assertEquals(foreignBaz, message.getRepeatedField(f("packed_enum" ),1)); } /** * Verifies that the reflection setters for the given.Builder object throw a * NullPointerException if they are passed a null value. Uses Assert to throw an * appropriate assertion failure, if the condition is not verified. */ public void assertReflectionSettersRejectNull(Message.Builder builder) throws Exception { try { builder.setField(f("optional_string"), null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } try { builder.setField(f("optional_bytes"), null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } try { builder.setField(f("optional_nested_enum"), null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } try { builder.setField(f("optional_nested_message"), (TestAllTypes.NestedMessage) null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } try { builder.setField(f("optional_nested_message"), (TestAllTypes.NestedMessage.Builder) null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } try { builder.addRepeatedField(f("repeated_string"), null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } try { builder.addRepeatedField(f("repeated_bytes"), null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } try { builder.addRepeatedField(f("repeated_nested_enum"), null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } try { builder.addRepeatedField(f("repeated_nested_message"), null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } } /** * Verifies that the reflection repeated setters for the given Builder object throw a * NullPointerException if they are passed a null value. Uses Assert to throw an appropriate * assertion failure, if the condition is not verified. */ public void assertReflectionRepeatedSettersRejectNull(Message.Builder builder) throws Exception { builder.addRepeatedField(f("repeated_string"), "one"); try { builder.setRepeatedField(f("repeated_string"), 0, null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } builder.addRepeatedField(f("repeated_bytes"), toBytes("one")); try { builder.setRepeatedField(f("repeated_bytes"), 0, null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } builder.addRepeatedField(f("repeated_nested_enum"), nestedBaz); try { builder.setRepeatedField(f("repeated_nested_enum"), 0, null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } builder.addRepeatedField( f("repeated_nested_message"), TestAllTypes.NestedMessage.newBuilder().setBb(218).build()); try { builder.setRepeatedField(f("repeated_nested_message"), 0, null); Assert.fail("Exception was not thrown"); } catch (NullPointerException e) { // We expect this exception. } } } /** * @param filePath The path relative to * {@link #getTestDataDir}. */ public static String readTextFromFile(String filePath) { return readBytesFromFile(filePath).toStringUtf8(); } private static File getTestDataDir() { // Search each parent directory looking for "src/google/protobuf". File ancestor = new File("."); try { ancestor = ancestor.getCanonicalFile(); } catch (IOException e) { throw new RuntimeException( "Couldn't get canonical name of working directory.", e); } while (ancestor != null && ancestor.exists()) { if (new File(ancestor, "src/google/protobuf").exists()) { return new File(ancestor, "src/google/protobuf/testdata"); } ancestor = ancestor.getParentFile(); } throw new RuntimeException( "Could not find golden files. This test must be run from within the " + "protobuf source package so that it can read test data files from the " + "C++ source tree."); } /** * @param filename The path relative to * {@link #getTestDataDir}. */ public static ByteString readBytesFromFile(String filename) { File fullPath = new File(getTestDataDir(), filename); try { RandomAccessFile file = new RandomAccessFile(fullPath, "r"); byte[] content = new byte[(int) file.length()]; file.readFully(content); return ByteString.copyFrom(content); } catch (IOException e) { // Throw a RuntimeException here so that we can call this function from // static initializers. throw new IllegalArgumentException( "Couldn't read file: " + fullPath.getPath(), e); } } /** * Get the bytes of the "golden message". This is a serialized TestAllTypes * with all fields set as they would be by * {@link #setAllFields(TestAllTypes.Builder)}, but it is loaded from a file * on disk rather than generated dynamically. The file is actually generated * by C++ code, so testing against it verifies compatibility with C++. */ public static ByteString getGoldenMessage() { if (goldenMessage == null) { goldenMessage = readBytesFromFile("golden_message_oneof_implemented"); } return goldenMessage; } private static ByteString goldenMessage = null; /** * Get the bytes of the "golden packed fields message". This is a serialized * TestPackedTypes with all fields set as they would be by * {@link #setPackedFields(TestPackedTypes.Builder)}, but it is loaded from a * file on disk rather than generated dynamically. The file is actually * generated by C++ code, so testing against it verifies compatibility with * C++. */ public static ByteString getGoldenPackedFieldsMessage() { if (goldenPackedFieldsMessage == null) { goldenPackedFieldsMessage = readBytesFromFile("golden_packed_fields_message"); } return goldenPackedFieldsMessage; } private static ByteString goldenPackedFieldsMessage = null; /** * Mock implementation of {@link GeneratedMessage.BuilderParent} for testing. * * @author jonp@google.com (Jon Perlow) */ public static class MockBuilderParent implements GeneratedMessage.BuilderParent { private int invalidations; //@Override (Java 1.6 override semantics, but we must support 1.5) public void markDirty() { invalidations++; } public int getInvalidationCount() { return invalidations; } } }
/* * Copyright 2011-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.stepfunctions.builder.states; import com.amazonaws.services.stepfunctions.builder.conditions.Condition; import com.amazonaws.services.stepfunctions.builder.conditions.ConditionDeserializer; import com.amazonaws.services.stepfunctions.builder.internal.Buildable; import com.amazonaws.services.stepfunctions.builder.internal.PropertyNames; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import java.io.IOException; /** * Class representing a choice rule to be included in a {@link ChoiceState}. A choice consists of a condition and a state that * the * state machine will transition to if the condition evaluates to true. * * @see <a href="https://states-language.net/spec.html#choice-state>https://states-language.net/spec.html#choice-state</a> */ public final class Choice { @JsonUnwrapped private final Condition condition; @JsonUnwrapped private final Transition transition; private Choice(Builder builder) { this.condition = builder.condition.build(); this.transition = builder.transition.build(); } /** * @return Condition for the choice rule. */ public Condition getCondition() { return condition; } /** * @return The {@link Transition} that occurs when this choice is evaluated. */ public Transition getTransition() { return transition; } /** * @return Builder instance to construct a {@link Choice}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link Choice}. */ @JsonDeserialize(using = Choice.ChoiceDeserializer.class) public final static class Builder implements Buildable<Choice> { private Condition.Builder condition = Condition.NULL_BUILDER; private Transition.Builder transition = Transition.NULL_BUILDER; private Builder() { } /** * REQUIRED. Sets the condition for this choice rule. * * @param conditionBuilder Instance of {@link com.amazonaws.services.stepfunctions.builder.conditions.Condition.Builder}. * Note that the * {@link State} object is not built until the {@link Choice} is built so any modifications on * the * state builder will be reflected in this object. * @return This object for method chaining. */ public Builder condition(Condition.Builder conditionBuilder) { this.condition = conditionBuilder; return this; } /** * Sets the name of the state that the state machine will transition to if the condition evaluates to true. * * @param nextStateName Name of the state. * @return This object for method chaining. */ @JsonProperty(PropertyNames.NEXT) private Builder nextStateName(String nextStateName) { return transition(NextStateTransition.builder().nextStateName(nextStateName)); } /** * REQUIRED. Sets the transition for this choice rule. * * @param transition Transition that occurs if the choice rule condition evaluates to true. * @return This object for method chaining. */ public Builder transition(NextStateTransition.Builder transition) { this.transition = transition; return this; } /** * @return An immutable {@link Choice} object. */ @Override public Choice build() { return new Choice(this); } } /** * Custom deserializer for {@link Choice.Builder}. */ private static class ChoiceDeserializer extends StdDeserializer<Builder> { private final ConditionDeserializer conditionDeserializer = new ConditionDeserializer(); protected ChoiceDeserializer() { super(Choice.class); } @Override public Choice.Builder deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { final JsonNode node = jsonParser.getCodec().readTree(jsonParser); return Choice.builder() .nextStateName(node.get(PropertyNames.NEXT).asText()) .condition(conditionDeserializer.deserializeCondition(node)); } } }
package JDescriptors.fr.lip6.color; import java.awt.image.ColorModel; import JDescriptors.fr.lip6.quantizer.Quantizer; public interface ColorQuantizer extends Quantizer { /** * @return the colorModel */ public ColorModel getColorModel(); /** * @param colorModel * the colorModel to set */ public void setColorModel(ColorModel colorModel); /** * the channel array of the color corresponding to the specified bin * @param b * @return */ public float[] getColorFromBin(int b); public int getBin(float[] fcol); }
/* * Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.apim.grpc.telemetry.receiver; /** * This class hold the Constants for the Telemetry Receiver component. */ public class Constants { static final String DEFAULT_RECEIVER_PORT = "9091"; static final String PORT_EVENT_SOURCE_OPTION_KEY = "port"; static final String SECONDS_KEY = "_sec"; static final String NANO_SECONDS_KEY = "_nanosec"; static final String REQUEST_HEADER_FIELDS_ATTRIBUTE = "request.headers"; static final String RESPONSE_HEADER_FIELDS_ATTRIBUTE = "response.headers"; public static final String UNKNOWN_ATTRIBUTE = "Unknown"; }
package com.coolweather.app.coolweather.model; /** * Created by cc on 2017/1/1. */ import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.coolweather.app.coolweather.db.CoolWeatherOpenHelper; import java.util.ArrayList; import java.util.List; public class CoolWeatherDB { /* * 数据库名 * */ public static final String DB_NAME = "cool_weather"; /* * 数据库版本 * */ public static final int VERSION = 1; private static CoolWeatherDB coolweatherDB; private SQLiteDatabase db; /* * 将构造方法私有化 * */ private CoolWeatherDB(Context context){ CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context, DB_NAME , null , VERSION); db = dbHelper.getWritableDatabase(); } /** * 获取CoolWeatherDB的实例。 */ public synchronized static CoolWeatherDB getInstance(Context context){ if(coolweatherDB == null){ coolweatherDB = new CoolWeatherDB(context); } return coolweatherDB; } /** * 将Province实例存储到数据库 */ public void saveProvince(Province province){ if (province != null){ ContentValues values = new ContentValues(); values.put("province_name", province.getProvinceName()); values.put("province_code", province.getProvinceCode()); db.insert("province", null, values); } } /** * 从数据库读取全国所有的省份信息 */ public List<Province> loadProvinces(){ List<Province> list = new ArrayList<Province>(); Cursor cursor = db .query("Province", null, null, null, null, null, null); if(cursor.moveToFirst()){ do{ Province province = new Province(); province.setId(cursor.getInt(cursor.getColumnIndex("id"))); province.setProvinceName(cursor.getString(cursor .getColumnIndex("province_name"))); province.setProvinceCode(cursor.getString(cursor .getColumnIndex("province_code"))); list.add(province); }while(cursor.moveToNext()); } if(cursor != null){ cursor.close(); } return list; } /* * 将City实例存储到数据库 * */ public void saveCity(City city){ if (city != null){ ContentValues values = new ContentValues(); values.put("city_name", city.getCityName()); values.put("city_code", city.getCityCode()); values.put("province_id", city.getProvinceId()); db.insert("city", null, values); } } /** * 从数据库读取某省下所有的城市信息 */ public List<City> loadCities(int provinceId){ List<City> list = new ArrayList<City>(); Cursor cursor = db.query("City", null, "province_id = ?", new String[]{String.valueOf(provinceId) }, null, null, null); if(cursor.moveToFirst()){ do{ City city = new City(); city.setId(cursor.getInt(cursor.getColumnIndex("id"))); city.setCityName(cursor.getString(cursor .getColumnIndex("city_name"))); city.setCityCode(cursor.getString(cursor .getColumnIndex("city_code"))); city.setProvinceId(provinceId); list.add(city); }while(cursor.moveToNext()); } if(cursor != null){ cursor.close(); } return list; } /** * 将County实例存储到数据库 */ public void saveCounty(County county){ if (county != null){ ContentValues values = new ContentValues(); values.put("county_name", county.getCountyName()); values.put("county_code", county.getCountyCode()); values.put("city_id", county.getCityId()); db.insert("county", null, values); } } /** * 从数据库读取某城市下所有县的信息 */ public List<County> loadCounties(int cityId){ List<County> list = new ArrayList<County>(); Cursor cursor = db.query("County", null, "city_id = ?", new String[]{String.valueOf(cityId) }, null, null, null); if(cursor.moveToFirst()){ do{ County county = new County(); county.setId(cursor.getInt(cursor.getColumnIndex("id"))); county.setCountyName(cursor.getString(cursor .getColumnIndex("county_name"))); county.setCountyCode(cursor.getString(cursor .getColumnIndex("county_code"))); county.setCityId(cityId); list.add(county); }while(cursor.moveToNext()); } if(cursor != null){ cursor.close(); } return list; } }
/***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * ------------------------------------------------------------------------- * * This software is published under the terms of the Apache Software License * * version 1.1, a copy of which has been included with this distribution in * * the LICENSE file. * *****************************************************************************/ package org.apache.cocoon.generation; import org.apache.avalon.excalibur.pool.Recyclable; import org.apache.avalon.framework.activity.Initializable; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.context.Context; import org.apache.avalon.framework.context.ContextException; import org.apache.avalon.framework.context.DefaultContext; import org.apache.avalon.framework.parameters.Parameters; import org.apache.avalon.framework.parameters.ParameterException; import org.apache.log.Logger; import org.apache.cocoon.Constants; import org.apache.cocoon.ProcessingException; import org.apache.cocoon.ResourceNotFoundException; import org.apache.cocoon.components.parser.Parser; import org.apache.cocoon.environment.Source; import org.apache.cocoon.environment.SourceResolver; import org.apache.commons.collections.ExtendedProperties; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.log.LogSystem; import org.apache.velocity.runtime.RuntimeServices; import org.apache.velocity.runtime.resource.loader.ResourceLoader; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.io.InputStream; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * <p>Cocoon {@link Generator} that produces dynamic XML SAX events * from a Velocity template file.</p> * * <h2>Sitemap Configuration</h2> * * <p> * Attributes: * <dl> * <dt>usecache (optional; default: 'false')</dt> * <dd>set to 'true' to enable template caching on the 'cocoon' * resource loader</dd> * * <dt>checkInterval (optional; default: '0')</dt> * <dd>This is the number of seconds between modification checks when * caching is turned on. When this is an integer &gt; 0, this represents * the number of seconds between checks to see if the template was * modified. If the template has been modified since last check, then * it is reloaded and reparsed. Otherwise nothing is done. When &lt;= 0, * no modification checks will take place, and assuming that the * property cache (above) is true, once a template is loaded and * parsed the first time it is used, it will not be checked or * reloaded after that until the application or servlet engine is * restarted.</dd> * </dl> * </p> * * <p> * Child Elements: * * <dl> * <dt>&lt;property key="propertyKey" value="propertyValue"/&gt; (optional; 0..n)</dt> * <dd>An additional property to pass along to the Velocity template * engine during initialization</dd> * * <dt>&lt;resource-loader name="loaderName" class="javaClassName" &gt; (optional; 0..n; children: property*)</dt> * <dd>The default configuration uses the 'cocoon' resource loader * which resolves resources via the Cocoon SourceResolver. Additional * resource loaders can be added with this configuration * element. Configuration properties for the resource loader can be * specified by adding a child property element of the resource-loader * element. The prefix '&lt;name&gt;.resource.loader.' is * automatically added to the property name.</dd> * * <dt>&lt;export-object key="objectMapKey" name="velocityContextName"/&gt; (optional; 0..n)</dt> * <dd>Export the object specified by <em>key</em> from the Cocoon * object map to the Velocity context of the template. The object can * be accessed from the template as <em>name</em>. Be careful to use a * valid VTL variable name.</dd> * </dl> * </p> * * <p> * Default Java objects exported to the Velocity context: * * <dl> * <dt>request (org.apache.cocoon.environment.Request)</dt> * <dd>The Cocoon current request</dd> * * <dt>template (java.lang.String)</dt> * <dd>The path of the template file currently being evaluated</dd> * * <dt>response (org.apache.cocoon.environment.Response)</dt> * <dd>The Cocoon response associated with the current request</dd> * * <dt>context (org.apache.cocoon.environment.Context)</dt> * <dd>The Cocoon context associated with the current request</dd> * * <dt>parameters (org.apache.avalon.framework.parameters.Parameters)</dt> * <dd>Any parameters passed to the generator in the pipeline</dd> * </dl> * </p> * * <p> Additional Java objects can be exported from the Cocoon object * map to the Velocity context by adding one or more &lt;export-object * key="objectMapKey" name="velocityContextName"/&gt; child elements * to the generator configuration in the sitemap.</p> * * @author <a href="mailto:dims@yahoo.com">Davanum Srinivas</a> * @author <a href="mailto:mike@hihat.net">Michael McKibben</a> * @version CVS $Revision: 1.2 $ $Date: 2002/01/25 03:48:30 $ */ public class VelocityGenerator extends ComposerGenerator implements Initializable, Configurable, Recyclable, LogSystem { /** * Velocity {@link org.apache.velocity.runtime.resource.loader.ResourceLoader} * implementation to load template resources using Cocoon's *{@link SourceResolver}. This class is created by the Velocity * framework via the ResourceLoaderFactory. * * @see org.apache.velocity.runtime.resource.loader.ResourceLoader */ public static class TemplateLoader extends org.apache.velocity.runtime.resource.loader.ResourceLoader { private Context resolverContext; /** * Initialize this resource loader. The 'context' property is * required and must be of type {@link Context}. The context * is used to pass the Cocoon SourceResolver for the current * pipeline. * * @param config the properties to configure this resource. * @throws IllegalArgumentException thrown if the required * 'context' property is not set. * @throws ClassCastException if the 'context' property is not * of type {@link Context}. * @see org.apache.velocity.runtime.resource.loader.ResourceLoader#init */ public void init(ExtendedProperties config) { this.resolverContext = (Context)config.get("context"); if (this.resolverContext == null) { throw new IllegalArgumentException("Runtime Cocoon resolver context not specified in resource loader configuration."); } } /** * @param systemId the path to the resource * @see org.apache.velocity.runtime.resource.loader.ResourceLoader#getResourceStream */ public InputStream getResourceStream(String systemId) throws org.apache.velocity.exception.ResourceNotFoundException { try { return resolveSource(systemId).getInputStream(); } catch (org.apache.velocity.exception.ResourceNotFoundException ex) { throw ex; } catch (Exception ex) { throw new org.apache.velocity.exception.ResourceNotFoundException("Unable to resolve source: " + ex); } } /** * @see org.apache.velocity.runtime.resource.loader.ResourceLoader#isSourceModified */ public boolean isSourceModified(org.apache.velocity.runtime.resource.Resource resource) { long lastModified = 0; try { lastModified = resolveSource(resource.getName()).getLastModified(); } catch (Exception ex) { super.rsvc.warn("Unable to determine last modified for resource: " + resource.getName() + ": " + ex); } return lastModified > 0? lastModified != resource.getLastModified() : true; } /** * @see org.apache.velocity.runtime.resource.loader.ResourceLoader#getLastModified */ public long getLastModified(org.apache.velocity.runtime.resource.Resource resource) { long lastModified = 0; try { lastModified = resolveSource(resource.getName()).getLastModified(); } catch (Exception ex) { super.rsvc.warn("Unable to determine last modified for resource: " + resource.getName() + ": " + ex); } return lastModified; } /** * Store all the Source objects we lookup via the SourceResolver so that they can be properly * recycled later. * * @param systemId the path to the resource */ private Source resolveSource(String systemId) throws org.apache.velocity.exception.ResourceNotFoundException { Map sourceCache; try { sourceCache = (Map)this.resolverContext.get(CONTEXT_SOURCE_CACHE_KEY); } catch (ContextException ignore) { throw new org.apache.velocity.exception.ResourceNotFoundException("Runtime Cocoon source cache not specified in resource loader resolver context."); } Source source = (Source)sourceCache.get(systemId); if (source == null) { try { SourceResolver resolver = (SourceResolver)this.resolverContext.get(CONTEXT_RESOLVER_KEY); source = resolver.resolve(systemId); } catch (ContextException ex) { throw new org.apache.velocity.exception.ResourceNotFoundException("No Cocoon source resolver associated with current request."); } catch (Exception ex) { throw new org.apache.velocity.exception.ResourceNotFoundException("Unable to resolve source: " + ex); } } sourceCache.put(systemId, source); return source; } } /** * Holder object for controlling Cocoon objects exported to the * Velocity Context */ private static class ObjectExport { public String key; public String name; } /** * Key to lookup the {@link SourceResolver} from the context of * the resource loader */ final private static String CONTEXT_RESOLVER_KEY = "resolver"; /** * Key to lookup the source cache {@link Map} from the context of * the resource loader */ final private static String CONTEXT_SOURCE_CACHE_KEY = "source-cache"; private List objectExports; private VelocityEngine tmplEngine; private DefaultContext resolverContext; private VelocityContext velocityContext; private boolean activeFlag; /** * Read any additional objects to export to the Velocity context * from the configuration. * * @param configuration the class configurations. * @see org.apache.avalon.framework.configuration.Configurable#configure */ public void configure(Configuration configuration) throws ConfigurationException { this.resolverContext = new DefaultContext(); this.objectExports = new ArrayList(); this.tmplEngine = new VelocityEngine(); this.tmplEngine.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, this); // First set up our default 'cocoon' resource loader // this.tmplEngine.setProperty("cocoon.resource.loader.class", TemplateLoader.class.getName()); this.tmplEngine.setProperty("cocoon.resource.loader.cache", configuration.getAttribute("usecache", "false")); this.tmplEngine.setProperty("cocoon.resource.loader.modificationCheckInterval", configuration.getAttribute("checkInterval", "0")); this.tmplEngine.setProperty("cocoon.resource.loader.context", this.resolverContext); // Read in any additional properties to pass to the VelocityEngine during initialization // Configuration[] properties = configuration.getChildren("property"); for (int i=0; i < properties.length; ++i) { Configuration c = properties[i]; String name = c.getAttribute("name"); // disallow setting of certain properties // if (name.startsWith("runtime.log") || name.indexOf(".resource.loader.") != -1) { if (getLogger().isInfoEnabled()) { getLogger().info("ignoring disallowed property '" + name + "'."); } continue; } this.tmplEngine.setProperty(name, c.getAttribute("value")); } // now read in any additional Velocity resource loaders // List resourceLoaders = new ArrayList(); Configuration[] loaders = configuration.getChildren("resource-loader"); for (int i=0; i < loaders.length; ++i) { Configuration loader = loaders[i]; String name = loader.getAttribute("name"); if (name.equals("cocoon")) { if (getLogger().isInfoEnabled()) { getLogger().info("'cocoon' resource loader already defined."); } continue; } resourceLoaders.add(name); String prefix = name + ".resource.loader."; String type = loader.getAttribute("class"); this.tmplEngine.setProperty(prefix + "class", type); Configuration [] loaderProperties = loader.getChildren("property"); for (int j=0; i < loaderProperties.length; ++j) { Configuration c = loaderProperties[j]; String propName = c.getAttribute("name"); this.tmplEngine.setProperty(prefix + propName, c.getAttribute("value")); } } // Velocity expects resource loaders as CSV list // StringBuffer buffer = new StringBuffer("cocoon"); for (Iterator it = resourceLoaders.iterator(); it.hasNext(); ) { buffer.append(','); buffer.append((String)it.next()); } tmplEngine.setProperty(Velocity.RESOURCE_LOADER, buffer.toString()); // read in additional objects to export from the object map // Configuration[] exports = configuration.getChildren("export-object"); for (int i=0; i < exports.length; ++i) { Configuration c = exports[i]; ObjectExport export = new ObjectExport(); export.key = c.getAttribute("key"); export.name = c.getAttribute("name"); this.objectExports.add(export); } } /** * @see org.apache.avalon.framework.activity.Initializable#initialize */ public void initialize() throws Exception { this.tmplEngine.init(); } /** * @see org.apache.cocoon.sitemap.SitemapModelComponent#setup */ public void setup(SourceResolver resolver, Map objectModel, String src, Parameters params) throws ProcessingException,SAXException,IOException { if (activeFlag) { throw new IllegalStateException("setup called on recyclable sitemap component before properly recycling previous state"); } super.setup(resolver, objectModel, src, params); // pass along the SourceResolver to the Velocity resource loader // this.resolverContext.put(CONTEXT_RESOLVER_KEY, resolver); this.resolverContext.put(CONTEXT_SOURCE_CACHE_KEY, new HashMap()); // Initialize the Velocity context // this.velocityContext = new VelocityContext(); this.velocityContext.put("template", src); this.velocityContext.put("request", objectModel.get(Constants.REQUEST_OBJECT)); this.velocityContext.put("response", objectModel.get(Constants.RESPONSE_OBJECT)); this.velocityContext.put("context", objectModel.get(Constants.CONTEXT_OBJECT)); this.velocityContext.put("parameters", params); // Export any additional objects to the Velocity context // for (Iterator it = this.objectExports.iterator(); it.hasNext();) { ObjectExport export = (ObjectExport)it.next(); Object object = objectModel.get(export.key); if (object != null) { this.velocityContext.put(export.name, object); if (getLogger().isDebugEnabled()) { getLogger().debug("exporting object under key '" + export.key + "' to velocity context with name '" + export.name + "'."); } } else if (getLogger().isInfoEnabled()) { getLogger().info("unable to export object under key '" + export.key + "' to velocity context."); } } this.activeFlag = true; } /** * Free up the VelocityContext associated with the pipeline, and * release any Source objects resolved by the resource loader. * * @see org.apache.avalon.excalibur.pool.Recyclable#recycle */ public void recycle() { this.activeFlag = false; // recycle all the Source objects resolved/used by our resource loader // try { Map sourceCache = (Map)this.resolverContext.get(CONTEXT_SOURCE_CACHE_KEY); for (Iterator it = sourceCache.values().iterator(); it.hasNext();) { ((Source)it.next()).recycle(); } } catch (ContextException ignore) { } this.velocityContext = null; super.recycle(); } /** * Generate XML data using Velocity template. * * @see org.apache.cocoon.generation.Generator#generate */ public void generate() throws IOException, SAXException, ProcessingException { // Guard against calling generate before setup. if (!activeFlag) { throw new IllegalStateException("generate called on sitemap component before setup."); } Parser parser = null; try { parser = (Parser)this.manager.lookup(Parser.ROLE); if (getLogger().isDebugEnabled()) { getLogger().debug("Processing File: " + super.source); } /* lets render a template */ StringWriter w = new StringWriter(); this.tmplEngine.mergeTemplate(super.source, velocityContext, w); InputSource xmlInput = new InputSource(new StringReader(w.toString())); parser.setConsumer(this.xmlConsumer); parser.parse(xmlInput); } catch (IOException e) { getLogger().warn("VelocityGenerator.generate()", e); throw new ResourceNotFoundException("Could not get Resource for VelocityGenerator", e); } catch (SAXException e) { getLogger().error("VelocityGenerator.generate()", e); throw e; } catch (ComponentException e) { getLogger().error("Could not get parser", e); throw new ProcessingException("Exception in VelocityGenerator.generate()", e); } catch (ProcessingException e) { throw e; } catch (Exception e) { getLogger().error("Could not get parser", e); throw new ProcessingException("Exception in VelocityGenerator.generate()", e); } finally { if (parser != null) { this.manager.release(parser); } } } /** * This implementation does nothing. * * @see org.apache.velocity.runtime.log.LogSystem#init */ public void init(RuntimeServices rs) throws Exception { } /** * Pass along Velocity log messages to our configured logger. * * @see org.apache.velocity.runtime.log.LogSystem#logVelocityMessage */ public void logVelocityMessage(int level, String message) { Logger logger = getLogger(); switch (level) { case LogSystem.WARN_ID: logger.warn(message); break; case LogSystem.INFO_ID: logger.info(message); break; case LogSystem.DEBUG_ID: logger.debug(message); break; case LogSystem.ERROR_ID: logger.error(message); break; default: logger.info(message); break; } } }
package ie.kyle.memorygame; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v8/enums/optimization_goal_type.proto package com.google.ads.googleads.v8.enums; /** * <pre> * Container for enum describing the type of optimization goal. * </pre> * * Protobuf type {@code google.ads.googleads.v8.enums.OptimizationGoalTypeEnum} */ public final class OptimizationGoalTypeEnum extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v8.enums.OptimizationGoalTypeEnum) OptimizationGoalTypeEnumOrBuilder { private static final long serialVersionUID = 0L; // Use OptimizationGoalTypeEnum.newBuilder() to construct. private OptimizationGoalTypeEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private OptimizationGoalTypeEnum() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new OptimizationGoalTypeEnum(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private OptimizationGoalTypeEnum( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v8.enums.OptimizationGoalTypeProto.internal_static_google_ads_googleads_v8_enums_OptimizationGoalTypeEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v8.enums.OptimizationGoalTypeProto.internal_static_google_ads_googleads_v8_enums_OptimizationGoalTypeEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum.class, com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum.Builder.class); } /** * <pre> * The type of optimization goal * </pre> * * Protobuf enum {@code google.ads.googleads.v8.enums.OptimizationGoalTypeEnum.OptimizationGoalType} */ public enum OptimizationGoalType implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ UNSPECIFIED(0), /** * <pre> * Used as a return value only. Represents value unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ UNKNOWN(1), /** * <pre> * Optimize for call clicks. Call click conversions are times people * selected 'Call' to contact a store after viewing an ad. * </pre> * * <code>CALL_CLICKS = 2;</code> */ CALL_CLICKS(2), /** * <pre> * Optimize for driving directions. Driving directions conversions are * times people selected 'Get directions' to navigate to a store after * viewing an ad. * </pre> * * <code>DRIVING_DIRECTIONS = 3;</code> */ DRIVING_DIRECTIONS(3), UNRECOGNIZED(-1), ; /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ public static final int UNSPECIFIED_VALUE = 0; /** * <pre> * Used as a return value only. Represents value unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ public static final int UNKNOWN_VALUE = 1; /** * <pre> * Optimize for call clicks. Call click conversions are times people * selected 'Call' to contact a store after viewing an ad. * </pre> * * <code>CALL_CLICKS = 2;</code> */ public static final int CALL_CLICKS_VALUE = 2; /** * <pre> * Optimize for driving directions. Driving directions conversions are * times people selected 'Get directions' to navigate to a store after * viewing an ad. * </pre> * * <code>DRIVING_DIRECTIONS = 3;</code> */ public static final int DRIVING_DIRECTIONS_VALUE = 3; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static OptimizationGoalType valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static OptimizationGoalType forNumber(int value) { switch (value) { case 0: return UNSPECIFIED; case 1: return UNKNOWN; case 2: return CALL_CLICKS; case 3: return DRIVING_DIRECTIONS; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<OptimizationGoalType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< OptimizationGoalType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<OptimizationGoalType>() { public OptimizationGoalType findValueByNumber(int number) { return OptimizationGoalType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum.getDescriptor().getEnumTypes().get(0); } private static final OptimizationGoalType[] VALUES = values(); public static OptimizationGoalType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private OptimizationGoalType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.ads.googleads.v8.enums.OptimizationGoalTypeEnum.OptimizationGoalType) } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum)) { return super.equals(obj); } com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum other = (com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Container for enum describing the type of optimization goal. * </pre> * * Protobuf type {@code google.ads.googleads.v8.enums.OptimizationGoalTypeEnum} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v8.enums.OptimizationGoalTypeEnum) com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnumOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v8.enums.OptimizationGoalTypeProto.internal_static_google_ads_googleads_v8_enums_OptimizationGoalTypeEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v8.enums.OptimizationGoalTypeProto.internal_static_google_ads_googleads_v8_enums_OptimizationGoalTypeEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum.class, com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum.Builder.class); } // Construct using com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v8.enums.OptimizationGoalTypeProto.internal_static_google_ads_googleads_v8_enums_OptimizationGoalTypeEnum_descriptor; } @java.lang.Override public com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum getDefaultInstanceForType() { return com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum build() { com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum buildPartial() { com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum result = new com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum) { return mergeFrom((com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum other) { if (other == com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v8.enums.OptimizationGoalTypeEnum) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v8.enums.OptimizationGoalTypeEnum) private static final com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum(); } public static com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<OptimizationGoalTypeEnum> PARSER = new com.google.protobuf.AbstractParser<OptimizationGoalTypeEnum>() { @java.lang.Override public OptimizationGoalTypeEnum parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new OptimizationGoalTypeEnum(input, extensionRegistry); } }; public static com.google.protobuf.Parser<OptimizationGoalTypeEnum> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<OptimizationGoalTypeEnum> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v8.enums.OptimizationGoalTypeEnum getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
package com.noseparte.battle.server; import com.noseparte.battle.BattleServerConfig; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @author Noseparte * @date 2019/8/21 16:52 * @Description */ @Slf4j @Component public class BattleServer { Object waitLock = new Object(); private static EventLoopGroup boss = new NioEventLoopGroup(); private static EventLoopGroup work = new NioEventLoopGroup(); private static ServerBootstrap server = new ServerBootstrap(); @Autowired BattleServerInitializer battleServerInitializer; @Autowired BattleServerConfig battleServerConfig; public void start() { synchronized (waitLock) { int port = battleServerConfig.getPort(); try { server.group(boss, work); server.channel(NioServerSocketChannel.class); server.childHandler(battleServerInitializer); log.info("匹配服务器在[{}]端口启动监听", port); ChannelFuture future = server.bind(port); future.channel().closeFuture().sync(); } catch (InterruptedException e) { log.error("[出现异常] 释放资源", e); }finally { boss.shutdownGracefully(); work.shutdownGracefully(); } } } public void close(){ synchronized (waitLock) { log.info("关闭服务器...."); //优雅退出 boss.shutdownGracefully(); work.shutdownGracefully(); } } }
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.repositoryservices.localrepository.repositorycontentmanager; import org.odpi.openmetadata.repositoryservices.events.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.odpi.openmetadata.repositoryservices.auditlog.OMRSAuditCode; import org.odpi.openmetadata.repositoryservices.auditlog.OMRSAuditLog; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.OMRSMetadataCollection; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.InstanceStatus; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.InstanceType; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.typedefs.*; import org.odpi.openmetadata.repositoryservices.eventmanagement.*; import org.odpi.openmetadata.repositoryservices.ffdc.OMRSErrorCode; import org.odpi.openmetadata.repositoryservices.ffdc.exception.*; import org.odpi.openmetadata.repositoryservices.localrepository.repositoryconnector.LocalOMRSRepositoryConnector; import org.odpi.openmetadata.repositoryservices.rest.server.OMRSRepositoryRESTServices; import java.util.*; /** * OMRSRepositoryContentManager supports an in-memory cache of TypeDefs for the local server. It is used by the OMRS * components for constructing metadata instances with valid types. It ensures that the TypeDefs used in other * members of the open metadata repository cohorts that the local server is also a member of are consistent with the * local repository. * * OMRSRepositoryContentManager plays a central role in ensuring the integrity of the metadata in the local repository. * It is called from multiple components at different points in the processing. It presents a different interface * to each of these components that is specialized to their needs. * <ul> * <li> * OMRSTypeDefEventProcessor: processes inbound events from remote members of the open metadata * repository cohorts that the local repository is connected to. These incoming TypeDef events need to * be validated against the types used locally and either saved or discarded depending on the exchange rule * setting. * </li> * <li> * OMRSTypeDefManager: provides maintenance methods for managing the TypeDefs in the local cache. * </li> * </ul> */ public class OMRSRepositoryContentManager extends OMRSTypeDefEventProcessor implements OMRSTypeDefManager { private LocalOMRSRepositoryConnector localRepositoryConnector = null; private String localServerName = null; private OMRSRepositoryEventManager outboundRepositoryEventManager = null; private String openTypesOriginGUID = null; private Map<String, TypeDef> knownTypeDefGUIDs = new HashMap<>(); private Map<String, TypeDef> knownTypeDefNames = new HashMap<>(); private Map<String, AttributeTypeDef> knownAttributeTypeDefGUIDs = new HashMap<>(); private Map<String, AttributeTypeDef> knownAttributeTypeDefNames = new HashMap<>(); private Map<String, TypeDef> activeTypeDefGUIDs = new HashMap<>(); private Map<String, TypeDef> activeTypeDefNames = new HashMap<>(); private Map<String, AttributeTypeDef> activeAttributeTypeDefGUIDs = new HashMap<>(); private Map<String, AttributeTypeDef> activeAttributeTypeDefNames = new HashMap<>(); private Map<String, List<TypeDefLink>> typeDefSuperTypes = new HashMap<>(); private Map<String, InstanceType> knownInstanceTypes = new HashMap<>(); private Map<String, String> metadataCollectionNames = new HashMap<>(); /* * The audit log provides a verifiable record of the open metadata archives that have been loaded into * the open metadata repository. The Logger is for standard debug. */ private OMRSAuditLog auditLog; private static final Logger log = LoggerFactory.getLogger(OMRSRepositoryContentManager.class); /** * Default constructor * * @param auditLog audit log for this component. */ public OMRSRepositoryContentManager(OMRSAuditLog auditLog) { this.auditLog = auditLog; } /** * Saves all of the information necessary to process incoming TypeDef events. * * @param localRepositoryConnector connector to the local repository * @param outboundRepositoryEventManager event manager to call for outbound events used to send out reports * of conflicting TypeDefs */ public void setupEventProcessor(LocalOMRSRepositoryConnector localRepositoryConnector, OMRSRepositoryEventManager outboundRepositoryEventManager) { if (localRepositoryConnector != null) { this.localRepositoryConnector = localRepositoryConnector; this.localServerName = localRepositoryConnector.getLocalServerName(); } this.outboundRepositoryEventManager = outboundRepositoryEventManager; } /** * Save the unique identifier of the open metadata archive. This is stored in the origin property of * all of the open metadata types. It is needed to support the isOpenType() method. * * @param openMetadataTypesGUID unique identifier for the open metadata type's archive */ public void setOpenMetadataTypesOriginGUID(String openMetadataTypesGUID) { openTypesOriginGUID = openMetadataTypesGUID; } /* * ======================== * OMRSTypeDefManager */ /** * Cache a definition of a new TypeDef. This method assumes the TypeDef has been successfully added to the * local repository already and all that is needed is to maintain the cached list of types * * @param sourceName source of the request (used for logging) * @param newTypeDef TypeDef structure describing the new TypeDef. */ public void addTypeDef(String sourceName, TypeDef newTypeDef) { this.cacheTypeDef(sourceName, newTypeDef,true); } /** * Cache a definition of a TypeDef. * * @param sourceName source of the request (used for logging) * @param newTypeDef TypeDef structure describing the new TypeDef. * @param isLocallySupported indicates whether the TypeDef is supported by the local repository. */ private void cacheTypeDef(String sourceName, TypeDef newTypeDef, boolean isLocallySupported) { if (this.validTypeDef(sourceName, newTypeDef)) { knownTypeDefGUIDs.put(newTypeDef.getGUID(), newTypeDef); knownTypeDefNames.put(newTypeDef.getName(), newTypeDef); if (isLocallySupported) { activeTypeDefGUIDs.put(newTypeDef.getGUID(), newTypeDef); activeTypeDefNames.put(newTypeDef.getName(), newTypeDef); log.debug("New Active Type " + newTypeDef.getName() + " from " + sourceName + ". Full TypeDef: " + newTypeDef); } else { log.debug("New Known Type " + newTypeDef.getName() + " from " + sourceName + ". Full TypeDef: " + newTypeDef); } } } /** * Cache a definition of a new AttributeTypeDef. * * @param sourceName source of the request (used for logging) * @param newAttributeTypeDef AttributeTypeDef structure describing the new TypeDef. */ public void addAttributeTypeDef(String sourceName, AttributeTypeDef newAttributeTypeDef) { this.cacheAttributeTypeDef(sourceName, newAttributeTypeDef, true); } /** * Cache a definition of a new AttributeTypeDef. * * @param sourceName source of the request (used for logging) * @param newAttributeTypeDef AttributeTypeDef structure describing the new TypeDef. * @param isLocallySupported indicates whether the TypeDef is supported by the local repository. */ private void cacheAttributeTypeDef(String sourceName, AttributeTypeDef newAttributeTypeDef, boolean isLocallySupported) { if (this.validAttributeTypeDef(sourceName, newAttributeTypeDef)) { knownAttributeTypeDefGUIDs.put(newAttributeTypeDef.getGUID(), newAttributeTypeDef); knownAttributeTypeDefNames.put(newAttributeTypeDef.getName(), newAttributeTypeDef); if (isLocallySupported) { activeAttributeTypeDefGUIDs.put(newAttributeTypeDef.getGUID(), newAttributeTypeDef); activeAttributeTypeDefNames.put(newAttributeTypeDef.getName(), newAttributeTypeDef); if (log.isDebugEnabled()) { log.debug("New Active Attribute Type " + newAttributeTypeDef.getName() + " from " + sourceName+ ". Full AttributeTypeDef: " + newAttributeTypeDef); } else { log.debug("New Known Attribute Type " + newAttributeTypeDef.getName() + " from " + sourceName+ ". Full AttributeTypeDef: " + newAttributeTypeDef); } } } } /** * Update one or more properties of a cached TypeDef. This method assumes the TypeDef has been successfully * updated in the local repository already and all that is needed is to maintain the cached list of types * * @param sourceName source of the request (used for logging) * @param typeDef TypeDef structure. */ public void updateTypeDef(String sourceName, TypeDef typeDef) { if (this.validTypeDef(sourceName, typeDef)) { knownTypeDefGUIDs.put(typeDef.getGUID(), typeDef); knownTypeDefNames.put(typeDef.getName(), typeDef); if (localRepositoryConnector != null) { activeTypeDefGUIDs.put(typeDef.getGUID(), typeDef); activeTypeDefNames.put(typeDef.getName(), typeDef); log.debug("Updated Active Type " + typeDef.getName() + " from " + sourceName + ". Full TypeDef: " + typeDef); } } } /** * Delete a cached TypeDef. * * @param sourceName source of the request (used for logging) * @param obsoleteTypeDefGUID String unique identifier for the TypeDef. * @param obsoleteTypeDefName String unique name for the TypeDef. */ public void deleteTypeDef(String sourceName, String obsoleteTypeDefGUID, String obsoleteTypeDefName) { if (this.validTypeId(sourceName, obsoleteTypeDefGUID, obsoleteTypeDefName)) { knownTypeDefGUIDs.remove(obsoleteTypeDefGUID); knownTypeDefNames.remove(obsoleteTypeDefName); if (localRepositoryConnector != null) { activeTypeDefGUIDs.remove(obsoleteTypeDefGUID); activeTypeDefNames.remove(obsoleteTypeDefName); log.debug("Deleted Active TypeDef " + obsoleteTypeDefName + " from " + sourceName); } } } /** * Delete a cached AttributeTypeDef. * * @param sourceName source of the request (used for logging) * @param obsoleteAttributeTypeDefGUID String unique identifier for the AttributeTypeDef. * @param obsoleteAttributeTypeDefName String unique name for the AttributeTypeDef. */ public void deleteAttributeTypeDef(String sourceName, String obsoleteAttributeTypeDefGUID, String obsoleteAttributeTypeDefName) { if (this.validTypeId(sourceName, obsoleteAttributeTypeDefGUID, obsoleteAttributeTypeDefName)) { knownAttributeTypeDefGUIDs.remove(obsoleteAttributeTypeDefGUID); knownAttributeTypeDefNames.remove(obsoleteAttributeTypeDefName); if (localRepositoryConnector != null) { activeAttributeTypeDefGUIDs.remove(obsoleteAttributeTypeDefGUID); activeAttributeTypeDefNames.remove(obsoleteAttributeTypeDefName); if (log.isDebugEnabled()) { log.debug("Deleted Active AttributeTypeDef " + obsoleteAttributeTypeDefName + " from " + sourceName); } } } } /** * Change the identifiers for a TypeDef. * * @param sourceName source of the request (used for logging). * @param originalTypeDefGUID TypeDef's original unique identifier. * @param originalTypeDefName TypeDef's original unique name. * @param newTypeDef updated TypeDef with new identifiers. */ public void reIdentifyTypeDef(String sourceName, String originalTypeDefGUID, String originalTypeDefName, TypeDef newTypeDef) { this.deleteTypeDef(sourceName, originalTypeDefGUID, originalTypeDefName); this.addTypeDef(sourceName, newTypeDef); } /** * Change the identifiers for an AttributeTypeDef. * * @param sourceName source of the request (used for logging). * @param originalAttributeTypeDefGUID AttributeTypeDef's original unique identifier. * @param originalAttributeTypeDefName AttributeTypeDef's original unique name. * @param newAttributeTypeDef updated AttributeTypeDef with new identifiers */ public void reIdentifyAttributeTypeDef(String sourceName, String originalAttributeTypeDefGUID, String originalAttributeTypeDefName, AttributeTypeDef newAttributeTypeDef) { this.deleteAttributeTypeDef(sourceName, originalAttributeTypeDefGUID, originalAttributeTypeDefName); this.addAttributeTypeDef(sourceName, newAttributeTypeDef); } /** * Return the list of property names defined for this TypeDef. * * @param sourceName source of the request (used for logging) * @param typeDef type definition to work with. * @return list of String property names * @throws TypeErrorException there is an issue with the TypeDef. */ private List<String> getPropertyNames(String sourceName, TypeDef typeDef) throws TypeErrorException { final String methodName = "getPropertyNames"; List<String> propertyNames = null; if (validTypeDef(sourceName, typeDef)) { List<TypeDefAttribute> propertiesDefinition = typeDef.getPropertiesDefinition(); if ((propertiesDefinition != null) && (propertiesDefinition.size() > 0)) { propertyNames = new ArrayList<>(); for (TypeDefAttribute propertyDefinition : propertiesDefinition) { if (propertyDefinition != null) { String propertyName = propertyDefinition.getAttributeName(); if (propertyName != null) { log.debug(typeDef.getName() + " from " + sourceName + " has property " + propertyName); propertyNames.add(propertyName); } else { OMRSErrorCode errorCode = OMRSErrorCode.BAD_TYPEDEF_ATTRIBUTE_NAME; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(sourceName); throw new TypeErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } } else { OMRSErrorCode errorCode = OMRSErrorCode.NULL_TYPEDEF_ATTRIBUTE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(sourceName); throw new TypeErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } } /* * If no property names have been extracted then remove the array. */ if (propertyNames.size() == 0) { propertyNames = null; } } } else { OMRSErrorCode errorCode = OMRSErrorCode.BAD_TYPEDEF; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(sourceName); throw new TypeErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return propertyNames; } /** * Evaluate the superTypes for a type. The results are cached in typeDefSuperTypes. * * @param sourceName source of the request (used for logging) * @param typeName name of type to process * @param methodName calling method * @return list of supertype links or null if top level */ private List<TypeDefLink> getSuperTypes(String sourceName, String typeName, String methodName) { final String thisMethodName = "getSuperTypes"; List<TypeDefLink> typeHierarchy = typeDefSuperTypes.get(typeName); if (typeHierarchy == null) { /* * The type hierarchy is not known at this time (it is evaluated lazily). */ typeHierarchy = new ArrayList<>(); TypeDef typeDef = knownTypeDefNames.get(typeName); if (typeDef != null) { TypeDefLink superTypeLink = typeDef.getSuperType(); while (superTypeLink != null) { String superTypeName = superTypeLink.getName(); if (superTypeName != null) { log.debug(typeName + " has super type " + superTypeName); typeHierarchy.add(superTypeLink); /* * Retrieve the TypeDef for this super type */ TypeDef superTypeDef = knownTypeDefNames.get(superTypeName); if (superTypeDef != null) { /* * Retrieve the super type for this super typeDef. It will be null if the type is top-level. */ superTypeLink = superTypeDef.getSuperType(); } else { log.error(superTypeName + " supertype is not known in TypeDef cache"); throwContentManagerLogicError(sourceName, methodName, thisMethodName); } } else { log.error("Corrupted TypeDef cache, no name for " + superTypeLink.toString()); throwContentManagerLogicError(sourceName, methodName, thisMethodName); } } /* * Cache the resulting superType list */ typeDefSuperTypes.put(typeName, typeHierarchy); } else { log.error(typeName + " type is not known in TypeDef cache"); throwContentManagerLogicError(sourceName, methodName, thisMethodName); } } if (typeHierarchy.isEmpty()) { /* * The type hierarchy has been evaluated and this type has no supertypes. */ return null; } else { /* * The type hierarchy is known and can be returned directly. */ return typeHierarchy; } } /** * Validate that the type of an entity is of the expected/desired type. The actual entity may be a subtype * of the expected type of course. * * @param sourceName source of the request (used for logging) * @param actualTypeName name of the entity type * @param expectedTypeName name of the expected type * @return boolean if they match (a null in either results in false) */ public boolean isTypeOf(String sourceName, String actualTypeName, String expectedTypeName) { final String methodName = "isTypeOf"; log.debug("IsTypeOf: sourceName = " + sourceName + "; actualTypeName = " + actualTypeName + "; expectedTypeName = " + expectedTypeName); if ((expectedTypeName != null) && (actualTypeName != null)) { /* * Do the obvious first. */ if (actualTypeName.equals(expectedTypeName)) { log.debug("Simple match success"); return true; } /* * Looking for a match in the superTypes. */ List<TypeDefLink> typeHierarchy = this.getSuperTypes(sourceName, actualTypeName, methodName); if (typeHierarchy != null) { for (TypeDefLink superType : typeHierarchy) { if (superType != null) { if (expectedTypeName.equals(superType.getName())) { log.debug("SuperType match success"); return true; } log.debug("No match with " + superType.getName()); } } } } return false; } /** * Validate that the type of an entity is of the expected/desired type. The actual entity may be a subtype * of the expected type of course. * * @param sourceName source of the request (used for logging) * @param actualTypeGUID GUID of the entity type * @param actualTypeName name of the entity type * @param expectedTypeGUID GUID of the expected type * @return boolean if they match (a null in either results in false) */ boolean isTypeOfByGUID(String sourceName, String actualTypeGUID, String actualTypeName, String expectedTypeGUID) { final String methodName = "isTypeOfByGUID"; log.debug("IsTypeOfByGUID: sourceName = " + sourceName + "; actualTypeName = " + actualTypeName + "; expectedTypeGUID = " + expectedTypeGUID); if ((expectedTypeGUID != null) && (actualTypeGUID != null)) { /* * Do the obvious first. */ if (actualTypeGUID.equals(expectedTypeGUID)) { log.debug("Simple match success"); return true; } /* * Looking for a match in the superTypes. */ List<TypeDefLink> typeHierarchy = this.getSuperTypes(sourceName, actualTypeName, methodName); if (typeHierarchy != null) { for (TypeDefLink superType : typeHierarchy) { if (superType != null) { if (expectedTypeGUID.equals(superType.getGUID())) { log.debug("SuperType match success"); return true; } log.debug("No match with " + superType.getGUID()); } } } } return false; } /** * Return the InstanceType that matches the supplied type name. If the type name is not recognized, * of the category is incorrect, a logic exception is thrown. * * @param sourceName source of the request (used for logging) * @param category category of the instance type required. * @param typeName String type name. * @param methodName name of calling method. * @return InstanceType object containing TypeDef properties such as unique identifier (guid), * typeDef name and version name * @throws TypeErrorException the type name is not a recognized type or is of the wrong category or there is * a problem with the cached TypeDef. */ public InstanceType getInstanceType(String sourceName, TypeDefCategory category, String typeName, String methodName) throws TypeErrorException { final String thisMethodName = "getInstanceType"; if (isValidTypeCategory(sourceName, category, typeName, methodName)) { InstanceType instanceType = knownInstanceTypes.get(typeName); if (instanceType != null) { return instanceType; } /* * The instance type has not yet been created. (They are created lazily.) */ TypeDef typeDef = knownTypeDefNames.get(typeName); if (typeDef != null) { instanceType = new InstanceType(); instanceType.setTypeDefCategory(category); instanceType.setTypeDefGUID(typeDef.getGUID()); instanceType.setTypeDefName(typeDef.getName()); instanceType.setTypeDefVersion(typeDef.getVersion()); instanceType.setTypeDefDescription(typeDef.getDescription()); instanceType.setTypeDefDescriptionGUID(typeDef.getDescriptionGUID()); instanceType.setTypeDefSuperTypes(this.getSuperTypes(sourceName, typeName, methodName)); /* * Extract the properties for this TypeDef. These will be augmented with property names * from the super type(s). */ List<String> propertyNames = this.getPropertyNames(sourceName, typeDef); /* * If propertyNames is null, it means this TypeDef has no attributes. However the superType * may have attributes and so we need an array to accumulate the attributes into. */ if (propertyNames == null) { propertyNames = new ArrayList<>(); } /* * Work up the TypeDef hierarchy extracting the property names. */ TypeDefLink superTypeLink = typeDef.getSuperType(); while (superTypeLink != null) { String superTypeName = superTypeLink.getName(); if (superTypeName != null) { log.debug(typeName + " from " + sourceName + " has super type " + superTypeName); /* * Retrieve the TypeDef for this super type */ TypeDef superTypeDef = knownTypeDefNames.get(superTypeName); if (superTypeDef != null) { List<String> superTypePropertyNames = this.getPropertyNames(sourceName, superTypeDef); if (superTypePropertyNames != null) { propertyNames.addAll(0, superTypePropertyNames); } /* * Retrieve the super type for this typeDef. It will be null if the type is top-level. */ superTypeLink = superTypeDef.getSuperType(); } else { /* * Super type not known so stop processing */ log.error(superTypeName + " is not known"); throwContentManagerLogicError(sourceName, methodName, thisMethodName); } } else { /* * Super type is invalid, suggests a corrupted cache */ log.error("Corrupted TypeDef cache"); throwContentManagerLogicError(sourceName, methodName, thisMethodName); } } /* * Make sure an empty list is converted to null */ if (propertyNames.size() > 0) { instanceType.setValidInstanceProperties(propertyNames); } /* * Cache the instance type for next time */ knownInstanceTypes.put(typeName, instanceType); return instanceType; } else { log.error("TypeDef " + typeName + " should already have been validated"); throwContentManagerLogicError(sourceName, methodName, thisMethodName); } } else { OMRSErrorCode errorCode = OMRSErrorCode.BAD_CATEGORY_FOR_TYPEDEF_ATTRIBUTE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(sourceName, typeName, category.getName()); throw new TypeErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return null; } /** * Return a boolean indicating that the type name matches the category. * * @param sourceName source of the request (used for logging) * @param category TypeDefCategory enum value to test * @param typeName type name to test * @return boolean flag indicating that the type name is of the specified category * @throws TypeErrorException the type name is not a recognized type or there is * a problem with the cached TypeDef. */ public boolean isValidTypeCategory(String sourceName, TypeDefCategory category, String typeName, String methodName) throws TypeErrorException { final String thisMethodName = "isValidTypeCategory"; if (category == null) { throwContentManagerLogicError(sourceName, methodName, thisMethodName); return false; } if (typeName == null) { throwContentManagerLogicError(sourceName, methodName, thisMethodName); return false; } TypeDef typeDef = knownTypeDefNames.get(typeName); if (typeDef != null) { TypeDefCategory retrievedTypeDefCategory = typeDef.getCategory(); if (retrievedTypeDefCategory != null) { return (category.getOrdinal() == retrievedTypeDefCategory.getOrdinal()); } else { throwContentManagerLogicError(sourceName, methodName, thisMethodName); } } else { OMRSErrorCode errorCode = OMRSErrorCode.TYPEDEF_NOT_KNOWN_FOR_INSTANCE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(typeName, category.getName(), methodName, sourceName); throw new TypeErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return false; } /** * Return boolean indicating if a classification type can be applied to a specified entity. This * uses the list of valid entity types located in the ClassificationDef. * * @param sourceName source of the request (used for logging) * @param classificationTypeName name of the classification's type (ClassificationDef) * @param entityTypeName name of the entity's type (EntityDef) * @param methodName name of calling method. * @return boolean indicating if the classification is valid for the entity. */ public boolean isValidClassificationForEntity(String sourceName, String classificationTypeName, String entityTypeName, String methodName) { final String thisMethodName = "isValidClassificationForEntity"; try { if ((isValidTypeCategory(sourceName, TypeDefCategory.CLASSIFICATION_DEF, classificationTypeName, methodName)) && (isValidTypeCategory(sourceName, TypeDefCategory.ENTITY_DEF, entityTypeName, methodName))) { ClassificationDef classificationTypeDef = (ClassificationDef) knownTypeDefNames.get(classificationTypeName); if (classificationTypeDef != null) { List<TypeDefLink> entityDefs = classificationTypeDef.getValidEntityDefs(); if (entityDefs == null) { /* * The classification has no restrictions on which entities it can be attached to. */ return true; } else { /* * The classification can only be attached to the entities listed. Note an empty list * means the classification can not be attached to any entity and it is effectively useless. * The logic checks the entity types parent types, as the parent types may allow the classification. * * The Archive types at this time do not have any ClassificationDefs with supertypes. If we want to support * ClassificationDefs with supertypes then we need to account for any entities that the ClassificationDef * supertype can introduce. */ Set<String> entityTypes = new HashSet<>(); TypeDef typeDef = getTypeDefByName(thisMethodName,entityTypeName); entityTypes.add(entityTypeName); while ( typeDef.getSuperType() !=null) { TypeDefLink superTypeLink=typeDef.getSuperType(); String parentName= superTypeLink.getName(); entityTypes.add(parentName); typeDef = this.knownTypeDefGUIDs.get(superTypeLink.getGUID()); } for (TypeDefLink allowedEntityDefLink : entityDefs) { if (allowedEntityDefLink != null) { String allowedTypeName = allowedEntityDefLink.getName(); if (entityTypes.contains(allowedTypeName)) { return true; } } } return false; } } else { throwContentManagerLogicError(sourceName, methodName, thisMethodName); return false; } } else { return false; } } catch (TypeErrorException | ClassCastException typeError) { throwContentManagerLogicError(sourceName, methodName, thisMethodName); return false; } } /** * Return the requested type. * * @param sourceName source of the request (used for logging) * @param typeName name of the type * @param thisMethodName name of calling method. * @param originalMethodName name of original calling method. * @return list of InstanceStatus enums * @throws TypeErrorException the type name is not recognized. */ private TypeDef getTypeDefFromCache(String sourceName, String typeName, String thisMethodName, String originalMethodName) throws TypeErrorException { if (typeName == null) { this.throwContentManagerLogicError(sourceName, thisMethodName, originalMethodName); } TypeDef typeDef = knownTypeDefNames.get(typeName); if (typeDef == null) { OMRSErrorCode errorCode = OMRSErrorCode.TYPEDEF_NAME_NOT_KNOWN; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(typeName, originalMethodName, sourceName); throw new TypeErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), originalMethodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return typeDef; } /** * Return the list of valid InstanceStatus states that instances of this type can handle. * * @param sourceName source of the request (used for logging) * @param typeName name of the type * @param methodName name of calling method. * @return list of InstanceStatus enums * @throws TypeErrorException the type name is not recognized. */ public List<InstanceStatus> getValidStatusList(String sourceName, String typeName, String methodName) throws TypeErrorException { final String thisMethodName = "validStatusList"; TypeDef typeDef = this.getTypeDefFromCache(sourceName, typeName, thisMethodName, methodName); return typeDef.getValidInstanceStatusList(); } /** * Return the initial status value to use for an instance of the supplied type. * * @param sourceName source of the request (used for logging) * @param typeName name of the type to extract the initial status from. * @param methodName calling method * @return InstanceStatus enum * @throws TypeErrorException the type name is not recognized. */ public InstanceStatus getInitialStatus(String sourceName, String typeName, String methodName) throws TypeErrorException { final String thisMethodName = "getInitialStatus"; TypeDef typeDef = this.getTypeDefFromCache(sourceName, typeName, thisMethodName, methodName); return typeDef.getInitialStatus(); } /** * Return the URL string to use for direct access to the metadata instance. * * @param sourceName source of the request (used for logging) * @param guid unique identifier for the instance. * @return String URL with placeholder for variables such as userId. */ public String getEntityURL(String sourceName, String guid) { return OMRSRepositoryRESTServices.getEntityURL(localServerName, guid); } /** * Return the URL string to use for direct access to the metadata instance. * * @param sourceName source of the request (used for logging) * @param guid unique identifier for the instance. * @return String URL with placeholder for variables such as userId. */ public String getRelationshipURL(String sourceName, String guid) { return OMRSRepositoryRESTServices.getRelationshipURL(localServerName, guid); } /** * Return the list of typedefs known by the local repository. * * @return TypeDef gallery */ public TypeDefGallery getActiveTypeDefGallery() { TypeDefGallery typeDefGallery = new TypeDefGallery(); if (! activeAttributeTypeDefNames.isEmpty()) { typeDefGallery.setAttributeTypeDefs(new ArrayList<>(activeAttributeTypeDefNames.values())); } if (! activeTypeDefNames.isEmpty()) { typeDefGallery.setTypeDefs(new ArrayList<>(activeTypeDefNames.values())); } return typeDefGallery; } /** * Return the list of typedefs known by the local repository. * * @return TypeDef gallery */ public TypeDefGallery getKnownTypeDefGallery() { TypeDefGallery typeDefGallery = new TypeDefGallery(); if (! knownAttributeTypeDefNames.isEmpty()) { typeDefGallery.setAttributeTypeDefs(new ArrayList<>(knownAttributeTypeDefNames.values())); } if (! knownTypeDefNames.isEmpty()) { typeDefGallery.setTypeDefs(new ArrayList<>(knownTypeDefNames.values())); } return typeDefGallery; } /** * Return the TypeDef identified by the name supplied by the caller. This is used in the connectors when * validating the actual types of the repository with the known open metadata types. It is looking specifically * for types of the same name but with different content. * * @param sourceName source of the request (used for logging) * @param typeDefName unique name for the TypeDef * @return TypeDef object or null if TypeDef is not known. */ public TypeDef getTypeDefByName (String sourceName, String typeDefName) { return knownTypeDefNames.get(typeDefName); } /** * Return the AttributeTypeDef identified by the name supplied by the caller. This is used in the connectors when * validating the actual types of the repository with the known open metadata types. It is looking specifically * for types of the same name but with different content. * * @param sourceName source of the request (used for logging) * @param attributeTypeDefName unique name for the TypeDef * @return AttributeTypeDef object or null if AttributeTypeDef is not known. */ public AttributeTypeDef getAttributeTypeDefByName (String sourceName, String attributeTypeDefName) { return knownAttributeTypeDefNames.get(attributeTypeDefName); } /** * Return the TypeDefs identified by the name supplied by the caller. The TypeDef name may have wild * card characters in it which is why the results are returned in a list. * * @param sourceName source of the request (used for logging) * @param typeDefName unique name for the TypeDef * @return TypeDef object or null if TypeDef is not known. */ public TypeDefGallery getActiveTypesByWildCardName (String sourceName, String typeDefName) { if (typeDefName != null) { Collection<TypeDef> typeDefs = activeTypeDefNames.values(); List<TypeDef> matchedTypeDefs = new ArrayList<>(); for (TypeDef typeDef : typeDefs) { if (typeDef != null) { if (typeDef.getName().matches(typeDefName)) { matchedTypeDefs.add(typeDef); } } } Collection<AttributeTypeDef> attributeTypeDefs = activeAttributeTypeDefNames.values(); List<AttributeTypeDef> matchedAttributeTypeDefs = new ArrayList<>(); for (AttributeTypeDef attributeTypeDef : attributeTypeDefs) { if (attributeTypeDef != null) { if (attributeTypeDef.getName().matches(typeDefName)) { matchedAttributeTypeDefs.add(attributeTypeDef); } } } if ((! matchedTypeDefs.isEmpty()) || (! matchedAttributeTypeDefs.isEmpty())) { TypeDefGallery typeDefGallery = new TypeDefGallery(); if (! matchedTypeDefs.isEmpty()) { typeDefGallery.setTypeDefs(matchedTypeDefs); } else { typeDefGallery.setTypeDefs(null); } if (! matchedAttributeTypeDefs.isEmpty()) { typeDefGallery.setAttributeTypeDefs(matchedAttributeTypeDefs); } else { typeDefGallery.setAttributeTypeDefs(null); } return typeDefGallery; } } return null; } /** * Return the TypeDef identified by the guid supplied by the caller. This call is used when * retrieving a type that only the guid is known. * * @param sourceName source of the request (used for logging) * @param guidParameterName name of parameter that supplied the GUID * @param typeDefGUID unique identifier for the TypeDef * @param methodName calling method * @return TypeDef object * @throws TypeErrorException unknown or invalid type */ public TypeDef getTypeDef (String sourceName, String guidParameterName, String typeDefGUID, String methodName) throws TypeErrorException { final String thisMethodName = "getTypeDef"; if (typeDefGUID != null) { TypeDef typeDef = knownTypeDefGUIDs.get(typeDefGUID); if (typeDef == null) { OMRSErrorCode errorCode = OMRSErrorCode.TYPEDEF_ID_NOT_KNOWN; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(typeDefGUID, guidParameterName, methodName, sourceName); throw new TypeErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return typeDef; } throwContentManagerLogicError(sourceName, methodName, thisMethodName); return null; } /** * Return the AttributeTypeDef identified by the guid and name supplied by the caller. This call is used when * retrieving a type that only the guid is known. * * @param sourceName source of the request (used for logging) * @param attributeTypeDefGUID unique identifier for the AttributeTypeDef * @param methodName calling method * @return TypeDef object * @throws TypeErrorException unknown or invalid type */ public AttributeTypeDef getAttributeTypeDef (String sourceName, String attributeTypeDefGUID, String methodName) throws TypeErrorException { final String thisMethodName = "getAttributeTypeDef"; if (attributeTypeDefGUID != null) { AttributeTypeDef attributeTypeDef = knownAttributeTypeDefGUIDs.get(attributeTypeDefGUID); if (attributeTypeDef == null) { OMRSErrorCode errorCode = OMRSErrorCode.BAD_TYPEDEF; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(sourceName); throw new TypeErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return attributeTypeDef; } throwContentManagerLogicError(sourceName, methodName, thisMethodName); return null; } /** * Return the TypeDef identified by the guid and name supplied by the caller. This call is used when * retrieving a type that should exist. For example, retrieving the type of a metadata instance. * * @param sourceName source of the request (used for logging) * @param guidParameterName name of parameter that supplied the GUID * @param nameParameterName name of parameter that supplied the name * @param typeDefGUID unique identifier for the TypeDef * @param typeDefName unique name for the TypeDef * @param methodName calling method * @return TypeDef object or null if the * @throws TypeErrorException invalid type */ public TypeDef getTypeDef (String sourceName, String guidParameterName, String nameParameterName, String typeDefGUID, String typeDefName, String methodName) throws TypeErrorException { if (validTypeId(sourceName, typeDefGUID, typeDefName)) { return knownTypeDefNames.get(typeDefName); } else { OMRSErrorCode errorCode = OMRSErrorCode.BAD_TYPEDEF; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(sourceName); throw new TypeErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } } /** * Return the AttributeTypeDef identified by the guid and name supplied by the caller. This call is used when * retrieving a type that should exist. For example, retrieving the type definition of a metadata instance's * property. * * @param sourceName source of the request (used for logging) * @param attributeTypeDefGUID unique identifier for the AttributeTypeDef * @param attributeTypeDefName unique name for the AttributeTypeDef * @param methodName calling method * @return TypeDef object * @throws TypeErrorException unknown or invalid type */ public AttributeTypeDef getAttributeTypeDef (String sourceName, String attributeTypeDefGUID, String attributeTypeDefName, String methodName) throws TypeErrorException { if (validTypeId(sourceName, attributeTypeDefGUID, attributeTypeDefName)) { return knownAttributeTypeDefNames.get(attributeTypeDefName); } else { OMRSErrorCode errorCode = OMRSErrorCode.BAD_TYPEDEF; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(sourceName); throw new TypeErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } } /** * Return the names of all of the properties in the supplied TypeDef and all of its super-types. * * @param sourceName name of caller. * @param typeDef TypeDef to query. * @param methodName calling method. * @return list of property definitions. */ public List<TypeDefAttribute> getAllPropertiesForTypeDef(String sourceName, TypeDef typeDef, String methodName) { final String thisMethodName = "getAllPropertiesForTypeDef"; if (typeDef == null) { throwContentManagerLogicError(sourceName, methodName, thisMethodName); } List<TypeDefAttribute> propertiesDefinition = typeDef.getPropertiesDefinition(); /* * If propertiesDefinition is null, it means the TypeDef has no properties defined. However the superType * may have properties defined and so we need an array to accumulate the property definitions into. */ if (propertiesDefinition == null) { propertiesDefinition = new ArrayList<>(); } /* * Work up the TypeDef hierarchy extracting the property definitions. */ TypeDefLink superTypeLink = typeDef.getSuperType(); while (superTypeLink != null) { TypeDef superTypeDef = this.knownTypeDefGUIDs.get(superTypeLink.getGUID()); List<TypeDefAttribute> superTypePropertiesDefinition = superTypeDef.getPropertiesDefinition(); if (superTypePropertiesDefinition != null) { propertiesDefinition.addAll(superTypePropertiesDefinition); } superTypeLink = superTypeDef.getSuperType(); } return propertiesDefinition; } /** * Return a boolean flag indicating whether the list of TypeDefs passed are compatible with the * all known typedefs. * * A valid TypeDef is one that matches name, GUID and version to the full list of TypeDefs. * If a new TypeDef is present, it is added to the enterprise list. * * @param sourceName source of the TypeDef (used for logging) * @param typeDefs list of TypeDefs. * @param methodName name of calling method * @throws RepositoryErrorException a conflicting or invalid TypeDef has been returned */ public void validateEnterpriseTypeDefs(String sourceName, List<TypeDef> typeDefs, String methodName) throws RepositoryErrorException { for (TypeDef typeDef : typeDefs) { if (validTypeId(sourceName, typeDef.getGUID(), typeDef.getName())) { if (!isKnownType(sourceName, typeDef.getGUID(), typeDef.getName())) { knownTypeDefNames.put(typeDef.getName(), typeDef); } } else { OMRSErrorCode errorCode = OMRSErrorCode.CONFLICTING_ENTERPRISE_TYPEDEFS; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } } } /** * Return a boolean flag indicating whether the list of TypeDefs passed are compatible with the * all known typedefs. * * A valid TypeDef is one that matches name, GUID and version to the full list of TypeDefs. * If a new TypeDef is present, it is added to the enterprise list. * * @param sourceName source of the TypeDef (used for logging) * @param attributeTypeDefs list of AttributeTypeDefs. * @param methodName name of calling method * @throws RepositoryErrorException a conflicting or invalid AttributeTypeDef has been returned */ public void validateEnterpriseAttributeTypeDefs(String sourceName, List<AttributeTypeDef> attributeTypeDefs, String methodName) throws RepositoryErrorException { for (AttributeTypeDef attributeTypeDef : attributeTypeDefs) { if (validTypeId(sourceName, attributeTypeDef.getGUID(), attributeTypeDef.getName())) { if (!isKnownType(sourceName, attributeTypeDef.getGUID(), attributeTypeDef.getName())) { knownAttributeTypeDefNames.put(attributeTypeDef.getName(), attributeTypeDef); } } else { OMRSErrorCode errorCode = OMRSErrorCode.CONFLICTING_ENTERPRISE_TYPEDEFS; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } } } /** * Return boolean indicating whether the TypeDef is one of the standard open metadata types. * * @param sourceName source of the TypeDef (used for logging) * @param typeGUID unique identifier of the type * @param typeName unique name of the type * @return boolean result */ public boolean isOpenType(String sourceName, String typeGUID, String typeName) { if (validTypeId(sourceName, typeGUID, typeName)) { TypeDef typeDef = knownTypeDefNames.get(typeName); if (typeDef == null) { return false; } if (openTypesOriginGUID != null) { if (openTypesOriginGUID.equals(typeDef.getOrigin())) { log.debug("TypeDef " + typeName + " (GUID = " + typeGUID + ") from " + sourceName + " is an open type"); return true; } else { log.debug("TypeDef " + typeName + " (GUID = " + typeGUID + ") from " + sourceName + " is NOT an open type"); } } } return false; } /** * Return boolean indicating whether the TypeDef is one of the standard open metadata types. * * @param sourceName source of the request (used for logging) * @param typeGUID unique identifier of the type * @return boolean result */ public boolean isOpenTypeId(String sourceName, String typeGUID) { if (typeGUID != null) { TypeDef typeDef = knownTypeDefGUIDs.get(typeGUID); if (typeDef != null) { String originGUID = typeDef.getOrigin(); if (originGUID != null) { if (originGUID.equals(openTypesOriginGUID)) { return true; } } } } return false; } /** * Return boolean indicating whether the (AttributeTypeDef/TypeDef is known, either as an open type, or one defined * by one or more of the members of the cohort. * * @param sourceName source of the TypeDef (used for logging) * @param typeGUID unique identifier of the type * @param typeName unique name of the type * @return boolean result */ public boolean isKnownType(String sourceName, String typeGUID, String typeName) { if (this.validTypeId(sourceName, typeGUID, typeName)) { TypeDef typeDef = knownTypeDefNames.get(typeName); if (typeDef == null) { AttributeTypeDef attributeTypeDef = knownAttributeTypeDefNames.get(typeName); if (attributeTypeDef == null) { log.debug("Unknown (Attribute)TypeDef " + typeName + " (GUID = " + typeGUID + ") from " + sourceName); return false; } else { log.debug("Known AttributeTypeDef " + typeName + " (GUID = " + typeGUID + ") from " + sourceName); return true; } } else { log.debug("Known TypeDef " + typeName + " (GUID = " + typeGUID + ") from " + sourceName); return true; } } else { log.error("Invalid TypeDef from " + sourceName + " so can not validate known type"); return false; } } /** * Return boolean indicating whether the TypeDef/AttributeTypeDef is known, either as an open type, or one defined * by one or more of the members of the cohort. * * @param sourceName source of the request (used for logging) * @param typeGUID unique identifier of the type * @return boolean result */ public boolean isKnownTypeId(String sourceName, String typeGUID) { if (typeGUID != null) { if (knownTypeDefGUIDs.get(typeGUID) != null) { return true; } if (knownAttributeTypeDefGUIDs.get(typeGUID) != null) { return true; } } return false; } /** * Return boolean indicating whether the TypeDef is in use in the repository. * * @param sourceName source of the TypeDef (used for logging) * @param typeGUID unique identifier of the type * @param typeName unique name of the type * @return boolean result */ public boolean isActiveType(String sourceName, String typeGUID, String typeName) { if (this.validTypeId(sourceName, typeGUID, typeName)) { TypeDef typeDef = activeTypeDefNames.get(typeName); if (typeDef == null) { AttributeTypeDef attributeTypeDef = activeAttributeTypeDefNames.get(typeName); if (attributeTypeDef == null) { log.debug("Inactive (Attribute)TypeDef " + typeName + " (GUID = " + typeGUID + ") from " + sourceName); return false; } else { log.debug("Active AttributeTypeDef " + typeName + " (GUID = " + typeGUID + ") from " + sourceName); return true; } } else { log.debug("Active TypeDef " + typeName + " (GUID = " + typeGUID + ") from " + sourceName); return true; } } else { log.error("Invalid TypeDef from " + sourceName + " so can not validate active type"); return false; } } /** * Return boolean indicating whether the TypeDef/AttributeTypeDef is in use in the local repository. * * @param sourceName source of the request (used for logging) * @param typeGUID unique identifier of the type * @return boolean result */ public boolean isActiveTypeId(String sourceName, String typeGUID) { if (typeGUID != null) { if (activeTypeDefGUIDs.get(typeGUID) != null) { return true; } if (activeAttributeTypeDefGUIDs.get(typeGUID) != null) { return true; } } return false; } /** * Return boolean indicating whether the (Attribute)TypeDef identifiers are valid or not. * * @param sourceName source of the TypeDef (used for logging) * @param typeGUID unique identifier of the TypeDef * @param typeName unique name of the TypeDef * @return boolean result */ public boolean validTypeId(String sourceName, String typeGUID, String typeName) { if (typeName == null) { /* * A null TypeDef name is invalid */ log.error("Null TypeDef Name from " + sourceName); return false; } if (typeGUID == null) { /* * A null guid is invalid */ log.error("Null TypeDef GUID from " + sourceName); return false; } TypeDef typeDef = knownTypeDefNames.get(typeName); if (typeDef == null) { /* * This TypeDef is unknown so see if it is an AttributeTypeDef */ AttributeTypeDef attributeTypeDef = knownAttributeTypeDefNames.get(typeName); if (attributeTypeDef == null) { log.debug("Unknown (Attribute)TypeDef from " + sourceName); } else { if (!typeGUID.equals(attributeTypeDef.getGUID())) { /* * The requested guid does not equal the stored one. */ log.error("GUID Mismatch in AttributeTypeDef " + typeName + " from " + sourceName + " received GUID is " + typeGUID + "; stored GUID is " + attributeTypeDef.getGUID()); return false; } log.debug("Valid AttributeTypeDef from " + sourceName); return true; } log.debug("Valid AttributeTypeDef from " + sourceName); return true; } if (! typeGUID.equals(typeDef.getGUID())) { /* * The requested guid does not equal the stored one. */ log.error("GUID Mismatch in TypeDef " + typeName + " from " + sourceName + " received GUID is " + typeGUID + "; stored GUID is " + typeDef.getGUID()); return false; } return true; } /** * Return boolean indicating whether the TypeDef identifiers are valid or not. * * @param sourceName source of the TypeDef (used for logging) * @param typeDefGUID unique identifier of the TypeDef * @param typeDefName unique name of the TypeDef * @param category category of TypeDef * @return boolean result */ public boolean validTypeDefId(String sourceName, String typeDefGUID, String typeDefName, TypeDefCategory category) { if (! validTypeId(sourceName, typeDefGUID, typeDefName)) { return false; } TypeDef typeDef = knownTypeDefNames.get(typeDefName); if (typeDef != null) { TypeDefCategory knownTypeDefCategory = typeDef.getCategory(); if (knownTypeDefCategory == null) { log.error("Unknown TypeDef Category for " + typeDefName + " (GUID = " + typeDefGUID + ") from " + sourceName); return false; } if (category.getOrdinal() != knownTypeDefCategory.getOrdinal()) { log.error("TypeDef category mismatch for TypeDef " + typeDefName + " (GUID = " + typeDefGUID + ") from " + sourceName + " received version number is " + category.getDescription() + " and stored category is " + knownTypeDefCategory.getDescription()); return false; } } return true; } /** * Return boolean indicating whether the AttributeTypeDef identifiers are from a single known type or not. * * @param sourceName source of the request (used for logging) * @param attributeTypeDefGUID unique identifier of the AttributeTypeDef * @param attributeTypeDefName unique name of the AttributeTypeDef * @param category category for the AttributeTypeDef * @return boolean result */ public boolean validAttributeTypeDefId(String sourceName, String attributeTypeDefGUID, String attributeTypeDefName, AttributeTypeDefCategory category) { if (! validTypeId(sourceName, attributeTypeDefGUID, attributeTypeDefName)) { return false; } AttributeTypeDef attributeTypeDef = knownAttributeTypeDefNames.get(attributeTypeDefName); if (attributeTypeDef != null) { AttributeTypeDefCategory knownAttributeTypeDefCategory = attributeTypeDef.getCategory(); if (knownAttributeTypeDefCategory == null) { log.error("Unknown AttributeTypeDef Category for " + attributeTypeDefName + " (GUID = " + attributeTypeDefGUID + ") from " + sourceName); return false; } if (category.getOrdinal() != knownAttributeTypeDefCategory.getOrdinal()) { log.error("TypeDef category mismatch for TypeDef " + attributeTypeDefName + " (GUID = " + attributeTypeDefGUID + ") from " + sourceName + " received version number is " + category.getDescription() + " and stored category is " + knownAttributeTypeDefCategory.getDescription()); return false; } } return true; } /** * Return boolean indicating whether the TypeDef identifiers are valid or not. * * @param sourceName source of the TypeDef (used for logging) * @param typeDefGUID unique identifier of the TypeDef * @param typeDefName unique name of the TypeDef * @param typeDefVersion version of the type * @param typeDefCategory category of the instance described by this TypeDef. * @return boolean result */ public boolean validTypeDefId(String sourceName, String typeDefGUID, String typeDefName, long typeDefVersion, TypeDefCategory typeDefCategory) { if (! validTypeDefId(sourceName, typeDefGUID, typeDefName, typeDefCategory)) { return false; } TypeDef typeDef = knownTypeDefNames.get(typeDefName); if (typeDef == null) { log.debug("Unknown TypeDef " + typeDefName + " (GUID = " + typeDefGUID + ") from " + sourceName); return true; } if (typeDef.getVersion() != typeDefVersion) { log.error("Version mismatch for TypeDef " + typeDefName + " (GUID = " + typeDefGUID + ") from " + sourceName + " received version number is " + Long.toString(typeDefVersion) + " and stored version is " + Long.toString(typeDef.getVersion())); return false; } return true; } /** * Return boolean indicating whether the TypeDef identifiers are from a single known type or not. * * @param sourceName source of the request (used for logging) * @param attributeTypeDefGUID unique identifier of the TypeDef * @param attributeTypeDefName unique name of the TypeDef * @param attributeTypeDefVersion version of the type * @param category category for the TypeDef * @return boolean result */ public boolean validAttributeTypeDefId(String sourceName, String attributeTypeDefGUID, String attributeTypeDefName, long attributeTypeDefVersion, AttributeTypeDefCategory category) { if (! validAttributeTypeDefId(sourceName, attributeTypeDefGUID, attributeTypeDefName, category)) { return false; } TypeDef typeDef = knownTypeDefNames.get(attributeTypeDefName); if (typeDef == null) { log.debug("Unknown TypeDef " + attributeTypeDefName + " (GUID = " + attributeTypeDefGUID + ") from " + sourceName); return true; } if (typeDef.getVersion() != attributeTypeDefVersion) { log.error("Version mismatch for TypeDef " + attributeTypeDefName + " (GUID = " + attributeTypeDefGUID + ") from " + sourceName + " received version number is " + Long.toString(attributeTypeDefVersion) + " and stored version is " + Long.toString(typeDef.getVersion())); return false; } return true; } /** * Return boolean indicating whether the supplied TypeDef is valid or not. * * @param sourceName source of the TypeDef (used for logging) * @param typeDef TypeDef to test * @return boolean result */ public boolean validTypeDef(String sourceName, TypeDef typeDef) { if (typeDef == null) { log.error("Null typeDef from " + sourceName); return false; } if (validTypeDefId(sourceName, typeDef.getGUID(), typeDef.getName(), typeDef.getVersion(), typeDef.getCategory())) { log.debug("Good typeDef from " + sourceName); return true; } else { log.error("Bad typeDef from " + sourceName); return false; } } /** * Return boolean indicating whether the supplied AttributeTypeDef is valid or not. * * @param sourceName source of the request (used for logging) * @param attributeTypeDef TypeDef to test * @return boolean result */ public boolean validAttributeTypeDef(String sourceName, AttributeTypeDef attributeTypeDef) { if (attributeTypeDef == null) { log.error("Null attributeTypeDef from " + sourceName); return false; } if (validAttributeTypeDefId(sourceName, attributeTypeDef.getGUID(), attributeTypeDef.getName(), attributeTypeDef.getCategory())) { log.debug("Good attributeTypeDef from " + sourceName); return true; } else { log.error("Bad attributeTypeDef from " + sourceName); return false; } } /** * Return boolean indicating whether the supplied TypeDefSummary is valid or not. * * @param sourceName source of the TypeDefSummary (used for logging) * @param typeDefSummary TypeDefSummary to test. * @return boolean result. */ public boolean validTypeDefSummary(String sourceName, TypeDefSummary typeDefSummary) { if (typeDefSummary != null) { if (validTypeDefId(sourceName, typeDefSummary.getGUID(), typeDefSummary.getName(), typeDefSummary.getVersion(), typeDefSummary.getCategory())) { return true; } else { log.error("Bad typeDefSummary from " + sourceName); } } log.error("Null typeDefSummary from " + sourceName); return false; } /* * =========================== * OMRSTypeDefEventProcessor */ /** * Process incoming TypeDefEvent based on its type. * * @param cohortName source of the event (cohort name) * @param typeDefEvent event to process */ public void sendTypeDefEvent(String cohortName, OMRSTypeDefEvent typeDefEvent) { OMRSTypeDefEventType typeDefEventType = typeDefEvent.getTypeDefEventType(); OMRSEventOriginator typeDefEventOriginator = typeDefEvent.getEventOriginator(); if ((typeDefEventType != null) && (typeDefEventOriginator != null)) { switch (typeDefEventType) { case NEW_TYPEDEF_EVENT: this.processNewTypeDefEvent(cohortName, typeDefEventOriginator.getMetadataCollectionId(), typeDefEventOriginator.getServerName(), typeDefEventOriginator.getServerType(), typeDefEventOriginator.getOrganizationName(), typeDefEvent.getTypeDef()); break; case NEW_ATTRIBUTE_TYPEDEF_EVENT: this.processNewAttributeTypeDefEvent(cohortName, typeDefEventOriginator.getMetadataCollectionId(), typeDefEventOriginator.getServerName(), typeDefEventOriginator.getServerType(), typeDefEventOriginator.getOrganizationName(), typeDefEvent.getAttributeTypeDef()); break; case UPDATED_TYPEDEF_EVENT: this.processUpdatedTypeDefEvent(cohortName, typeDefEventOriginator.getMetadataCollectionId(), typeDefEventOriginator.getServerName(), typeDefEventOriginator.getServerType(), typeDefEventOriginator.getOrganizationName(), typeDefEvent.getTypeDefPatch()); break; case DELETED_TYPEDEF_EVENT: this.processDeletedTypeDefEvent(cohortName, typeDefEventOriginator.getMetadataCollectionId(), typeDefEventOriginator.getServerName(), typeDefEventOriginator.getServerType(), typeDefEventOriginator.getOrganizationName(), typeDefEvent.getTypeDefGUID(), typeDefEvent.getTypeDefName()); break; case DELETED_ATTRIBUTE_TYPEDEF_EVENT: this.processDeletedAttributeTypeDefEvent(cohortName, typeDefEventOriginator.getMetadataCollectionId(), typeDefEventOriginator.getServerName(), typeDefEventOriginator.getServerType(), typeDefEventOriginator.getOrganizationName(), typeDefEvent.getTypeDefGUID(), typeDefEvent.getTypeDefName()); break; case RE_IDENTIFIED_TYPEDEF_EVENT: this.processReIdentifiedTypeDefEvent(cohortName, typeDefEventOriginator.getMetadataCollectionId(), typeDefEventOriginator.getServerName(), typeDefEventOriginator.getServerType(), typeDefEventOriginator.getOrganizationName(), typeDefEvent.getOriginalTypeDefSummary(), typeDefEvent.getTypeDef()); break; case RE_IDENTIFIED_ATTRIBUTE_TYPEDEF_EVENT: this.processReIdentifiedAttributeTypeDefEvent(cohortName, typeDefEventOriginator.getMetadataCollectionId(), typeDefEventOriginator.getServerName(), typeDefEventOriginator.getServerType(), typeDefEventOriginator.getOrganizationName(), typeDefEvent.getOriginalAttributeTypeDef(), typeDefEvent.getAttributeTypeDef()); case TYPEDEF_ERROR_EVENT: OMRSTypeDefEventErrorCode errorCode = typeDefEvent.getErrorCode(); if (errorCode != null) { switch(errorCode) { case CONFLICTING_TYPEDEFS: this.processTypeDefConflictEvent(cohortName, typeDefEventOriginator.getMetadataCollectionId(), typeDefEventOriginator.getServerName(), typeDefEventOriginator.getServerType(), typeDefEventOriginator.getOrganizationName(), typeDefEvent.getOriginalTypeDefSummary(), typeDefEvent.getOtherMetadataCollectionId(), typeDefEvent.getOtherTypeDefSummary(), typeDefEvent.getErrorMessage()); break; case CONFLICTING_ATTRIBUTE_TYPEDEFS: this.processAttributeTypeDefConflictEvent(cohortName, typeDefEventOriginator.getMetadataCollectionId(), typeDefEventOriginator.getServerName(), typeDefEventOriginator.getServerType(), typeDefEventOriginator.getOrganizationName(), typeDefEvent.getOriginalAttributeTypeDef(), typeDefEvent.getOtherMetadataCollectionId(), typeDefEvent.getOtherAttributeTypeDef(), typeDefEvent.getErrorMessage()); case TYPEDEF_PATCH_MISMATCH: this.processTypeDefPatchMismatchEvent(cohortName, typeDefEventOriginator.getMetadataCollectionId(), typeDefEventOriginator.getServerName(), typeDefEventOriginator.getServerType(), typeDefEventOriginator.getOrganizationName(), typeDefEvent.getTargetMetadataCollectionId(), typeDefEvent.getTargetTypeDefSummary(), typeDefEvent.getOtherTypeDef(), typeDefEvent.getErrorMessage()); break; default: log.debug("Unknown TypeDef event error code; ignoring event"); break; } } else { log.debug("Ignored TypeDef event; null error code"); } break; default: log.debug("Ignored TypeDef event; unknown type"); break; } } } /** * A new TypeDef has been defined either in an archive, or in another member of the cohort. * * This new TypeDef can be added to the repository if it does not clash with an existing typeDef and the local * repository supports dynamic type definitions. * * @param sourceName name of the source of the event. It may be the cohort name for incoming events or the * local repository, or event mapper name. * @param originatorMetadataCollectionId unique identifier for the metadata collection hosted by the server that * sent the event. * @param originatorServerName name of the server that the event came from. * @param originatorServerType type of server that the event came from. * @param originatorOrganizationName name of the organization that owns the server that sent the event. * @param typeDef details of the new TypeDef */ public void processNewTypeDefEvent(String sourceName, String originatorMetadataCollectionId, String originatorServerName, String originatorServerType, String originatorOrganizationName, TypeDef typeDef) { final String actionDescription = "Process New TypeDef Event"; OMRSMetadataCollection metadataCollection = null; try { if (localRepositoryConnector != null) { metadataCollection = localRepositoryConnector.getMetadataCollection(); } if (metadataCollection != null) { /* * VerifyTypeDef returns true if the typeDef is known and matches the supplied definition. * It returns false if the type is supportable but has not yet been defined. * It throws TypeDefNotSupportedException if the typeDef is not supported and can not * be dynamically defined by the local repository. */ if (!metadataCollection.verifyTypeDef(sourceName, typeDef)) { metadataCollection.addTypeDef(sourceName, typeDef); OMRSAuditCode auditCode = OMRSAuditCode.NEW_TYPE_ADDED; auditLog.logRecord(actionDescription, auditCode.getLogMessageId(), auditCode.getSeverity(), auditCode.getFormattedLogMessage(typeDef.getName(), typeDef.getGUID(), Long.toString(typeDef.getVersion()), sourceName), null, auditCode.getSystemAction(), auditCode.getUserAction()); } /* * Either the repository already supports the type, or it has just added it. * Cache information about the type in the repository content manager's maps. */ this.cacheTypeDef(sourceName, typeDef, true); } else { /* * No local repository so just cache for enterprise repository services. */ this.cacheTypeDef(sourceName, typeDef, false); } } catch (TypeDefNotSupportedException fixedTypeSystemResponse) { /* * Adds information about the type to the repository content manager for * use by the enterprise repository services (but not local repository). */ this.cacheTypeDef(sourceName, typeDef, false); OMRSAuditCode auditCode = OMRSAuditCode.NEW_TYPE_NOT_SUPPORTED; auditLog.logRecord(actionDescription, auditCode.getLogMessageId(), auditCode.getSeverity(), auditCode.getFormattedLogMessage(typeDef.getName(), typeDef.getGUID(), Long.toString(typeDef.getVersion())), null, auditCode.getSystemAction(), auditCode.getUserAction()); log.debug("TypeDef not added because repository does not support dynamic type definitions: " + typeDef); log.debug("TypeDefNotSupportedException:", fixedTypeSystemResponse); } catch (RepositoryErrorException error) { /* * Adds information about the type to the repository content manager for * use by the enterprise repository services (but not local repository). */ this.cacheTypeDef(sourceName, typeDef, false); log.error("TypeDef " + typeDef.getName() + " not added because repository is not available: " + typeDef); log.error("RepositoryErrorException:", error); } catch (TypeDefConflictException error) { // TODO log an error to say that the TypeDef conflicts with a TypeDef already stored. log.error("TypeDef not added because it conflicts with another TypeDef already in the repository: " + typeDef); log.error("TypeDefConflictException:", error); outboundRepositoryEventManager.processTypeDefConflictEvent(sourceName, localRepositoryConnector.getMetadataCollectionId(), localRepositoryConnector.getLocalServerName(), localRepositoryConnector.getLocalServerType(), localRepositoryConnector.getOrganizationName(), typeDef, originatorMetadataCollectionId, knownTypeDefNames.get(typeDef.getName()), null); } catch (InvalidTypeDefException error) { // TODO log an error to say that the TypeDef contains bad values. log.error("TypeDef not added because repository thinks it is invalid: " + typeDef); log.error("InvalidTypeDefException: ", error); } catch (TypeDefKnownException error) { // TODO log an error to say that a logic error has occurred log.error("TypeDef not added because repository has a logic error: " + typeDef); log.error("TypeDefKnownException: ", error); } catch (Throwable error) { // TODO log an error to say that an unexpected error has occurred log.error("TypeDef not added because repository has an unexpected error: " + typeDef); log.error("Throwable: ", error); } } /** * A new AttributeTypeDef has been defined in an open metadata repository. * * @param sourceName name of the source of the event. It may be the cohort name for incoming events or the * local repository, or event mapper name. * @param originatorMetadataCollectionId unique identifier for the metadata collection hosted by the server that * sent the event. * @param originatorServerName name of the server that the event came from. * @param originatorServerType type of server that the event came from. * @param originatorOrganizationName name of the organization that owns the server that sent the event. * @param attributeTypeDef details of the new AttributeTypeDef. */ public void processNewAttributeTypeDefEvent(String sourceName, String originatorMetadataCollectionId, String originatorServerName, String originatorServerType, String originatorOrganizationName, AttributeTypeDef attributeTypeDef) { final String actionDescription = "Process New TypeDef Event"; OMRSMetadataCollection metadataCollection = null; try { if (localRepositoryConnector != null) { metadataCollection = localRepositoryConnector.getMetadataCollection(); } if (metadataCollection != null) { /* * VerifyTypeDef returns true if the typeDef is known and matches the supplied definition. * It returns false if the type is supportable but has not yet been defined. * It throws TypeDefNotSupportedException if the typeDef is not supported and can not * be dynamically defined by the local repository. */ if (!metadataCollection.verifyAttributeTypeDef(sourceName, attributeTypeDef)) { metadataCollection.addAttributeTypeDef(sourceName, attributeTypeDef); /* * Update the active TypeDefs as this new TypeDef has been accepted by the local repository. */ activeAttributeTypeDefNames.put(attributeTypeDef.getName(), attributeTypeDef); OMRSAuditCode auditCode = OMRSAuditCode.NEW_TYPE_ADDED; auditLog.logRecord(actionDescription, auditCode.getLogMessageId(), auditCode.getSeverity(), auditCode.getFormattedLogMessage(attributeTypeDef.getName(), attributeTypeDef.getGUID(), Long.toString(attributeTypeDef.getVersion()), sourceName), null, auditCode.getSystemAction(), auditCode.getUserAction()); } /* * Either the repository already supports the type, or it has just added it. * Cache information about the type in the repository content manager's maps. */ this.cacheAttributeTypeDef(sourceName, attributeTypeDef, true); } else { /* * No local repository so just cache for enterprise repository services. */ this.cacheAttributeTypeDef(sourceName, attributeTypeDef, false); } } catch (TypeDefNotSupportedException fixedTypeSystemResponse) { /* * Adds information about the type to the repository content manager for * use by the enterprise repository services (but not local repository). */ this.cacheAttributeTypeDef(sourceName, attributeTypeDef, false); OMRSAuditCode auditCode = OMRSAuditCode.NEW_TYPE_NOT_SUPPORTED; auditLog.logRecord(actionDescription, auditCode.getLogMessageId(), auditCode.getSeverity(), auditCode.getFormattedLogMessage(attributeTypeDef.getName(), attributeTypeDef.getGUID(), Long.toString(attributeTypeDef.getVersion())), null, auditCode.getSystemAction(), auditCode.getUserAction()); log.debug("TypeDef not added because repository does not support dynamic type definitions: " + attributeTypeDef); log.debug("TypeDefNotSupportedException:", fixedTypeSystemResponse); } catch (RepositoryErrorException error) { /* * Adds information about the type to the repository content manager for * use by the enterprise repository services (but not local repository). */ this.cacheAttributeTypeDef(sourceName, attributeTypeDef, false); log.error("TypeDef " + attributeTypeDef.getName() + " not added because repository is not available: " + attributeTypeDef); log.error("RepositoryErrorException:", error); } catch (TypeDefConflictException error) { // TODO log an error to say that the TypeDef conflicts with a TypeDef already stored. log.error("TypeDef not added because it conflicts with another TypeDef already in the repository: " + attributeTypeDef); log.error("TypeDefConflictException:", error); outboundRepositoryEventManager.processAttributeTypeDefConflictEvent(sourceName, localRepositoryConnector.getMetadataCollectionId(), localRepositoryConnector.getLocalServerName(), localRepositoryConnector.getLocalServerType(), localRepositoryConnector.getOrganizationName(), attributeTypeDef, originatorMetadataCollectionId, knownAttributeTypeDefNames.get( attributeTypeDef.getName()), null); } catch (InvalidTypeDefException error) { // TODO log an error to say that the TypeDef contains bad values. log.error("TypeDef not added because repository thinks it is invalid: " + attributeTypeDef); log.error("InvalidTypeDefException: ", error); } catch (TypeDefKnownException error) { // TODO log an error to say that a logic error has occurred log.error("TypeDef not added because repository has a logic error: " + attributeTypeDef); log.error("TypeDefKnownException: ", error); } catch (Throwable error) { // TODO log an error to say that an unexpected error has occurred log.error("TypeDef not added because repository has an unexpected error: " + attributeTypeDef); log.error("Throwable: ", error); } } /** * An existing TypeDef has been updated in a remote metadata repository. * * @param sourceName name of the source of the event. It may be the cohort name for incoming events or the * local repository, or event mapper name. * @param originatorMetadataCollectionId unique identifier for the metadata collection hosted by the server that * sent the event. * @param originatorServerName name of the server that the event came from. * @param originatorServerType type of server that the event came from. * @param originatorOrganizationName name of the organization that owns the server that sent the event. * @param typeDefPatch details of the new version of the TypeDef */ public void processUpdatedTypeDefEvent(String sourceName, String originatorMetadataCollectionId, String originatorServerName, String originatorServerType, String originatorOrganizationName, TypeDefPatch typeDefPatch) { try { OMRSMetadataCollection metadataCollection = localRepositoryConnector.getMetadataCollection(); if (metadataCollection != null) { TypeDef updatedTypeDef = metadataCollection.updateTypeDef(null, typeDefPatch); log.debug("Patch successfully applied:" + updatedTypeDef); // TODO update needed to TypeDef Caches - whether there is a local repository or not } } catch (RepositoryErrorException error) { // TODO log an error to say that the repository is not available if (log.isDebugEnabled()) { log.debug("Patch not applied because repository is not available: " + typeDefPatch); } } catch (TypeDefNotKnownException error) { // TODO log an error to say that the TypeDef is not known if (log.isDebugEnabled()) { log.debug("Patch not applied because TypeDef does not exist: " + typeDefPatch); log.debug("TypeDefNotKnownException: ", error); } } catch (PatchErrorException error) { // TODO log an error to say that the TypeDef patch is invalid if (log.isDebugEnabled()) { log.debug("Patch not applied because it is invalid: " + typeDefPatch); log.debug("PatchErrorException: ", error); } } catch (Throwable error) { // TODO log a generic error if (log.isDebugEnabled()) { log.debug("Patch not applied because of an error " + typeDefPatch); log.debug("Throwable: ", error); } } } /** * An existing TypeDef has been deleted in a remote metadata repository. Both the name and the * GUID are provided to ensure the right TypeDef is deleted in other cohort member repositories. * * @param sourceName name of the source of the event. It may be the cohort name for incoming events or the * local repository, or event mapper name. * @param originatorMetadataCollectionId unique identifier for the metadata collection hosted by the server that * sent the event. * @param originatorServerName name of the server that the event came from. * @param originatorServerType type of server that the event came from. * @param originatorOrganizationName name of the organization that owns the server that sent the event. * @param typeDefGUID unique identifier of the TypeDef * @param typeDefName unique name of the TypeDef */ public void processDeletedTypeDefEvent(String sourceName, String originatorMetadataCollectionId, String originatorServerName, String originatorServerType, String originatorOrganizationName, String typeDefGUID, String typeDefName) { // TODO } /** * An existing AttributeTypeDef has been deleted in an open metadata repository. Both the name and the * GUID are provided to ensure the right AttributeTypeDef is deleted in other cohort member repositories. * * @param sourceName name of the source of the event. It may be the cohort name for incoming events or the * local repository, or event mapper name. * @param originatorMetadataCollectionId unique identifier for the metadata collection hosted by the server that * sent the event. * @param originatorServerName name of the server that the event came from. * @param originatorServerType type of server that the event came from. * @param originatorOrganizationName name of the organization that owns the server that sent the event. * @param attributeTypeDefGUID unique identifier of the AttributeTypeDef * @param attributeTypeDefName unique name of the AttributeTypeDef */ public void processDeletedAttributeTypeDefEvent(String sourceName, String originatorMetadataCollectionId, String originatorServerName, String originatorServerType, String originatorOrganizationName, String attributeTypeDefGUID, String attributeTypeDefName) { // TODO } /** * Process an event that changes either the name or guid of a TypeDef. It is resolving a Conflicting TypeDef Error. * * @param sourceName name of the source of the event. It may be the cohort name for incoming events or the * local repository, or event mapper name. * @param originatorMetadataCollectionId unique identifier for the metadata collection hosted by the server that * sent the event. * @param originatorServerName name of the server that the event came from. * @param originatorServerType type of server that the event came from. * @param originatorOrganizationName name of the organization that owns the server that sent the event. * @param originalTypeDefSummary details of the original TypeDef * @param typeDef updated TypeDef with new identifiers inside. */ public void processReIdentifiedTypeDefEvent(String sourceName, String originatorMetadataCollectionId, String originatorServerName, String originatorServerType, String originatorOrganizationName, TypeDefSummary originalTypeDefSummary, TypeDef typeDef) { // Todo } /** * Process an event that changes either the name or guid of an AttributeTypeDef. * It is resolving a Conflicting AttributeTypeDef Error. * * @param sourceName name of the source of the event. It may be the cohort name for incoming events or the * local repository, or event mapper name. * @param originatorMetadataCollectionId unique identifier for the metadata collection hosted by the server that * sent the event. * @param originatorServerName name of the server that the event came from. * @param originatorServerType type of server that the event came from. * @param originatorOrganizationName name of the organization that owns the server that sent the event. * @param originalAttributeTypeDef description of original AttributeTypeDef * @param attributeTypeDef updated AttributeTypeDef with new identifiers inside. */ public void processReIdentifiedAttributeTypeDefEvent(String sourceName, String originatorMetadataCollectionId, String originatorServerName, String originatorServerType, String originatorOrganizationName, AttributeTypeDef originalAttributeTypeDef, AttributeTypeDef attributeTypeDef) { // TODO } /** * Process a detected conflict in type definitions (TypeDefs) used in the cohort. * * @param sourceName name of the source of the event. It may be the cohort name for incoming events or the * local repository, or event mapper name. * @param originatorMetadataCollectionId unique identifier for the metadata collection hosted by the server that * sent the event. * @param originatorServerName name of the server that the event came from. * @param originatorServerType type of server that the event came from. * @param originatorOrganizationName name of the organization that owns the server that sent the event. * @param originatorTypeDefSummary details of the TypeDef in the event originator * @param otherMetadataCollectionId the metadataCollection using the conflicting TypeDef * @param conflictingTypeDefSummary the details of the TypeDef in the other metadata collection * @param errorMessage details of the error that occurs when the connection is used. */ public void processTypeDefConflictEvent(String sourceName, String originatorMetadataCollectionId, String originatorServerName, String originatorServerType, String originatorOrganizationName, TypeDefSummary originatorTypeDefSummary, String otherMetadataCollectionId, TypeDefSummary conflictingTypeDefSummary, String errorMessage) { // TODO } /** * Process a detected conflict in the attribute type definitions (AttributeTypeDefs) used in the cohort. * * @param sourceName name of the source of the event. It may be the cohort name for incoming events or the * local repository, or event mapper name. * @param originatorMetadataCollectionId unique identifier for the metadata collection hosted by the server that * sent the event. * @param originatorServerName name of the server that the event came from. * @param originatorServerType type of server that the event came from. * @param originatorOrganizationName name of the organization that owns the server that sent the event. * @param originatorAttributeTypeDef- description of the AttributeTypeDef in the event originator. * @param otherMetadataCollectionId the metadataCollection using the conflicting AttributeTypeDef. * @param conflictingAttributeTypeDef description of the AttributeTypeDef in the other metadata collection. * @param errorMessage details of the error that occurs when the connection is used. */ public void processAttributeTypeDefConflictEvent(String sourceName, String originatorMetadataCollectionId, String originatorServerName, String originatorServerType, String originatorOrganizationName, AttributeTypeDef originatorAttributeTypeDef, String otherMetadataCollectionId, AttributeTypeDef conflictingAttributeTypeDef, String errorMessage) { // TODO } /** * A TypeDef from another member in the cohort is at a different version than the local repository. This may * create some inconsistencies in the different copies of instances of this type in different members of the * cohort. The recommended action is to update all TypeDefs to the latest version. * * @param sourceName name of the source of the event. It may be the cohort name for incoming events or the * local repository, or event mapper name. * @param originatorMetadataCollectionId unique identifier for the metadata collection hosted by the server that * sent the event. * @param originatorServerName name of the server that the event came from. * @param originatorServerType type of server that the event came from. * @param originatorOrganizationName name of the organization that owns the server that sent the event. * @param targetMetadataCollectionId identifier of the metadata collection that is reporting a TypeDef at a * different level to the local repository. * @param targetTypeDefSummary details of the target TypeDef * @param otherTypeDef details of the TypeDef in the local repository. */ public void processTypeDefPatchMismatchEvent(String sourceName, String originatorMetadataCollectionId, String originatorServerName, String originatorServerType, String originatorOrganizationName, String targetMetadataCollectionId, TypeDefSummary targetTypeDefSummary, TypeDef otherTypeDef, String errorMessage) { // TODO } /* * =========================== * Metadata Collections */ /** * Remember the metadata collection name for this metadata collection Id. If the metadata collection id * is null, it is ignored. * * @param metadataCollectionId unique identifier (guid) for the metadata collection. * @param metadataCollectionName display name for the metadata collection (can be null). */ synchronized void registerMetadataCollection(String metadataCollectionId, String metadataCollectionName) { if (metadataCollectionId != null) { metadataCollectionNames.put(metadataCollectionId, metadataCollectionName); } } /** * Return the metadata collection name (or null) for a metadata collection id. * * @param metadataCollectionId unique identifier (guid) for the metadata collection. * @return display name */ public synchronized String getMetadataCollectionName(String metadataCollectionId) { if (metadataCollectionId != null) { return metadataCollectionNames.get(metadataCollectionId); } else { return null; } } /* ======================== * Private error handling */ /* ======================== * Private error handling */ /** * Throws a logic error exception when the repository content manager is called with invalid parameters. * Normally this means the repository content manager methods have been called in the wrong order. * * @param sourceName source of the request (used for logging) * @param originatingMethodName method that called the repository validator * @param localMethodName local method that deleted the error */ private void throwContentManagerLogicError(String sourceName, String originatingMethodName, String localMethodName) { OMRSErrorCode errorCode = OMRSErrorCode.CONTENT_MANAGER_LOGIC_ERROR; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(sourceName, localMethodName, originatingMethodName); throw new OMRSLogicErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), localMethodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } }
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.kubernetes.customresources; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.ExtendedPropertyConfigurerGetter; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.spi.ConfigurerStrategy; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.support.component.PropertyConfigurerSupport; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class KubernetesCustomResourcesEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { KubernetesCustomResourcesEndpoint target = (KubernetesCustomResourcesEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiversion": case "apiVersion": target.getConfiguration().setApiVersion(property(camelContext, java.lang.String.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "cacertdata": case "caCertData": target.getConfiguration().setCaCertData(property(camelContext, java.lang.String.class, value)); return true; case "cacertfile": case "caCertFile": target.getConfiguration().setCaCertFile(property(camelContext, java.lang.String.class, value)); return true; case "clientcertdata": case "clientCertData": target.getConfiguration().setClientCertData(property(camelContext, java.lang.String.class, value)); return true; case "clientcertfile": case "clientCertFile": target.getConfiguration().setClientCertFile(property(camelContext, java.lang.String.class, value)); return true; case "clientkeyalgo": case "clientKeyAlgo": target.getConfiguration().setClientKeyAlgo(property(camelContext, java.lang.String.class, value)); return true; case "clientkeydata": case "clientKeyData": target.getConfiguration().setClientKeyData(property(camelContext, java.lang.String.class, value)); return true; case "clientkeyfile": case "clientKeyFile": target.getConfiguration().setClientKeyFile(property(camelContext, java.lang.String.class, value)); return true; case "clientkeypassphrase": case "clientKeyPassphrase": target.getConfiguration().setClientKeyPassphrase(property(camelContext, java.lang.String.class, value)); return true; case "connectiontimeout": case "connectionTimeout": target.getConfiguration().setConnectionTimeout(property(camelContext, java.lang.Integer.class, value)); return true; case "crdgroup": case "crdGroup": target.getConfiguration().setCrdGroup(property(camelContext, java.lang.String.class, value)); return true; case "crdname": case "crdName": target.getConfiguration().setCrdName(property(camelContext, java.lang.String.class, value)); return true; case "crdplural": case "crdPlural": target.getConfiguration().setCrdPlural(property(camelContext, java.lang.String.class, value)); return true; case "crdscope": case "crdScope": target.getConfiguration().setCrdScope(property(camelContext, java.lang.String.class, value)); return true; case "crdversion": case "crdVersion": target.getConfiguration().setCrdVersion(property(camelContext, java.lang.String.class, value)); return true; case "dnsdomain": case "dnsDomain": target.getConfiguration().setDnsDomain(property(camelContext, java.lang.String.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "kubernetesclient": case "kubernetesClient": target.getConfiguration().setKubernetesClient(property(camelContext, io.fabric8.kubernetes.client.KubernetesClient.class, value)); return true; case "labelkey": case "labelKey": target.getConfiguration().setLabelKey(property(camelContext, java.lang.String.class, value)); return true; case "labelvalue": case "labelValue": target.getConfiguration().setLabelValue(property(camelContext, java.lang.String.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "namespace": target.getConfiguration().setNamespace(property(camelContext, java.lang.String.class, value)); return true; case "oauthtoken": case "oauthToken": target.getConfiguration().setOauthToken(property(camelContext, java.lang.String.class, value)); return true; case "operation": target.getConfiguration().setOperation(property(camelContext, java.lang.String.class, value)); return true; case "password": target.getConfiguration().setPassword(property(camelContext, java.lang.String.class, value)); return true; case "poolsize": case "poolSize": target.getConfiguration().setPoolSize(property(camelContext, int.class, value)); return true; case "portname": case "portName": target.getConfiguration().setPortName(property(camelContext, java.lang.String.class, value)); return true; case "portprotocol": case "portProtocol": target.getConfiguration().setPortProtocol(property(camelContext, java.lang.String.class, value)); return true; case "resourcename": case "resourceName": target.getConfiguration().setResourceName(property(camelContext, java.lang.String.class, value)); return true; case "trustcerts": case "trustCerts": target.getConfiguration().setTrustCerts(property(camelContext, java.lang.Boolean.class, value)); return true; case "username": target.getConfiguration().setUsername(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "apiversion": case "apiVersion": return java.lang.String.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "cacertdata": case "caCertData": return java.lang.String.class; case "cacertfile": case "caCertFile": return java.lang.String.class; case "clientcertdata": case "clientCertData": return java.lang.String.class; case "clientcertfile": case "clientCertFile": return java.lang.String.class; case "clientkeyalgo": case "clientKeyAlgo": return java.lang.String.class; case "clientkeydata": case "clientKeyData": return java.lang.String.class; case "clientkeyfile": case "clientKeyFile": return java.lang.String.class; case "clientkeypassphrase": case "clientKeyPassphrase": return java.lang.String.class; case "connectiontimeout": case "connectionTimeout": return java.lang.Integer.class; case "crdgroup": case "crdGroup": return java.lang.String.class; case "crdname": case "crdName": return java.lang.String.class; case "crdplural": case "crdPlural": return java.lang.String.class; case "crdscope": case "crdScope": return java.lang.String.class; case "crdversion": case "crdVersion": return java.lang.String.class; case "dnsdomain": case "dnsDomain": return java.lang.String.class; case "exceptionhandler": case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class; case "exchangepattern": case "exchangePattern": return org.apache.camel.ExchangePattern.class; case "kubernetesclient": case "kubernetesClient": return io.fabric8.kubernetes.client.KubernetesClient.class; case "labelkey": case "labelKey": return java.lang.String.class; case "labelvalue": case "labelValue": return java.lang.String.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "namespace": return java.lang.String.class; case "oauthtoken": case "oauthToken": return java.lang.String.class; case "operation": return java.lang.String.class; case "password": return java.lang.String.class; case "poolsize": case "poolSize": return int.class; case "portname": case "portName": return java.lang.String.class; case "portprotocol": case "portProtocol": return java.lang.String.class; case "resourcename": case "resourceName": return java.lang.String.class; case "trustcerts": case "trustCerts": return java.lang.Boolean.class; case "username": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { KubernetesCustomResourcesEndpoint target = (KubernetesCustomResourcesEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiversion": case "apiVersion": return target.getConfiguration().getApiVersion(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "cacertdata": case "caCertData": return target.getConfiguration().getCaCertData(); case "cacertfile": case "caCertFile": return target.getConfiguration().getCaCertFile(); case "clientcertdata": case "clientCertData": return target.getConfiguration().getClientCertData(); case "clientcertfile": case "clientCertFile": return target.getConfiguration().getClientCertFile(); case "clientkeyalgo": case "clientKeyAlgo": return target.getConfiguration().getClientKeyAlgo(); case "clientkeydata": case "clientKeyData": return target.getConfiguration().getClientKeyData(); case "clientkeyfile": case "clientKeyFile": return target.getConfiguration().getClientKeyFile(); case "clientkeypassphrase": case "clientKeyPassphrase": return target.getConfiguration().getClientKeyPassphrase(); case "connectiontimeout": case "connectionTimeout": return target.getConfiguration().getConnectionTimeout(); case "crdgroup": case "crdGroup": return target.getConfiguration().getCrdGroup(); case "crdname": case "crdName": return target.getConfiguration().getCrdName(); case "crdplural": case "crdPlural": return target.getConfiguration().getCrdPlural(); case "crdscope": case "crdScope": return target.getConfiguration().getCrdScope(); case "crdversion": case "crdVersion": return target.getConfiguration().getCrdVersion(); case "dnsdomain": case "dnsDomain": return target.getConfiguration().getDnsDomain(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "kubernetesclient": case "kubernetesClient": return target.getConfiguration().getKubernetesClient(); case "labelkey": case "labelKey": return target.getConfiguration().getLabelKey(); case "labelvalue": case "labelValue": return target.getConfiguration().getLabelValue(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "namespace": return target.getConfiguration().getNamespace(); case "oauthtoken": case "oauthToken": return target.getConfiguration().getOauthToken(); case "operation": return target.getConfiguration().getOperation(); case "password": return target.getConfiguration().getPassword(); case "poolsize": case "poolSize": return target.getConfiguration().getPoolSize(); case "portname": case "portName": return target.getConfiguration().getPortName(); case "portprotocol": case "portProtocol": return target.getConfiguration().getPortProtocol(); case "resourcename": case "resourceName": return target.getConfiguration().getResourceName(); case "trustcerts": case "trustCerts": return target.getConfiguration().getTrustCerts(); case "username": return target.getConfiguration().getUsername(); default: return null; } } }
package server; import java.util.HashMap; import java.util.Map; /** * * @author zjj */ public class MapleShopFactory { private Map<Integer, MapleShop> shops = new HashMap<>(); private Map<Integer, MapleShop> npcShops = new HashMap<>(); private static MapleShopFactory instance = new MapleShopFactory(); /** * * @return */ public static MapleShopFactory getInstance() { return instance; } /** * */ public void clear() { shops.clear(); npcShops.clear(); } /** * * @param shopId * @return */ public MapleShop getShop(int shopId) { if (shops.containsKey(shopId)) { return shops.get(shopId); } return loadShop(shopId, true); } /** * * @param npcId * @return */ public MapleShop getShopForNPC(int npcId) { if (npcShops.containsKey(npcId)) { return npcShops.get(npcId); } return loadShop(npcId, false); } private MapleShop loadShop(int id, boolean isShopId) { MapleShop ret = MapleShop.createFromDB(id, isShopId); if (ret != null) { shops.put(ret.getId(), ret); npcShops.put(ret.getNpcId(), ret); } else if (isShopId) { shops.put(id, null); } else { npcShops.put(id, null); } return ret; } }
package ch.heigvd.amt.mvcdemo.services; import ch.heigvd.amt.mvcdemo.model.User; import ch.heigvd.amt.mvcdemo.rest.UserRessource; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Patrick Deslé Djomo * @version 1.0 * @description this stateless session bean class implements the user DAO interface */ @Stateless public class UserManagerService implements UserManagerServiceLocal { //dependency injection @Resource(lookup = "java:/jdbc/MCVDemo") private DataSource dataSource; private static final Logger LOG = Logger.getLogger(UserManagerService.class.getName()); /** * @description methode to save a new user to database * @param user the user to save * @return int * @throws DuplicateResourceException * @throws ResourceNotFoundException */ @Override public int registerUser(User user) throws DuplicateResourceException{ int id = 0; try { // we check weither the login already existed if(getUser(user.getLogin()) != null){ throw new DuplicateResourceException(); } } catch (ResourceNotFoundException e) { // if not then we can register the user // SQL query String sql = "INSERT INTO user(email, login, password)" + "VALUES (?,?,?)"; try(Connection con = dataSource.getConnection(); // we get the connection from the pool PreparedStatement prepstmt = con.prepareStatement(sql)){ prepstmt.setString(1, user.getEmail()); prepstmt.setString(2, user.getLogin()); prepstmt.setString(3, user.getPassword()); prepstmt.executeUpdate(); // we create and submit sql query prepstmt.close(); con.close(); // we return the connection to the pool } catch (SQLException ex) { throw new RuntimeException(ex); } try { id = getUser(user.getLogin(), user.getPassword()).getId(); }catch (ResourceNotFoundException exc){ throw new RuntimeException(exc); } } return id; } /** * @description methode to update the user attributes that owne the id gived in parameter * @param id user id * @param user user with new attribute to update * @throws ResourceNotFoundException * @throws DuplicateResourceException */ @Override public void updateUser(int id, User user) throws ResourceNotFoundException, DuplicateResourceException { getUser(id); // we check if the id exist. if not RessourceNotFoundException will be throw try{ if(getUser(user.getLogin())!= null){ // we also check if the login alredy existed throw new DuplicateResourceException(); } }catch (ResourceNotFoundException e){ // if not we update the user login // SQL query String sql = "UPDATE user SET email = ?, login = ?, password = ?" + "WHERE userID = ?"; try (Connection con = dataSource.getConnection(); // we get the connection from the pool PreparedStatement prepState = con.prepareStatement(sql)){ prepState.setString(1, user.getEmail()); prepState.setString(2, user.getLogin()); prepState.setString(3, user.getPassword()); prepState.setInt(4, id); prepState.executeUpdate(); // we create and submit the SQL query prepState.close(); con.close(); // we return the connection to the pool }catch (SQLException ex){ throw new RuntimeException(ex); } } } /** * @description methode to delete user that owne the id gived in parameter * @param id id user * @throws ResourceNotFoundException */ @Override public void deleteUser(int id) throws ResourceNotFoundException { // SQL query String sql = "DELETE " + "FROM user " + "WHERE userID = ?"; try(Connection con = dataSource.getConnection(); // we get the connection from the pool PreparedStatement prepstmt = con.prepareStatement(sql)){ prepstmt.setInt(1, id); int result = prepstmt.executeUpdate(); // we create and submit the SQL query if(result == 0){ // we check weither we have been able to delete the user throw new ResourceNotFoundException(); } prepstmt.close(); // we return the connection to the pool con.close(); } catch (SQLException e) { throw new RuntimeException(e); } } /** * @description methode to get user that owne the id gived in parameter * @param id user id * @throws ResourceNotFoundException * @return User */ @Override public User getUser(int id) throws ResourceNotFoundException { // SQL query String sql = "SELECT userID, email, login, password " + "FROM user " + "WHERE userID = ?"; User user = null; try(Connection con = dataSource.getConnection(); // we get the connection from the pool PreparedStatement prepstmt = con.prepareStatement(sql)){ prepstmt.setInt(1, id); ResultSet set = prepstmt.executeQuery(); // we submit the SQL query if(!set.next()){ // we check weither we have been able to find the user with the id throw new ResourceNotFoundException(); } // we get the user user = new User(set.getInt("userID"), set.getString("email"), set.getString("login"), set.getString("password")); prepstmt.close(); con.close(); // we return the connection to the pool } catch (SQLException e) { throw new RuntimeException(e); } return user; } /** * @description methode to get user that owne the login gived in parameter * @param login user login * @throws ResourceNotFoundException * @return User */ @Override public User getUser(String login) throws ResourceNotFoundException{ //SQL query String sql = "SELECT email, login, password " + "FROM user " + "WHERE login = ?"; User user = null; try(Connection con = dataSource.getConnection(); // we get connection from the pool PreparedStatement prepstmt = con.prepareStatement(sql)){ prepstmt.setString(1, login); ResultSet set = prepstmt.executeQuery(); // we submit the SQL query if(!set.next()){ // we check weither we have been able to get the user with the login throw new ResourceNotFoundException(); } user = new User(set.getString("email"), set.getString("login"), set.getString("password")); prepstmt.close(); con.close(); // we return the connection to the pool } catch (SQLException e) { throw new RuntimeException(e); } return user; } /** * @description methode to get user that owne the login and password gived in parameters * @param login user login * @param password user password * @return User */ @Override public User getUser(String login, String password) throws ResourceNotFoundException { //SQL query String sql = "SELECT userID, email, login, password " + "FROM user " + "WHERE login = ? AND password = ?"; User user = null; try(Connection con = dataSource.getConnection(); // we get the connection from the pool PreparedStatement prepstmt = con.prepareStatement(sql)){ prepstmt.setString(1, login); prepstmt.setString(2, password); ResultSet set = prepstmt.executeQuery(); // we submit the SQL connection if(!set.next()){ // we check weither we have been able to get the user with the login and password throw new ResourceNotFoundException(); } user = new User(set.getInt("userID"), set.getString("email"), set.getString("login"), set.getString("password")); prepstmt.close(); con.close(); // we return the connnection to the pool } catch (SQLException e) { LOG.log(Level.SEVERE, e.getMessage()); } return user; } /** * @description methode to get users list stored in the database * @return List<User> */ @Override public List<User> getUsers() { String sql = "SELECT email, login, password " + "FROM user "; User user = null; List<User> users = new LinkedList<>(); try(Connection con = dataSource.getConnection(); // we get the connection from the pool PreparedStatement prepstmt = con.prepareStatement(sql)){ ResultSet set = prepstmt.executeQuery(); // we create and submit the SQL query // we scroll through the tabular result set while (set.next()){ users.add(new User(set.getString("email"), set.getString("login"), set.getString("password"))); } prepstmt.close(); con.close(); // we return the connection to the pool } catch (SQLException e) { throw new RuntimeException(e); } return users; } }
package org.innovateuk.ifs.competitionsetup.application.sectionupdater; import org.innovateuk.ifs.commons.rest.RestResult; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.competition.resource.CompetitionSetupSubsection; import org.innovateuk.ifs.competition.service.CompetitionSetupRestService; import org.innovateuk.ifs.competitionsetup.application.form.DetailsForm; import org.innovateuk.ifs.competitionsetup.core.form.CompetitionSetupForm; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import java.math.BigDecimal; import static org.assertj.core.api.Assertions.assertThat; import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.Silent.class) public class ApplicationDetailsSectionSaverTest { @InjectMocks private DetailsSectionUpdater service; @Mock private CompetitionSetupRestService competitionSetupRestServiceMock; @Before public void setup() { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ReflectionTestUtils.setField(service, "validator", validator); } @Test public void testSectionToSave() { assertThat(service.subsectionToSave()).isEqualByComparingTo(CompetitionSetupSubsection.APPLICATION_DETAILS); } @Test public void testsSupportsForm() { assertThat(service.supportsForm(DetailsForm.class)).isTrue(); assertThat(service.supportsForm(CompetitionSetupForm.class)).isFalse(); } @Test public void doSaveSection_validInputIsMappedProperlyAndResultsInUpdateRestCall() { CompetitionResource competitionResource = newCompetitionResource().withId(1L).build(); DetailsForm detailsForm = new DetailsForm(); detailsForm.setMinProjectDuration(new BigDecimal(9)); detailsForm.setMaxProjectDuration(new BigDecimal(10)); detailsForm.setUseResubmissionQuestion(true); when(competitionSetupRestServiceMock.update(any())).thenReturn(RestResult.restSuccess()); ServiceResult<Void> result = service.doSaveSection(competitionResource, detailsForm); CompetitionResource expectedCompetitionResource = newCompetitionResource().build(); expectedCompetitionResource.setId(1L); expectedCompetitionResource.setMinProjectDuration(9); expectedCompetitionResource.setMaxProjectDuration(10); expectedCompetitionResource.setUseResubmissionQuestion(true); assertThat(result.isSuccess()).isTrue(); verify(competitionSetupRestServiceMock, times(1)).update(expectedCompetitionResource); } @Test public void doSaveSection_errorWhenFieldsAreEmpty() { CompetitionResource competitionResource = newCompetitionResource().build(); DetailsForm detailsForm = new DetailsForm(); ServiceResult<Void> result = service.doSaveSection(competitionResource, detailsForm); assertThat(result.isFailure()).isTrue(); assertThat(result.getErrors().size()).isEqualTo(3); assertThat(result.getErrors()) .filteredOn(error -> error.getFieldName().equals("minProjectDuration") && error.getErrorKey().equals("validation.field.must.not.be.blank")) .isNotEmpty(); assertThat(result.getErrors()) .filteredOn(error -> error.getFieldName().equals("maxProjectDuration") && error.getErrorKey().equals("validation.field.must.not.be.blank")) .isNotEmpty(); assertThat(result.getErrors()) .filteredOn(error -> error.getFieldName().equals("useResubmissionQuestion") && error.getErrorKey().equals("validation.application.must.indicate.resubmission.or.not")) .isNotEmpty(); verifyZeroInteractions(competitionSetupRestServiceMock); } @Test public void doSaveSection_errorWhenProjectDurationsAreBelowMinimumAllowed() { CompetitionResource competitionResource = newCompetitionResource().build(); DetailsForm detailsForm = new DetailsForm(); detailsForm.setUseResubmissionQuestion(false); detailsForm.setMaxProjectDuration(new BigDecimal(0)); detailsForm.setMinProjectDuration(new BigDecimal(0)); ServiceResult<Void> result = service.doSaveSection(competitionResource, detailsForm); assertThat(result.isFailure()).isTrue(); assertThat(result.getErrors().size()).isEqualTo(2); assertThat(result.getErrors()) .filteredOn(error -> error.getFieldName().equals("minProjectDuration") && error.getErrorKey().equals("competition.setup.applicationdetails.projectduration.min")) .isNotEmpty(); assertThat(result.getErrors()) .filteredOn(error -> error.getFieldName().equals("maxProjectDuration") && error.getErrorKey().equals("competition.setup.applicationdetails.projectduration.min")) .isNotEmpty(); verifyZeroInteractions(competitionSetupRestServiceMock); } @Test public void doSaveSection_errorWhenProjectDurationsAreNegative() { CompetitionResource competitionResource = newCompetitionResource().build(); DetailsForm detailsForm = new DetailsForm(); detailsForm.setUseResubmissionQuestion(false); detailsForm.setMaxProjectDuration(new BigDecimal(-1)); detailsForm.setMinProjectDuration(new BigDecimal(-1)); ServiceResult<Void> result = service.doSaveSection(competitionResource, detailsForm); assertThat(result.isFailure()).isTrue(); assertThat(result.getErrors().size()).isEqualTo(2); assertThat(result.getErrors()) .filteredOn(error -> error.getFieldName().equals("minProjectDuration") && error.getErrorKey().equals("competition.setup.applicationdetails.projectduration.min")) .isNotEmpty(); assertThat(result.getErrors()) .filteredOn(error -> error.getFieldName().equals("maxProjectDuration") && error.getErrorKey().equals("competition.setup.applicationdetails.projectduration.min")) .isNotEmpty(); verifyZeroInteractions(competitionSetupRestServiceMock); } @Test public void doSaveSection_errorWhenDecimalsInProjectDurations() { CompetitionResource competitionResource = newCompetitionResource().build(); DetailsForm detailsForm = new DetailsForm(); detailsForm.setUseResubmissionQuestion(false); detailsForm.setMinProjectDuration(new BigDecimal(3.5)); detailsForm.setMaxProjectDuration(new BigDecimal(3.5)); ServiceResult<Void> result = service.doSaveSection(competitionResource, detailsForm); assertThat(result.isFailure()).isTrue(); assertThat(result.getErrors().size()).isEqualTo(2); assertThat(result.getErrors()) .filteredOn(error -> error.getFieldName().equals("minProjectDuration") && error.getErrorKey().equals("validation.standard.integer.non.decimal.format")) .isNotEmpty(); assertThat(result.getErrors()) .filteredOn(error -> error.getFieldName().equals("maxProjectDuration") && error.getErrorKey().equals("validation.standard.integer.non.decimal.format")) .isNotEmpty(); verifyZeroInteractions(competitionSetupRestServiceMock); } @Test public void doSaveSection_successWhenMinFieldIsEqualToMaxField() { CompetitionResource competitionResource = newCompetitionResource().build(); DetailsForm detailsForm = new DetailsForm(); detailsForm.setMinProjectDuration(new BigDecimal(10)); detailsForm.setMaxProjectDuration(new BigDecimal(10)); detailsForm.setUseResubmissionQuestion(true); when(competitionSetupRestServiceMock.update(any())).thenReturn(RestResult.restSuccess()); ServiceResult<Void> result = service.doSaveSection(competitionResource, detailsForm); assertThat(result.isSuccess()).isTrue(); verify(competitionSetupRestServiceMock, times(1)).update(any()); } @Test public void doSaveSection_errorWhenMinFieldExceedsMaxField() { CompetitionResource competitionResource = newCompetitionResource().build(); DetailsForm detailsForm = new DetailsForm(); detailsForm.setMinProjectDuration(new BigDecimal(11)); detailsForm.setMaxProjectDuration(new BigDecimal(10)); detailsForm.setUseResubmissionQuestion(false); ServiceResult<Void> result = service.doSaveSection(competitionResource, detailsForm); assertThat(result.isFailure()).isTrue(); assertThat(result.getErrors().size()).isEqualTo(2); assertThat(result.getErrors()) .filteredOn(error -> error.getFieldName().equals("minProjectDuration") && error.getErrorKey().equals("competition.setup.applicationdetails.min.projectduration.exceedsmax")) .isNotEmpty(); assertThat(result.getErrors()) .filteredOn(error -> error.getFieldName().equals("maxProjectDuration") && error.getErrorKey().equals("competition.setup.applicationdetails.max.projectduration.beneathmin")) .isNotEmpty(); verifyZeroInteractions(competitionSetupRestServiceMock); } @Test public void doSaveSection_errorWhenProjectDurationsExceedMaximumAllowed() { CompetitionResource competitionResource = newCompetitionResource().build(); DetailsForm detailsForm = new DetailsForm(); detailsForm.setMinProjectDuration(new BigDecimal(61)); detailsForm.setMaxProjectDuration(new BigDecimal(61)); detailsForm.setUseResubmissionQuestion(false); ServiceResult<Void> result = service.doSaveSection(competitionResource, detailsForm); assertThat(result.isFailure()).isTrue(); assertThat(result.getErrors().size()).isEqualTo(2); assertThat(result.getErrors()) .filteredOn(error -> error.getFieldName().equals("minProjectDuration") && error.getErrorKey().equals("competition.setup.applicationdetails.projectduration.max")) .isNotEmpty(); assertThat(result.getErrors()) .filteredOn(error -> error.getFieldName().equals("maxProjectDuration") && error.getErrorKey().equals("competition.setup.applicationdetails.projectduration.max")) .isNotEmpty(); verifyZeroInteractions(competitionSetupRestServiceMock); } }
package com.htetznaing.xgetter.Utils; import android.util.Base64; import com.htetznaing.xgetter.Model.XModel; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Utils { public static void putModel(String url, String quality, ArrayList<XModel> model){ for (XModel x:model){ if (x.getQuality().equalsIgnoreCase(quality)){ return; } } XModel xModel = new XModel(); xModel.setUrl(url); xModel.setQuality(quality); model.add(xModel); } public static ArrayList<XModel> sortMe(ArrayList<XModel> x){ if (x!=null) { ArrayList<XModel> result = new ArrayList<>(); for (XModel t : x) { if (startWithNumber(t.getQuality()) || t.getQuality().isEmpty()) { // with this modificaction it is included those with quality field is empty. EX. openload result.add(t); } } Collections.sort(result, Collections.reverseOrder()); return result; } return null; } private static boolean startWithNumber(String string){ //final String regex = "^[0-9][A-Za-z0-9-]*$"; final String regex ="^[0-9][A-Za-z0-9-\\s,]*$"; // start with number and can contain space or comma ( 480p , ENG) final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); final Matcher matcher = pattern.matcher(string); return matcher.find(); } public static String getDomainFromURL(String url){ String regex = "^(?:https?:\\/\\/)?(?:[^@\\n]+@)?(?:www\\.)?([^:\\/\\n?]+)"; Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); Matcher matcher = pattern.matcher(url); if (matcher.find()) { return matcher.group(0); } return null; } public static String base64Encode(String text) { byte[] data = new byte[0]; try { data = text.getBytes("UTF-8"); return Base64.encodeToString(data, Base64.DEFAULT); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public static String base64Decode(String text) { byte[] data = Base64.decode(text, Base64.DEFAULT); try { return new String(data, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } }
/** * Appia: Group communication and protocol composition framework library * Copyright 2006 University of Lisbon * * 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. * * Initial developer(s): Nuno Carvalho. * Contributor(s): See Appia web page for a list of contributors. */ package net.sf.appia.jgcs.protocols.top; import net.sf.appia.core.Layer; import net.sf.appia.core.Session; import net.sf.appia.core.events.channel.ChannelClose; import net.sf.appia.core.events.channel.ChannelInit; import net.sf.appia.jgcs.MessageSender; import net.sf.appia.protocols.common.RegisterSocketEvent; import net.sf.appia.protocols.udpsimple.MulticastInitEvent; /** * This class defines a SimpleTOPLayer * * @author <a href="mailto:nunomrc@di.fc.ul.pt">Nuno Carvalho</a> * @version 1.0 */ public class SimpleTOPLayer extends Layer { /** * Creates a new SimpleTOPLayer. */ public SimpleTOPLayer() { super(); evProvide=new Class[]{ RegisterSocketEvent.class, JGCSSendableEvent.class, MulticastInitEvent.class }; evRequire=new Class[]{}; evAccept=new Class[]{ ChannelInit.class, ChannelClose.class, RegisterSocketEvent.class, MulticastInitEvent.class, JGCSSendableEvent.class, MessageSender.class, }; } /** * @see net.sf.appia.core.Layer#createSession() */ @Override public Session createSession() { return new SimpleTOPSession(this); } }
/* * aTalk, android VoIP and Instant Messaging client * Copyright 2014 Eng Chong Meng * * 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.atalk.android.gui; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.webkit.WebView; import android.widget.TextView; import net.java.sip.communicator.service.update.UpdateService; import net.java.sip.communicator.util.ServiceUtils; import org.atalk.android.*; import de.cketti.library.changelog.ChangeLog; /** * About activity * * @author Eng Chong Meng */ public class About extends Activity implements OnClickListener { private static String[][] USED_LIBRARIES = new String[][]{ new String[]{"Android Support Library", "https://developer.android.com/topic/libraries/support-library/index.html"}, new String[]{"android-betterpickers", "https://github.com/code-troopers/android-betterpickers"}, new String[]{"Android-EasyLocation", "https://github.com/akhgupta/Android-EasyLocation"}, new String[]{"annotations-java5", "https://mvnrepository.com/artifact/org.jetbrains/annotations"}, new String[]{"bouncycastle", "https://github.com/bcgit/bc-java"}, new String[]{"butterknife", "https://github.com/JakeWharton/butterknife"}, new String[]{"ckChangeLog", "https://github.com/cketti/ckChangeLog"}, new String[]{"commons-lang", "https://commons.apache.org/proper/commons-lang/"}, new String[]{"Dexter", "https://github.com/Karumi/Dexter"}, new String[]{"dhcp4java", "https://github.com/ggrandes-clones/dhcp4java"}, new String[]{"FFmpeg", "https://github.com/FFmpeg/FFmpeg"}, new String[]{"glide", "https://github.com/bumptech/glide"}, new String[]{"Google Play Services", "https://developers.google.com/android/guides/overview"}, new String[]{"httpclient-android", "https://github.com/smarek/httpclient-android"}, new String[]{"ice4j", "https://github.com/jitsi/ice4j"}, new String[]{"jitsi", "https://github.com/jitsi/jitsi"}, new String[]{"jitsi-android", "https://github.com/jitsi/jitsi-android"}, new String[]{"jmdns", "https://github.com/jmdns/jmdns"}, new String[]{"jxmpp-jid", "https://github.com/igniterealtime/jxmpp"}, new String[]{"libjitsi", "https://github.com/jitsi/libjitsi"}, new String[]{"libphonenumber", "https://github.com/googlei18n/libphonenumber"}, new String[]{"libvpx", "https://github.com/webmproject/libvpx"}, new String[]{"Mime4j", "https://james.apache.org/mime4j/"}, new String[]{"miniDNS", "https://github.com/MiniDNS/minidns"}, new String[]{"Noembed", "https://noembed.com/"}, new String[]{"otr4j", "https://github.com/jitsi/otr4j"}, new String[]{"opensles", "https://github.com/openssl/openssl "}, new String[]{"osgi.core", "http://grepcode.com/snapshot/repo1.maven.org/maven2/org.osgi/org.osgi.core/6.0.0"}, new String[]{"sdes4j", "https://github.com/ibauersachs/sdes4j"}, new String[]{"sdp-api", "https://mvnrepository.com/artifact/org.opentelecoms.sdp/sdp-api"}, new String[]{"Smack", "https://github.com/igniterealtime/Smack"}, new String[]{"speex", "https://github.com/xiph/speex"}, new String[]{"Timber", "https://github.com/JakeWharton/timber"}, new String[]{"TokenAutoComplete", "https://github.com/splitwise/TokenAutoComplete"}, new String[]{"uCrop", "https://github.com/Yalantis/uCrop"}, new String[]{"weupnp", "https://github.com/bitletorg/weupnp"}, new String[]{"x264", "https://git.videolan.org/git/x264.git"}, new String[]{"zrtp4j-light", "https://github.com/jitsi/zrtp4j"}, }; private static String[][] SUPPORTED_XEP = new String[][]{ new String[]{"XEP-0012: Last Activity", "https://xmpp.org/extensions/xep-0012.html"}, new String[]{"XEP-0030: Service Discovery", "https://xmpp.org/extensions/xep-0030.html"}, new String[]{"XEP-0045: Multi-User Chat", "https://xmpp.org/extensions/xep-0045.html"}, new String[]{"XEP-0047: In-Band Bytestreams", "https://xmpp.org/extensions/xep-00047.html"}, new String[]{"XEP-0048: Bookmarks", "https://xmpp.org/extensions/xep-0048.html"}, new String[]{"XEP-0054: vcard-temp", "https://xmpp.org/extensions/xep-0054.html"}, new String[]{"XEP-0060: Publish-Subscribe", "https://xmpp.org/extensions/xep-0060.html"}, new String[]{"XEP-0065: SOCKS5 Bytestreams", "https://xmpp.org/extensions/xep-0065.html"}, new String[]{"XEP-0070: Verifying HTTP Requests via XMPP", "https://xmpp.org/extensions/xep-0070.html"}, new String[]{"XEP-0071: XHTML-IM", "https://xmpp.org/extensions/xep-0071.html"}, new String[]{"XEP-0077: In-Band Registration", "https://xmpp.org/extensions/xep-0077.html"}, new String[]{"XEP-0084: User Avatar", "https://xmpp.org/extensions/xep-0084.html"}, new String[]{"XEP-0085: Chat State Notifications", "https://xmpp.org/extensions/xep-0085.html"}, new String[]{"XEP-0092: Software Version", "https://xmpp.org/extensions/xep-0092.html"}, new String[]{"XEP-0095: Stream Initiation", "https://xmpp.org/extensions/xep-0095.html"}, new String[]{"XEP-0096: SI File Transfer", "https://xmpp.org/extensions/xep-0096.html"}, new String[]{"XEP-0115: Entity Capabilities", "https://xmpp.org/extensions/xep-0115.html"}, new String[]{"XEP-0124: Bidirectional-streams Over Synchronous HTTP (BOSH)", "https://xmpp.org/extensions/xep-0124.html"}, new String[]{"XEP-0138: Stream Compression", "https://xmpp.org/extensions/xep-0138.html"}, new String[]{"XEP-0153: vCard-Based Avatar", "https://xmpp.org/extensions/xep-0153.html"}, new String[]{"XEP-0158: CAPTCHA Forms", "https://xmpp.org/extensions/xep-0158.html"}, new String[]{"XEP-0163: Personal Eventing Protocol (avatars and nicks)", "https://xmpp.org/extensions/xep-0163.html"}, new String[]{"XEP-0166: Jingle", "https://xmpp.org/extensions/xep-0166.html"}, new String[]{"XEP-0167: Jingle RTP Sessions", "https://xmpp.org/extensions/xep-0167.html"}, new String[]{"XEP-0172: User Nickname", "https://xmpp.org/extensions/xep-0172.html"}, new String[]{"XEP-0176: Jingle ICE-UDP Transport Method", "https://xmpp.org/extensions/xep-0176.html"}, new String[]{"XEP-0177: Jingle Raw UDP Transport Method", "https://xmpp.org/extensions/xep-0177.html"}, new String[]{"XEP-0178: Best Practices for Use of SASL EXTERNAL with Certificates", "https://xmpp.org/extensions/xep-0178.html"}, new String[]{"XEP-0184: Message Delivery Receipts", "https://xmpp.org/extensions/xep-0184.html"}, new String[]{"XEP-0191: Blocking command (NI)", "https://xmpp.org/extensions/xep-0191.html"}, new String[]{"XEP-0198: Stream Management", "https://xmpp.org/extensions/xep-0198.html"}, new String[]{"XEP-0199: XMPP Ping", "https://xmpp.org/extensions/xep-0199.html"}, new String[]{"XEP-0203: Delayed Delivery", "https://xmpp.org/extensions/xep-0203.html"}, new String[]{"XEP-0206: XMPP Over BOSH", "https://xmpp.org/extensions/xep-0206.html"}, new String[]{"XEP-0231: Bits of Binary", "https://xmpp.org/extensions/xep-0231.html"}, new String[]{"XEP-0234: Jingle File Transfer", "https://xmpp.org/extensions/xep-0234.html"}, new String[]{"XEP-0237: Roster Versioning", "https://xmpp.org/extensions/xep-0237.html"}, new String[]{"XEP-0249: Direct MUC Invitations", "https://xmpp.org/extensions/xep-0249.html"}, new String[]{"XEP-0251: Jingle Session Transfer", "https://xmpp.org/extensions/xep-0251.html"}, new String[]{"XEP-0260: Jingle SOCKS5 Bytestreams Transport Method", "https://xmpp.org/extensions/xep-0260.html"}, new String[]{"XEP-0261: Jingle In-Band Bytestreams Transport Method", "https://xmpp.org/extensions/xep-0261.html"}, new String[]{"XEP-0262: Use of ZRTP in Jingle RTP Sessions", "https://xmpp.org/extensions/xep-0262.html"}, new String[]{"XEP-0264: File Transfer Thumbnails", "https://xmpp.org/extensions/xep-0264.html"}, new String[]{"XEP-0278: Jingle Relay Nodes", "https://xmpp.org/extensions/xep-0278.html"}, new String[]{"XEP-0280: Message Carbons", "https://xmpp.org/extensions/xep-0280.html"}, new String[]{"XEP-0294: Jingle RTP Header Extensions Negotiation", "https://xmpp.org/extensions/xep-0294.html"}, new String[]{"XEP-0298: Delivering Conference Information to Jingle Participants (Coin)", "https://xmpp.org/extensions/xep-0298.html"}, new String[]{"XEP-0308: Last Message Correction", "https://xmpp.org/extensions/xep-0308.html"}, new String[]{"XEP-0319: Last User Interaction in Presence", "https://xmpp.org/extensions/xep-0319.html"}, new String[]{"XEP-0320: Use of DTLS-SRTP in Jingle Sessions", "https://xmpp.org/extensions/xep-0320.html"}, new String[]{"XEP-0352: Client State Indication", "https://xmpp.org/extensions/xep-052.html"}, new String[]{"XEP-0364: Off-the-Record Messaging (V2/3)", "https://xmpp.org/extensions/xep-0364.html"}, // new String[]{"XEP-0368: SRV records for XMPP over TLS", "https://xmpp.org/extensions/xep-0368.html"}, new String[]{"XEP-0384: OMEMO Encryption", "https://xmpp.org/extensions/xep-0384.html"}, new String[]{"XEP-xxxx: OMEMO Media sharing", "https://xmpp.org/extensions/inbox/omemo-media-sharing.html"}, }; /** * Default CSS styles used to format the change log. */ public static final String DEFAULT_CSS = "h1 { margin-left: 0px; font-size: 1.2em; }" + "\n" + "li { margin-left: 0px; font-size: 0.9em;}" + "\n" + "ul { padding-left: 2em; }"; public void onCreate(Bundle savedInstanceState) { setTheme(aTalkApp.getAppThemeResourceId()); super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_LEFT_ICON); setContentView(R.layout.about); View atakUrl = findViewById(R.id.atalk_link); atakUrl.setOnClickListener(this); TextView atalkHelp = findViewById(R.id.atalk_help); // atalkHelp.setText(Html.fromHtml(getString(R.string.AboutDialog_help))); // atalkHelp.setMovementMethod(LinkMovementMethod.getInstance()); atalkHelp.setTextColor(getResources().getColor(R.color.blue50)); atalkHelp.setOnClickListener(this); findViewById(R.id.ok_button).setOnClickListener(this); findViewById(R.id.history_log).setOnClickListener(this); View btn_submitLogs = findViewById(R.id.submit_logs); btn_submitLogs.setOnClickListener(this); if (BuildConfig.DEBUG) { View btn_update = findViewById(R.id.check_new_version); btn_update.setVisibility(View.VISIBLE); btn_update.setOnClickListener(this); } String aboutInfo = getAboutInfo(); WebView wv = findViewById(R.id.AboutDialog_Info); wv.loadDataWithBaseURL("file:///android_res/drawable/", aboutInfo, "text/html", "utf-8", null); setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_info); setTitle(getString(R.string.AboutDialog_title)); try { PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0); TextView textView = findViewById(R.id.AboutDialog_Version); textView.setText(String.format(getString(R.string.AboutDialog_Version), pi.versionName)); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.ok_button: finish(); break; case R.id.check_new_version: new Thread() { @Override public void run() { UpdateService updateService = ServiceUtils.getService(AndroidGUIActivator.bundleContext, UpdateService.class); if (updateService != null) { updateService.checkForUpdates(true); } } }.start(); break; case R.id.submit_logs: aTalkApp.showSendLogsDialog(); break; case R.id.history_log: ChangeLog cl = new ChangeLog(this, DEFAULT_CSS); cl.getFullLogDialog().show(); break; case R.id.atalk_help: case R.id.atalk_link: atalkUrlAccess(); break; default: finish(); break; } } private void atalkUrlAccess() { String url = getString(R.string.AboutDialog_Link); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } private String getAboutInfo() { StringBuilder html = new StringBuilder() .append("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"/>") .append("<html><head><style type=\"text/css\">") .append(DEFAULT_CSS) .append("</style></head><body>"); StringBuilder xeps = new StringBuilder().append("<ul>"); for (String[] feature : SUPPORTED_XEP) { xeps.append("<li><a href=\"") .append(feature[1]) .append("\">") .append(feature[0]) .append("</a></li>"); } xeps.append("</ul>"); html.append(String.format(getString(R.string.app_xeps), xeps.toString())) .append("</p><hr/><p>"); StringBuilder libs = new StringBuilder().append("<ul>"); for (String[] library : USED_LIBRARIES) { libs.append("<li><a href=\"") .append(library[1]) .append("\">") .append(library[0]) .append("</a></li>"); } libs.append("</ul>"); html.append(String.format(getString(R.string.app_libraries), libs.toString())) .append("</p><hr/><p>"); html.append("</body></html>"); return html.toString(); } }
/* * Copyright 2021 EPAM Systems, Inc * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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.epam.deltix.util.jcg.scg; import com.epam.deltix.util.jcg.*; import java.io.IOException; import static com.epam.deltix.util.jcg.scg.JavaSrcGenContext.*; /** * */ abstract class JExprImplBase implements JExpr, Printable { final JContextImpl context; public JExprImplBase (JContextImpl context) { this.context = context; } @Override public final void print (SourceCodePrinter out) throws IOException { print (JavaOpPriority.OPEN, out); } abstract void print (int outerPriority, SourceCodePrinter out) throws IOException; protected final void printBinary ( int outerPriority, JExprImplBase left, String infix, int thisPriority, InfixAssociation thisAssociation, JExprImplBase right, SourceCodePrinter out ) throws IOException { boolean parenthesize = outerPriority > thisPriority; if (parenthesize) out.print ("("); left.print (thisAssociation == InfixAssociation.LEFT ? thisPriority : thisPriority + 1, out); out.print (infix); right.print (thisAssociation == InfixAssociation.RIGHT ? thisPriority : thisPriority + 1, out); if (parenthesize) out.print (")"); } protected final void printPrefix ( int outerPriority, String prefix, int thisPriority, JExprImplBase right, SourceCodePrinter out ) throws IOException { int intPriority; boolean parenthesize = outerPriority > thisPriority; if (parenthesize) { out.print ("("); intPriority = JavaOpPriority.OPEN; } else intPriority = thisPriority; out.print (prefix); right.print (intPriority, out); if (parenthesize) out.print (")"); } protected final void printPostfix ( int outerPriority, JExprImplBase left, String postfix, int thisPriority, SourceCodePrinter out ) throws IOException { int intPriority; boolean parenthesize = outerPriority > thisPriority; if (parenthesize) { out.print ("("); intPriority = JavaOpPriority.OPEN; } else intPriority = thisPriority; left.print (intPriority, out); out.print (postfix); if (parenthesize) out.print (")"); } abstract static class X2 extends JExprImplBase { protected final JExpr arg; public X2 (JExprImplBase arg) { super (arg.context); this.arg = arg; } } @Override public JExpr cast (final Class<?> toClass) { return ( new X2 (this) { @Override public void print (int outerPriority, SourceCodePrinter out) throws IOException { boolean parenthesize = outerPriority > JavaOpPriority.CAST; int intPriority; if (parenthesize) { out.print ("("); intPriority = JavaOpPriority.OPEN; } else intPriority = JavaOpPriority.CAST; out.print ("("); out.printRefClassName (context.cn1 (toClass)); out.print (")"); ((JExprImplBase) arg).print (intPriority, out); if (parenthesize) out.print (")"); } } ); } @Override public JExpr incAndGet () { return ( new X2 (this) { @Override public void print (int outerPriority, SourceCodePrinter out) throws IOException { printPrefix ( outerPriority, "++", JavaOpPriority.UNARY, (JExprImplBase) arg, out ); } } ); } @Override public JExpr decAndGet () { return ( new X2 (this) { @Override public void print (int outerPriority, SourceCodePrinter out) throws IOException { printPrefix ( outerPriority, "--", JavaOpPriority.UNARY, (JExprImplBase) arg, out ); } } ); } @Override public JExpr getAndInc () { return ( new X2 (this) { @Override public void print (int outerPriority, SourceCodePrinter out) throws IOException { printPostfix ( outerPriority, (JExprImplBase) arg, "++", JavaOpPriority.POSTFIX, out ); } } ); } @Override public JExpr getAndDec () { return ( new X2 (this) { @Override public void print (int outerPriority, SourceCodePrinter out) throws IOException { printPostfix ( outerPriority, (JExprImplBase) arg, "--", JavaOpPriority.POSTFIX, out ); } } ); } @Override public JStatement inc () { return ( new JStatementImplBase (context) { @Override public void printElement (SourceCodePrinter out) throws IOException { out.print (JExprImplBase.this, "++;"); } } ); } @Override public JStatement assign (final JExpr value) { return ( new JStatementImplBase (context) { @Override public void printElement (SourceCodePrinter out) throws IOException { out.print (JExprImplBase.this, " = ", value, ";"); } } ); } @Override public JExpr assignExpr (final JExpr value) { return ( new X2 (this) { @Override public void print (int outerPriority, SourceCodePrinter out) throws IOException { printBinary ( outerPriority, JExprImplBase.this, " = ", JavaOpPriority.ASSIGNMENT, InfixAssociation.RIGHT, (JExprImplBase) value, out ); } } ); } @Override public JStatement dec () { return ( new JStatementImplBase (context) { @Override public void printElement (SourceCodePrinter out) throws IOException { out.print (JExprImplBase.this, "--;"); } } ); } @Override public JStatement alter (final String op, final JExpr arg) { return ( new JStatementImplBase (context) { @Override public void printElement (SourceCodePrinter out) throws IOException { out.print (JExprImplBase.this, " ", op, " ", arg, ";"); } } ); } @Override public JExpr cast (final JType toClass) { return ( new X2 (this) { @Override public void print (int outerPriority, SourceCodePrinter out) throws IOException { boolean parenthesize = outerPriority > JavaOpPriority.CAST; int intPriority; if (parenthesize) { out.print ("("); intPriority = JavaOpPriority.OPEN; } else intPriority = JavaOpPriority.CAST; out.print ("("); out.printRefClassName (cn (toClass)); out.print (")"); ((JExprImplBase) arg).print (intPriority, out); if (parenthesize) out.print (")"); } } ); } @Override public JExpr not () { return ( new X2 (this) { @Override public void print (int outerPriority, SourceCodePrinter out) throws IOException { printPrefix (outerPriority, "!", JavaOpPriority.UNARY, (JExprImplBase) arg, out); } } ); } @Override public JStatement throwStmt () { return ( new JStatementImplBase (context) { @Override public void printElement (SourceCodePrinter out) throws IOException { out.print ("throw ", JExprImplBase.this, ";"); } } ); } @Override public JStatement returnStmt () { return ( new JStatementImplBase (context) { @Override public void printElement (SourceCodePrinter out) throws IOException { out.print ("return ", JExprImplBase.this, ";"); } } ); } @Override public JStatement asStmt () { return (etos (this)); } @Override public JExpr call (final String method, final JExpr ... args) { return ( new X2 (this) { @Override public void print (int outerPriority, SourceCodePrinter out) throws IOException { int intPriority; boolean parenthesize = outerPriority > JavaOpPriority.POSTFIX; if (parenthesize) { out.print ("("); intPriority = JavaOpPriority.OPEN; } else intPriority = JavaOpPriority.POSTFIX; ((JExprImplBase) arg).print (intPriority, out); out.print (".", method, " ("); px (out, args); out.print (")"); if (parenthesize) out.print (")"); } } ); } @Override public JExpr index (final JExpr index) { return ( new X2 (this) { @Override public void print (int outerPriority, SourceCodePrinter out) throws IOException { int intPriority; boolean parenthesize = outerPriority > JavaOpPriority.POSTFIX; if (parenthesize) { out.print ("("); intPriority = JavaOpPriority.OPEN; } else intPriority = JavaOpPriority.POSTFIX; ((JExprImplBase) arg).print (intPriority, out); out.print ("[", index, "]"); if (parenthesize) out.print (")"); } } ); } @Override public JExpr index (final int index) { return (index (context.mkint (index))); } @Override public JExpr field (final String fieldId) { return ( new X2 (this) { @Override public void print (int outerPriority, SourceCodePrinter out) throws IOException { printPostfix ( outerPriority, (JExprImplBase) arg, "." + fieldId, JavaOpPriority.POSTFIX, out ); } } ); } @Override public JSwitchStatement switchStmt () { return (switchStmt (null)); } @Override public JSwitchStatement switchStmt (String label) { return (new JSwitchStatementImpl (label, this)); } }
package bf.stock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.Date; import java.util.List; /** * Created by Administrator on 2015/12/1. */ @Component public class StockBaseTask extends WebServiceTask { private static Logger logger = LoggerFactory.getLogger(StockBaseTask.class); public static void main(String[] args) { } public void populate() { List<String> stocks = jdbcTemplate.queryForList("select id from stock_base", String.class); logger.info("total stocks:{}", stocks.size()); stocks.parallelStream().forEach(id -> { boolean exist = isExist(id, new Date()); if (exist) return; jdbcTemplate.update("insert into stock(id) values(?)", id); }); } }
/* * 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.cassandra.db.compaction; import java.util.ArrayList; import java.util.UUID; import org.junit.Test; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.repair.AbstractPendingAntiCompactionTest; import org.apache.cassandra.schema.MockSchema; import org.apache.cassandra.schema.TableId; import org.assertj.core.api.Assertions; public class AbstractTableOperationTest extends AbstractPendingAntiCompactionTest { @Test public void testAbstractTableOperationToStringContainsTaskId() { ColumnFamilyStore cfs = MockSchema.newCFS(); UUID expectedTaskId = UUID.randomUUID(); AbstractTableOperation.OperationProgress task = new AbstractTableOperation.OperationProgress(cfs.metadata(), OperationType.COMPACTION, 0, 1000, expectedTaskId, new ArrayList<>()); Assertions.assertThat(task.toString()) .contains(expectedTaskId.toString()); } @Test public void testCompactionInfoToStringFormat() { UUID tableId = UUID.randomUUID(); UUID taskId = UUID.randomUUID(); ColumnFamilyStore cfs = MockSchema.newCFS(builder -> builder.id(TableId.fromUUID(tableId))); AbstractTableOperation.OperationProgress task = new AbstractTableOperation.OperationProgress(cfs.metadata(), OperationType.COMPACTION, 0, 1000, taskId, new ArrayList<>()); Assertions.assertThat(task.toString()) .isEqualTo("Compaction(%s, 0 / 1000 bytes)@%s(%s, %s)", taskId, tableId, cfs.getKeyspaceName(), cfs.getTableName()); } }
/* * Copyright (c) 2020, GoMint, BlackyPaw and geNAZt * * This code is licensed under the BSD license found in the * LICENSE file in the root directory of this source tree. */ package io.gomint.inventory.item; import io.gomint.GoMint; /** * @author geNAZt * @version 1.0 * @stability 1 */ public interface ItemPiglinBruteSpawnEgg extends ItemStack<ItemPiglinBruteSpawnEgg> { /** * Create a new item stack with given class and amount * * @param amount which is used for the creation * @return freshly generated item */ static ItemPiglinBruteSpawnEgg create( int amount ) { return GoMint.instance().createItemStack( ItemPiglinBruteSpawnEgg.class, amount ); } }
/* * Copyright (C) 2006 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 android.content; import android.annotation.AttrRes; import android.annotation.CheckResult; import android.annotation.ColorInt; import android.annotation.ColorRes; import android.annotation.DrawableRes; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.RequiresPermission; import android.annotation.StringDef; import android.annotation.StringRes; import android.annotation.StyleRes; import android.annotation.StyleableRes; import android.annotation.SystemApi; import android.annotation.TestApi; import android.annotation.UserIdInt; import android.app.IApplicationThread; import android.app.IServiceConnection; import android.app.VrManager; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.content.res.ColorStateList; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.StatFs; import android.os.UserHandle; import android.os.UserManager; import android.os.storage.StorageManager; import android.provider.MediaStore; import android.util.AttributeSet; import android.view.Display; import android.view.DisplayAdjustments; import android.view.View; import android.view.ViewDebug; import android.view.WindowManager; import android.view.autofill.AutofillManager.AutofillClient; import android.view.textclassifier.TextClassificationManager; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Interface to global information about an application environment. This is * an abstract class whose implementation is provided by * the Android system. It * allows access to application-specific resources and classes, as well as * up-calls for application-level operations such as launching activities, * broadcasting and receiving intents, etc. */ public abstract class Context { /** @hide */ @IntDef(flag = true, prefix = { "MODE_" }, value = { MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE, MODE_APPEND, }) @Retention(RetentionPolicy.SOURCE) public @interface FileMode {} /** @hide */ @IntDef(flag = true, prefix = { "MODE_" }, value = { MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE, MODE_MULTI_PROCESS, }) @Retention(RetentionPolicy.SOURCE) public @interface PreferencesMode {} /** @hide */ @IntDef(flag = true, prefix = { "MODE_" }, value = { MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE, MODE_ENABLE_WRITE_AHEAD_LOGGING, MODE_NO_LOCALIZED_COLLATORS, }) @Retention(RetentionPolicy.SOURCE) public @interface DatabaseMode {} /** * File creation mode: the default mode, where the created file can only * be accessed by the calling application (or all applications sharing the * same user ID). */ public static final int MODE_PRIVATE = 0x0000; /** * File creation mode: allow all other applications to have read access to * the created file. * <p> * Starting from {@link android.os.Build.VERSION_CODES#N}, attempting to use this * mode throws a {@link SecurityException}. * * @deprecated Creating world-readable files is very dangerous, and likely * to cause security holes in applications. It is strongly * discouraged; instead, applications should use more formal * mechanism for interactions such as {@link ContentProvider}, * {@link BroadcastReceiver}, and {@link android.app.Service}. * There are no guarantees that this access mode will remain on * a file, such as when it goes through a backup and restore. * @see android.support.v4.content.FileProvider * @see Intent#FLAG_GRANT_WRITE_URI_PERMISSION */ @Deprecated public static final int MODE_WORLD_READABLE = 0x0001; /** * File creation mode: allow all other applications to have write access to * the created file. * <p> * Starting from {@link android.os.Build.VERSION_CODES#N}, attempting to use this * mode will throw a {@link SecurityException}. * * @deprecated Creating world-writable files is very dangerous, and likely * to cause security holes in applications. It is strongly * discouraged; instead, applications should use more formal * mechanism for interactions such as {@link ContentProvider}, * {@link BroadcastReceiver}, and {@link android.app.Service}. * There are no guarantees that this access mode will remain on * a file, such as when it goes through a backup and restore. * @see android.support.v4.content.FileProvider * @see Intent#FLAG_GRANT_WRITE_URI_PERMISSION */ @Deprecated public static final int MODE_WORLD_WRITEABLE = 0x0002; /** * File creation mode: for use with {@link #openFileOutput}, if the file * already exists then write data to the end of the existing file * instead of erasing it. * @see #openFileOutput */ public static final int MODE_APPEND = 0x8000; /** * SharedPreference loading flag: when set, the file on disk will * be checked for modification even if the shared preferences * instance is already loaded in this process. This behavior is * sometimes desired in cases where the application has multiple * processes, all writing to the same SharedPreferences file. * Generally there are better forms of communication between * processes, though. * * <p>This was the legacy (but undocumented) behavior in and * before Gingerbread (Android 2.3) and this flag is implied when * targetting such releases. For applications targetting SDK * versions <em>greater than</em> Android 2.3, this flag must be * explicitly set if desired. * * @see #getSharedPreferences * * @deprecated MODE_MULTI_PROCESS does not work reliably in * some versions of Android, and furthermore does not provide any * mechanism for reconciling concurrent modifications across * processes. Applications should not attempt to use it. Instead, * they should use an explicit cross-process data management * approach such as {@link android.content.ContentProvider ContentProvider}. */ @Deprecated public static final int MODE_MULTI_PROCESS = 0x0004; /** * Database open flag: when set, the database is opened with write-ahead * logging enabled by default. * * @see #openOrCreateDatabase(String, int, CursorFactory) * @see #openOrCreateDatabase(String, int, CursorFactory, DatabaseErrorHandler) * @see SQLiteDatabase#enableWriteAheadLogging */ public static final int MODE_ENABLE_WRITE_AHEAD_LOGGING = 0x0008; /** * Database open flag: when set, the database is opened without support for * localized collators. * * @see #openOrCreateDatabase(String, int, CursorFactory) * @see #openOrCreateDatabase(String, int, CursorFactory, DatabaseErrorHandler) * @see SQLiteDatabase#NO_LOCALIZED_COLLATORS */ public static final int MODE_NO_LOCALIZED_COLLATORS = 0x0010; /** @hide */ @IntDef(flag = true, value = { BIND_AUTO_CREATE, BIND_DEBUG_UNBIND, BIND_NOT_FOREGROUND, BIND_ABOVE_CLIENT, BIND_ALLOW_OOM_MANAGEMENT, BIND_WAIVE_PRIORITY, BIND_IMPORTANT, BIND_ADJUST_WITH_ACTIVITY }) @Retention(RetentionPolicy.SOURCE) public @interface BindServiceFlags {} /** * Flag for {@link #bindService}: automatically create the service as long * as the binding exists. Note that while this will create the service, * its {@link android.app.Service#onStartCommand} * method will still only be called due to an * explicit call to {@link #startService}. Even without that, though, * this still provides you with access to the service object while the * service is created. * * <p>Note that prior to {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}, * not supplying this flag would also impact how important the system * consider's the target service's process to be. When set, the only way * for it to be raised was by binding from a service in which case it will * only be important when that activity is in the foreground. Now to * achieve this behavior you must explicitly supply the new flag * {@link #BIND_ADJUST_WITH_ACTIVITY}. For compatibility, old applications * that don't specify {@link #BIND_AUTO_CREATE} will automatically have * the flags {@link #BIND_WAIVE_PRIORITY} and * {@link #BIND_ADJUST_WITH_ACTIVITY} set for them in order to achieve * the same result. */ public static final int BIND_AUTO_CREATE = 0x0001; /** * Flag for {@link #bindService}: include debugging help for mismatched * calls to unbind. When this flag is set, the callstack of the following * {@link #unbindService} call is retained, to be printed if a later * incorrect unbind call is made. Note that doing this requires retaining * information about the binding that was made for the lifetime of the app, * resulting in a leak -- this should only be used for debugging. */ public static final int BIND_DEBUG_UNBIND = 0x0002; /** * Flag for {@link #bindService}: don't allow this binding to raise * the target service's process to the foreground scheduling priority. * It will still be raised to at least the same memory priority * as the client (so that its process will not be killable in any * situation where the client is not killable), but for CPU scheduling * purposes it may be left in the background. This only has an impact * in the situation where the binding client is a foreground process * and the target service is in a background process. */ public static final int BIND_NOT_FOREGROUND = 0x0004; /** * Flag for {@link #bindService}: indicates that the client application * binding to this service considers the service to be more important than * the app itself. When set, the platform will try to have the out of * memory killer kill the app before it kills the service it is bound to, though * this is not guaranteed to be the case. */ public static final int BIND_ABOVE_CLIENT = 0x0008; /** * Flag for {@link #bindService}: allow the process hosting the bound * service to go through its normal memory management. It will be * treated more like a running service, allowing the system to * (temporarily) expunge the process if low on memory or for some other * whim it may have, and being more aggressive about making it a candidate * to be killed (and restarted) if running for a long time. */ public static final int BIND_ALLOW_OOM_MANAGEMENT = 0x0010; /** * Flag for {@link #bindService}: don't impact the scheduling or * memory management priority of the target service's hosting process. * Allows the service's process to be managed on the background LRU list * just like a regular application process in the background. */ public static final int BIND_WAIVE_PRIORITY = 0x0020; /** * Flag for {@link #bindService}: this service is very important to * the client, so should be brought to the foreground process level * when the client is. Normally a process can only be raised to the * visibility level by a client, even if that client is in the foreground. */ public static final int BIND_IMPORTANT = 0x0040; /** * Flag for {@link #bindService}: If binding from an activity, allow the * target service's process importance to be raised based on whether the * activity is visible to the user, regardless whether another flag is * used to reduce the amount that the client process's overall importance * is used to impact it. */ public static final int BIND_ADJUST_WITH_ACTIVITY = 0x0080; /** * @hide Flag for {@link #bindService}: like {@link #BIND_NOT_FOREGROUND}, but puts it * up in to the important background state (instead of transient). */ public static final int BIND_IMPORTANT_BACKGROUND = 0x00800000; /** * @hide Flag for {@link #bindService}: allows application hosting service to manage whitelists * such as temporary allowing a {@code PendingIntent} to bypass Power Save mode. */ public static final int BIND_ALLOW_WHITELIST_MANAGEMENT = 0x01000000; /** * @hide Flag for {@link #bindService}: Like {@link #BIND_FOREGROUND_SERVICE}, * but only applies while the device is awake. */ public static final int BIND_FOREGROUND_SERVICE_WHILE_AWAKE = 0x02000000; /** * @hide Flag for {@link #bindService}: For only the case where the binding * is coming from the system, set the process state to FOREGROUND_SERVICE * instead of the normal maximum of IMPORTANT_FOREGROUND. That is, this is * saying that the process shouldn't participate in the normal power reduction * modes (removing network access etc). */ public static final int BIND_FOREGROUND_SERVICE = 0x04000000; /** * @hide Flag for {@link #bindService}: Treat the binding as hosting * an activity, an unbinding as the activity going in the background. * That is, when unbinding, the process when empty will go on the activity * LRU list instead of the regular one, keeping it around more aggressively * than it otherwise would be. This is intended for use with IMEs to try * to keep IME processes around for faster keyboard switching. */ public static final int BIND_TREAT_LIKE_ACTIVITY = 0x08000000; /** * @hide An idea that is not yet implemented. * Flag for {@link #bindService}: If binding from an activity, consider * this service to be visible like the binding activity is. That is, * it will be treated as something more important to keep around than * invisible background activities. This will impact the number of * recent activities the user can switch between without having them * restart. There is no guarantee this will be respected, as the system * tries to balance such requests from one app vs. the importantance of * keeping other apps around. */ public static final int BIND_VISIBLE = 0x10000000; /** * @hide * Flag for {@link #bindService}: Consider this binding to be causing the target * process to be showing UI, so it will be do a UI_HIDDEN memory trim when it goes * away. */ public static final int BIND_SHOWING_UI = 0x20000000; /** * Flag for {@link #bindService}: Don't consider the bound service to be * visible, even if the caller is visible. * @hide */ public static final int BIND_NOT_VISIBLE = 0x40000000; /** * Flag for {@link #bindService}: The service being bound is an * {@link android.R.attr#isolatedProcess isolated}, * {@link android.R.attr#externalService external} service. This binds the service into the * calling application's package, rather than the package in which the service is declared. * <p> * When using this flag, the code for the service being bound will execute under the calling * application's package name and user ID. Because the service must be an isolated process, * it will not have direct access to the application's data, though. * * The purpose of this flag is to allow applications to provide services that are attributed * to the app using the service, rather than the application providing the service. * </p> */ public static final int BIND_EXTERNAL_SERVICE = 0x80000000; /** @hide */ @IntDef(flag = true, value = { RECEIVER_VISIBLE_TO_INSTANT_APPS }) @Retention(RetentionPolicy.SOURCE) public @interface RegisterReceiverFlags {} /** * Flag for {@link #registerReceiver}: The receiver can receive broadcasts from Instant Apps. */ public static final int RECEIVER_VISIBLE_TO_INSTANT_APPS = 0x1; /** * Returns an AssetManager instance for the application's package. * <p> * <strong>Note:</strong> Implementations of this method should return * an AssetManager instance that is consistent with the Resources instance * returned by {@link #getResources()}. For example, they should share the * same {@link Configuration} object. * * @return an AssetManager instance for the application's package * @see #getResources() */ public abstract AssetManager getAssets(); /** * Returns a Resources instance for the application's package. * <p> * <strong>Note:</strong> Implementations of this method should return * a Resources instance that is consistent with the AssetManager instance * returned by {@link #getAssets()}. For example, they should share the * same {@link Configuration} object. * * @return a Resources instance for the application's package * @see #getAssets() */ public abstract Resources getResources(); /** Return PackageManager instance to find global package information. */ public abstract PackageManager getPackageManager(); /** Return a ContentResolver instance for your application's package. */ public abstract ContentResolver getContentResolver(); /** * Return the Looper for the main thread of the current process. This is * the thread used to dispatch calls to application components (activities, * services, etc). * <p> * By definition, this method returns the same result as would be obtained * by calling {@link Looper#getMainLooper() Looper.getMainLooper()}. * </p> * * @return The main looper. */ public abstract Looper getMainLooper(); /** * Return the context of the single, global Application object of the * current process. This generally should only be used if you need a * Context whose lifecycle is separate from the current context, that is * tied to the lifetime of the process rather than the current component. * * <p>Consider for example how this interacts with * {@link #registerReceiver(BroadcastReceiver, IntentFilter)}: * <ul> * <li> <p>If used from an Activity context, the receiver is being registered * within that activity. This means that you are expected to unregister * before the activity is done being destroyed; in fact if you do not do * so, the framework will clean up your leaked registration as it removes * the activity and log an error. Thus, if you use the Activity context * to register a receiver that is static (global to the process, not * associated with an Activity instance) then that registration will be * removed on you at whatever point the activity you used is destroyed. * <li> <p>If used from the Context returned here, the receiver is being * registered with the global state associated with your application. Thus * it will never be unregistered for you. This is necessary if the receiver * is associated with static data, not a particular component. However * using the ApplicationContext elsewhere can easily lead to serious leaks * if you forget to unregister, unbind, etc. * </ul> */ public abstract Context getApplicationContext(); /** Non-activity related autofill ids are unique in the app */ private static int sLastAutofillId = View.NO_ID; /** * Gets the next autofill ID. * * <p>All IDs will be smaller or the same as {@link View#LAST_APP_AUTOFILL_ID}. All IDs * returned will be unique. * * @return A ID that is unique in the process * * {@hide} */ public int getNextAutofillId() { if (sLastAutofillId == View.LAST_APP_AUTOFILL_ID - 1) { sLastAutofillId = View.NO_ID; } sLastAutofillId++; return sLastAutofillId; } /** * Add a new {@link ComponentCallbacks} to the base application of the * Context, which will be called at the same times as the ComponentCallbacks * methods of activities and other components are called. Note that you * <em>must</em> be sure to use {@link #unregisterComponentCallbacks} when * appropriate in the future; this will not be removed for you. * * @param callback The interface to call. This can be either a * {@link ComponentCallbacks} or {@link ComponentCallbacks2} interface. */ public void registerComponentCallbacks(ComponentCallbacks callback) { getApplicationContext().registerComponentCallbacks(callback); } /** * Remove a {@link ComponentCallbacks} object that was previously registered * with {@link #registerComponentCallbacks(ComponentCallbacks)}. */ public void unregisterComponentCallbacks(ComponentCallbacks callback) { getApplicationContext().unregisterComponentCallbacks(callback); } /** * Return a localized, styled CharSequence from the application's package's * default string table. * * @param resId Resource id for the CharSequence text */ public final CharSequence getText(@StringRes int resId) { return getResources().getText(resId); } /** * Returns a localized string from the application's package's * default string table. * * @param resId Resource id for the string * @return The string data associated with the resource, stripped of styled * text information. */ @NonNull public final String getString(@StringRes int resId) { return getResources().getString(resId); } /** * Returns a localized formatted string from the application's package's * default string table, substituting the format arguments as defined in * {@link java.util.Formatter} and {@link java.lang.String#format}. * * @param resId Resource id for the format string * @param formatArgs The format arguments that will be used for * substitution. * @return The string data associated with the resource, formatted and * stripped of styled text information. */ @NonNull public final String getString(@StringRes int resId, Object... formatArgs) { return getResources().getString(resId, formatArgs); } /** * Returns a color associated with a particular resource ID and styled for * the current theme. * * @param id The desired resource identifier, as generated by the aapt * tool. This integer encodes the package, type, and resource * entry. The value 0 is an invalid identifier. * @return A single color value in the form 0xAARRGGBB. * @throws android.content.res.Resources.NotFoundException if the given ID * does not exist. */ @ColorInt public final int getColor(@ColorRes int id) { return getResources().getColor(id, getTheme()); } /** * Returns a drawable object associated with a particular resource ID and * styled for the current theme. * * @param id The desired resource identifier, as generated by the aapt * tool. This integer encodes the package, type, and resource * entry. The value 0 is an invalid identifier. * @return An object that can be used to draw this resource, or * {@code null} if the resource could not be resolved. * @throws android.content.res.Resources.NotFoundException if the given ID * does not exist. */ @Nullable public final Drawable getDrawable(@DrawableRes int id) { return getResources().getDrawable(id, getTheme()); } /** * Returns a color state list associated with a particular resource ID and * styled for the current theme. * * @param id The desired resource identifier, as generated by the aapt * tool. This integer encodes the package, type, and resource * entry. The value 0 is an invalid identifier. * @return A color state list, or {@code null} if the resource could not be * resolved. * @throws android.content.res.Resources.NotFoundException if the given ID * does not exist. */ @Nullable public final ColorStateList getColorStateList(@ColorRes int id) { return getResources().getColorStateList(id, getTheme()); } /** * Set the base theme for this context. Note that this should be called * before any views are instantiated in the Context (for example before * calling {@link android.app.Activity#setContentView} or * {@link android.view.LayoutInflater#inflate}). * * @param resid The style resource describing the theme. */ public abstract void setTheme(@StyleRes int resid); /** @hide Needed for some internal implementation... not public because * you can't assume this actually means anything. */ public int getThemeResId() { return 0; } /** * Return the Theme object associated with this Context. */ @ViewDebug.ExportedProperty(deepExport = true) public abstract Resources.Theme getTheme(); /** * Retrieve styled attribute information in this Context's theme. See * {@link android.content.res.Resources.Theme#obtainStyledAttributes(int[])} * for more information. * * @see android.content.res.Resources.Theme#obtainStyledAttributes(int[]) */ public final TypedArray obtainStyledAttributes(@StyleableRes int[] attrs) { return getTheme().obtainStyledAttributes(attrs); } /** * Retrieve styled attribute information in this Context's theme. See * {@link android.content.res.Resources.Theme#obtainStyledAttributes(int, int[])} * for more information. * * @see android.content.res.Resources.Theme#obtainStyledAttributes(int, int[]) */ public final TypedArray obtainStyledAttributes( @StyleRes int resid, @StyleableRes int[] attrs) throws Resources.NotFoundException { return getTheme().obtainStyledAttributes(resid, attrs); } /** * Retrieve styled attribute information in this Context's theme. See * {@link android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int)} * for more information. * * @see android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int) */ public final TypedArray obtainStyledAttributes( AttributeSet set, @StyleableRes int[] attrs) { return getTheme().obtainStyledAttributes(set, attrs, 0, 0); } /** * Retrieve styled attribute information in this Context's theme. See * {@link android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int)} * for more information. * * @see android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int) */ public final TypedArray obtainStyledAttributes( AttributeSet set, @StyleableRes int[] attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) { return getTheme().obtainStyledAttributes( set, attrs, defStyleAttr, defStyleRes); } /** * Return a class loader you can use to retrieve classes in this package. */ public abstract ClassLoader getClassLoader(); /** Return the name of this application's package. */ public abstract String getPackageName(); /** @hide Return the name of the base context this context is derived from. */ public abstract String getBasePackageName(); /** @hide Return the package name that should be used for app ops calls from * this context. This is the same as {@link #getBasePackageName()} except in * cases where system components are loaded into other app processes, in which * case this will be the name of the primary package in that process (so that app * ops uid verification will work with the name). */ public abstract String getOpPackageName(); /** Return the full application info for this context's package. */ public abstract ApplicationInfo getApplicationInfo(); /** * Return the full path to this context's primary Android package. * The Android package is a ZIP file which contains the application's * primary resources. * * <p>Note: this is not generally useful for applications, since they should * not be directly accessing the file system. * * @return String Path to the resources. */ public abstract String getPackageResourcePath(); /** * Return the full path to this context's primary Android package. * The Android package is a ZIP file which contains application's * primary code and assets. * * <p>Note: this is not generally useful for applications, since they should * not be directly accessing the file system. * * @return String Path to the code and assets. */ public abstract String getPackageCodePath(); /** * @hide * @deprecated use {@link #getSharedPreferencesPath(String)} */ @Deprecated public File getSharedPrefsFile(String name) { return getSharedPreferencesPath(name); } /** * Retrieve and hold the contents of the preferences file 'name', returning * a SharedPreferences through which you can retrieve and modify its * values. Only one instance of the SharedPreferences object is returned * to any callers for the same name, meaning they will see each other's * edits as soon as they are made. * * @param name Desired preferences file. If a preferences file by this name * does not exist, it will be created when you retrieve an * editor (SharedPreferences.edit()) and then commit changes (Editor.commit()). * @param mode Operating mode. * * @return The single {@link SharedPreferences} instance that can be used * to retrieve and modify the preference values. * * @see #MODE_PRIVATE */ public abstract SharedPreferences getSharedPreferences(String name, @PreferencesMode int mode); /** * Retrieve and hold the contents of the preferences file, returning * a SharedPreferences through which you can retrieve and modify its * values. Only one instance of the SharedPreferences object is returned * to any callers for the same name, meaning they will see each other's * edits as soon as they are made. * * @param file Desired preferences file. If a preferences file by this name * does not exist, it will be created when you retrieve an * editor (SharedPreferences.edit()) and then commit changes (Editor.commit()). * @param mode Operating mode. * * @return The single {@link SharedPreferences} instance that can be used * to retrieve and modify the preference values. * * @see #getSharedPreferencesPath(String) * @see #MODE_PRIVATE * @removed */ public abstract SharedPreferences getSharedPreferences(File file, @PreferencesMode int mode); /** * Move an existing shared preferences file from the given source storage * context to this context. This is typically used to migrate data between * storage locations after an upgrade, such as moving to device protected * storage. * * @param sourceContext The source context which contains the existing * shared preferences to move. * @param name The name of the shared preferences file. * @return {@code true} if the move was successful or if the shared * preferences didn't exist in the source context, otherwise * {@code false}. * @see #createDeviceProtectedStorageContext() */ public abstract boolean moveSharedPreferencesFrom(Context sourceContext, String name); /** * Delete an existing shared preferences file. * * @param name The name (unique in the application package) of the shared * preferences file. * @return {@code true} if the shared preferences file was successfully * deleted; else {@code false}. * @see #getSharedPreferences(String, int) */ public abstract boolean deleteSharedPreferences(String name); /** @hide */ public abstract void reloadSharedPreferences(); /** * Open a private file associated with this Context's application package * for reading. * * @param name The name of the file to open; can not contain path * separators. * * @return The resulting {@link FileInputStream}. * * @see #openFileOutput * @see #fileList * @see #deleteFile * @see java.io.FileInputStream#FileInputStream(String) */ public abstract FileInputStream openFileInput(String name) throws FileNotFoundException; /** * Open a private file associated with this Context's application package * for writing. Creates the file if it doesn't already exist. * <p> * No additional permissions are required for the calling app to read or * write the returned file. * * @param name The name of the file to open; can not contain path * separators. * @param mode Operating mode. * @return The resulting {@link FileOutputStream}. * @see #MODE_APPEND * @see #MODE_PRIVATE * @see #openFileInput * @see #fileList * @see #deleteFile * @see java.io.FileOutputStream#FileOutputStream(String) */ public abstract FileOutputStream openFileOutput(String name, @FileMode int mode) throws FileNotFoundException; /** * Delete the given private file associated with this Context's * application package. * * @param name The name of the file to delete; can not contain path * separators. * * @return {@code true} if the file was successfully deleted; else * {@code false}. * * @see #openFileInput * @see #openFileOutput * @see #fileList * @see java.io.File#delete() */ public abstract boolean deleteFile(String name); /** * Returns the absolute path on the filesystem where a file created with * {@link #openFileOutput} is stored. * <p> * The returned path may change over time if the calling app is moved to an * adopted storage device, so only relative paths should be persisted. * * @param name The name of the file for which you would like to get * its path. * * @return An absolute path to the given file. * * @see #openFileOutput * @see #getFilesDir * @see #getDir */ public abstract File getFileStreamPath(String name); /** * Returns the absolute path on the filesystem where a file created with * {@link #getSharedPreferences(String, int)} is stored. * <p> * The returned path may change over time if the calling app is moved to an * adopted storage device, so only relative paths should be persisted. * * @param name The name of the shared preferences for which you would like * to get a path. * @return An absolute path to the given file. * @see #getSharedPreferences(String, int) * @removed */ public abstract File getSharedPreferencesPath(String name); /** * Returns the absolute path to the directory on the filesystem where all * private files belonging to this app are stored. Apps should not use this * path directly; they should instead use {@link #getFilesDir()}, * {@link #getCacheDir()}, {@link #getDir(String, int)}, or other storage * APIs on this class. * <p> * The returned path may change over time if the calling app is moved to an * adopted storage device, so only relative paths should be persisted. * <p> * No additional permissions are required for the calling app to read or * write files under the returned path. * * @see ApplicationInfo#dataDir */ public abstract File getDataDir(); /** * Returns the absolute path to the directory on the filesystem where files * created with {@link #openFileOutput} are stored. * <p> * The returned path may change over time if the calling app is moved to an * adopted storage device, so only relative paths should be persisted. * <p> * No additional permissions are required for the calling app to read or * write files under the returned path. * * @return The path of the directory holding application files. * @see #openFileOutput * @see #getFileStreamPath * @see #getDir */ public abstract File getFilesDir(); /** * Returns the absolute path to the directory on the filesystem similar to * {@link #getFilesDir()}. The difference is that files placed under this * directory will be excluded from automatic backup to remote storage. See * {@link android.app.backup.BackupAgent BackupAgent} for a full discussion * of the automatic backup mechanism in Android. * <p> * The returned path may change over time if the calling app is moved to an * adopted storage device, so only relative paths should be persisted. * <p> * No additional permissions are required for the calling app to read or * write files under the returned path. * * @return The path of the directory holding application files that will not * be automatically backed up to remote storage. * @see #openFileOutput * @see #getFileStreamPath * @see #getDir * @see android.app.backup.BackupAgent */ public abstract File getNoBackupFilesDir(); /** * Returns the absolute path to the directory on the primary shared/external * storage device where the application can place persistent files it owns. * These files are internal to the applications, and not typically visible * to the user as media. * <p> * This is like {@link #getFilesDir()} in that these files will be deleted * when the application is uninstalled, however there are some important * differences: * <ul> * <li>Shared storage may not always be available, since removable media can * be ejected by the user. Media state can be checked using * {@link Environment#getExternalStorageState(File)}. * <li>There is no security enforced with these files. For example, any * application holding * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to * these files. * </ul> * <p> * If a shared storage device is emulated (as determined by * {@link Environment#isExternalStorageEmulated(File)}), it's contents are * backed by a private user data partition, which means there is little * benefit to storing data here instead of the private directories returned * by {@link #getFilesDir()}, etc. * <p> * Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, no permissions * are required to read or write to the returned path; it's always * accessible to the calling app. This only applies to paths generated for * package name of the calling application. To access paths belonging to * other packages, * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} and/or * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} are required. * <p> * On devices with multiple users (as described by {@link UserManager}), * each user has their own isolated shared storage. Applications only have * access to the shared storage for the user they're running as. * <p> * The returned path may change over time if different shared storage media * is inserted, so only relative paths should be persisted. * <p> * Here is an example of typical code to manipulate a file in an * application's shared storage: * </p> * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java * private_file} * <p> * If you supply a non-null <var>type</var> to this function, the returned * file will be a path to a sub-directory of the given type. Though these * files are not automatically scanned by the media scanner, you can * explicitly add them to the media database with * {@link android.media.MediaScannerConnection#scanFile(Context, String[], String[], android.media.MediaScannerConnection.OnScanCompletedListener) * MediaScannerConnection.scanFile}. Note that this is not the same as * {@link android.os.Environment#getExternalStoragePublicDirectory * Environment.getExternalStoragePublicDirectory()}, which provides * directories of media shared by all applications. The directories returned * here are owned by the application, and their contents will be removed * when the application is uninstalled. Unlike * {@link android.os.Environment#getExternalStoragePublicDirectory * Environment.getExternalStoragePublicDirectory()}, the directory returned * here will be automatically created for you. * <p> * Here is an example of typical code to manipulate a picture in an * application's shared storage and add it to the media database: * </p> * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java * private_picture} * * @param type The type of files directory to return. May be {@code null} * for the root of the files directory or one of the following * constants for a subdirectory: * {@link android.os.Environment#DIRECTORY_MUSIC}, * {@link android.os.Environment#DIRECTORY_PODCASTS}, * {@link android.os.Environment#DIRECTORY_RINGTONES}, * {@link android.os.Environment#DIRECTORY_ALARMS}, * {@link android.os.Environment#DIRECTORY_NOTIFICATIONS}, * {@link android.os.Environment#DIRECTORY_PICTURES}, or * {@link android.os.Environment#DIRECTORY_MOVIES}. * @return the absolute path to application-specific directory. May return * {@code null} if shared storage is not currently available. * @see #getFilesDir * @see #getExternalFilesDirs(String) * @see Environment#getExternalStorageState(File) * @see Environment#isExternalStorageEmulated(File) * @see Environment#isExternalStorageRemovable(File) */ @Nullable public abstract File getExternalFilesDir(@Nullable String type); /** * Returns absolute paths to application-specific directories on all * shared/external storage devices where the application can place * persistent files it owns. These files are internal to the application, * and not typically visible to the user as media. * <p> * This is like {@link #getFilesDir()} in that these files will be deleted * when the application is uninstalled, however there are some important * differences: * <ul> * <li>Shared storage may not always be available, since removable media can * be ejected by the user. Media state can be checked using * {@link Environment#getExternalStorageState(File)}. * <li>There is no security enforced with these files. For example, any * application holding * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to * these files. * </ul> * <p> * If a shared storage device is emulated (as determined by * {@link Environment#isExternalStorageEmulated(File)}), it's contents are * backed by a private user data partition, which means there is little * benefit to storing data here instead of the private directories returned * by {@link #getFilesDir()}, etc. * <p> * Shared storage devices returned here are considered a stable part of the * device, including physical media slots under a protective cover. The * returned paths do not include transient devices, such as USB flash drives * connected to handheld devices. * <p> * An application may store data on any or all of the returned devices. For * example, an app may choose to store large files on the device with the * most available space, as measured by {@link StatFs}. * <p> * No additional permissions are required for the calling app to read or * write files under the returned path. Write access outside of these paths * on secondary external storage devices is not available. * <p> * The returned path may change over time if different shared storage media * is inserted, so only relative paths should be persisted. * * @param type The type of files directory to return. May be {@code null} * for the root of the files directory or one of the following * constants for a subdirectory: * {@link android.os.Environment#DIRECTORY_MUSIC}, * {@link android.os.Environment#DIRECTORY_PODCASTS}, * {@link android.os.Environment#DIRECTORY_RINGTONES}, * {@link android.os.Environment#DIRECTORY_ALARMS}, * {@link android.os.Environment#DIRECTORY_NOTIFICATIONS}, * {@link android.os.Environment#DIRECTORY_PICTURES}, or * {@link android.os.Environment#DIRECTORY_MOVIES}. * @return the absolute paths to application-specific directories. Some * individual paths may be {@code null} if that shared storage is * not currently available. The first path returned is the same as * {@link #getExternalFilesDir(String)}. * @see #getExternalFilesDir(String) * @see Environment#getExternalStorageState(File) * @see Environment#isExternalStorageEmulated(File) * @see Environment#isExternalStorageRemovable(File) */ public abstract File[] getExternalFilesDirs(String type); /** * Return the primary shared/external storage directory where this * application's OBB files (if there are any) can be found. Note if the * application does not have any OBB files, this directory may not exist. * <p> * This is like {@link #getFilesDir()} in that these files will be deleted * when the application is uninstalled, however there are some important * differences: * <ul> * <li>Shared storage may not always be available, since removable media can * be ejected by the user. Media state can be checked using * {@link Environment#getExternalStorageState(File)}. * <li>There is no security enforced with these files. For example, any * application holding * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to * these files. * </ul> * <p> * Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, no permissions * are required to read or write to the path that this method returns. * However, starting from {@link android.os.Build.VERSION_CODES#M}, * to read the OBB expansion files, you must declare the * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} permission in the app manifest and ask for * permission at runtime as follows: * </p> * <p> * {@code <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" * android:maxSdkVersion="23" />} * </p> * <p> * Starting from {@link android.os.Build.VERSION_CODES#N}, * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} * permission is not required, so don’t ask for this * permission at runtime. To handle both cases, your app must first try to read the OBB file, * and if it fails, you must request * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} permission at runtime. * </p> * * <p> * The following code snippet shows how to do this: * </p> * * <pre> * File obb = new File(obb_filename); * boolean open_failed = false; * * try { * BufferedReader br = new BufferedReader(new FileReader(obb)); * open_failed = false; * ReadObbFile(br); * } catch (IOException e) { * open_failed = true; * } * * if (open_failed) { * // request READ_EXTERNAL_STORAGE permission before reading OBB file * ReadObbFileWithPermission(); * } * </pre> * * On devices with multiple users (as described by {@link UserManager}), * multiple users may share the same OBB storage location. Applications * should ensure that multiple instances running under different users don't * interfere with each other. * * @return the absolute path to application-specific directory. May return * {@code null} if shared storage is not currently available. * @see #getObbDirs() * @see Environment#getExternalStorageState(File) * @see Environment#isExternalStorageEmulated(File) * @see Environment#isExternalStorageRemovable(File) */ public abstract File getObbDir(); /** * Returns absolute paths to application-specific directories on all * shared/external storage devices where the application's OBB files (if * there are any) can be found. Note if the application does not have any * OBB files, these directories may not exist. * <p> * This is like {@link #getFilesDir()} in that these files will be deleted * when the application is uninstalled, however there are some important * differences: * <ul> * <li>Shared storage may not always be available, since removable media can * be ejected by the user. Media state can be checked using * {@link Environment#getExternalStorageState(File)}. * <li>There is no security enforced with these files. For example, any * application holding * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to * these files. * </ul> * <p> * Shared storage devices returned here are considered a stable part of the * device, including physical media slots under a protective cover. The * returned paths do not include transient devices, such as USB flash drives * connected to handheld devices. * <p> * An application may store data on any or all of the returned devices. For * example, an app may choose to store large files on the device with the * most available space, as measured by {@link StatFs}. * <p> * No additional permissions are required for the calling app to read or * write files under the returned path. Write access outside of these paths * on secondary external storage devices is not available. * * @return the absolute paths to application-specific directories. Some * individual paths may be {@code null} if that shared storage is * not currently available. The first path returned is the same as * {@link #getObbDir()} * @see #getObbDir() * @see Environment#getExternalStorageState(File) * @see Environment#isExternalStorageEmulated(File) * @see Environment#isExternalStorageRemovable(File) */ public abstract File[] getObbDirs(); /** * Returns the absolute path to the application specific cache directory on * the filesystem. * <p> * The system will automatically delete files in this directory as disk * space is needed elsewhere on the device. The system will always delete * older files first, as reported by {@link File#lastModified()}. If * desired, you can exert more control over how files are deleted using * {@link StorageManager#setCacheBehaviorGroup(File, boolean)} and * {@link StorageManager#setCacheBehaviorTombstone(File, boolean)}. * <p> * Apps are strongly encouraged to keep their usage of cache space below the * quota returned by * {@link StorageManager#getCacheQuotaBytes(java.util.UUID)}. If your app * goes above this quota, your cached files will be some of the first to be * deleted when additional disk space is needed. Conversely, if your app * stays under this quota, your cached files will be some of the last to be * deleted when additional disk space is needed. * <p> * Note that your cache quota will change over time depending on how * frequently the user interacts with your app, and depending on how much * system-wide disk space is used. * <p> * The returned path may change over time if the calling app is moved to an * adopted storage device, so only relative paths should be persisted. * <p> * Apps require no extra permissions to read or write to the returned path, * since this path lives in their private storage. * * @return The path of the directory holding application cache files. * @see #openFileOutput * @see #getFileStreamPath * @see #getDir * @see #getExternalCacheDir */ public abstract File getCacheDir(); /** * Returns the absolute path to the application specific cache directory on * the filesystem designed for storing cached code. * <p> * The system will delete any files stored in this location both when your * specific application is upgraded, and when the entire platform is * upgraded. * <p> * This location is optimal for storing compiled or optimized code generated * by your application at runtime. * <p> * The returned path may change over time if the calling app is moved to an * adopted storage device, so only relative paths should be persisted. * <p> * Apps require no extra permissions to read or write to the returned path, * since this path lives in their private storage. * * @return The path of the directory holding application code cache files. */ public abstract File getCodeCacheDir(); /** * Returns absolute path to application-specific directory on the primary * shared/external storage device where the application can place cache * files it owns. These files are internal to the application, and not * typically visible to the user as media. * <p> * This is like {@link #getCacheDir()} in that these files will be deleted * when the application is uninstalled, however there are some important * differences: * <ul> * <li>The platform does not always monitor the space available in shared * storage, and thus may not automatically delete these files. Apps should * always manage the maximum space used in this location. Currently the only * time files here will be deleted by the platform is when running on * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} or later and * {@link Environment#isExternalStorageEmulated(File)} returns true. * <li>Shared storage may not always be available, since removable media can * be ejected by the user. Media state can be checked using * {@link Environment#getExternalStorageState(File)}. * <li>There is no security enforced with these files. For example, any * application holding * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to * these files. * </ul> * <p> * If a shared storage device is emulated (as determined by * {@link Environment#isExternalStorageEmulated(File)}), its contents are * backed by a private user data partition, which means there is little * benefit to storing data here instead of the private directory returned by * {@link #getCacheDir()}. * <p> * Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, no permissions * are required to read or write to the returned path; it's always * accessible to the calling app. This only applies to paths generated for * package name of the calling application. To access paths belonging to * other packages, * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} and/or * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} are required. * <p> * On devices with multiple users (as described by {@link UserManager}), * each user has their own isolated shared storage. Applications only have * access to the shared storage for the user they're running as. * <p> * The returned path may change over time if different shared storage media * is inserted, so only relative paths should be persisted. * * @return the absolute path to application-specific directory. May return * {@code null} if shared storage is not currently available. * @see #getCacheDir * @see #getExternalCacheDirs() * @see Environment#getExternalStorageState(File) * @see Environment#isExternalStorageEmulated(File) * @see Environment#isExternalStorageRemovable(File) */ @Nullable public abstract File getExternalCacheDir(); /** * Returns absolute path to application-specific directory in the preloaded cache. * <p>Files stored in the cache directory can be deleted when the device runs low on storage. * There is no guarantee when these files will be deleted. * @hide */ @Nullable @SystemApi public abstract File getPreloadsFileCache(); /** * Returns absolute paths to application-specific directories on all * shared/external storage devices where the application can place cache * files it owns. These files are internal to the application, and not * typically visible to the user as media. * <p> * This is like {@link #getCacheDir()} in that these files will be deleted * when the application is uninstalled, however there are some important * differences: * <ul> * <li>The platform does not always monitor the space available in shared * storage, and thus may not automatically delete these files. Apps should * always manage the maximum space used in this location. Currently the only * time files here will be deleted by the platform is when running on * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} or later and * {@link Environment#isExternalStorageEmulated(File)} returns true. * <li>Shared storage may not always be available, since removable media can * be ejected by the user. Media state can be checked using * {@link Environment#getExternalStorageState(File)}. * <li>There is no security enforced with these files. For example, any * application holding * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to * these files. * </ul> * <p> * If a shared storage device is emulated (as determined by * {@link Environment#isExternalStorageEmulated(File)}), it's contents are * backed by a private user data partition, which means there is little * benefit to storing data here instead of the private directory returned by * {@link #getCacheDir()}. * <p> * Shared storage devices returned here are considered a stable part of the * device, including physical media slots under a protective cover. The * returned paths do not include transient devices, such as USB flash drives * connected to handheld devices. * <p> * An application may store data on any or all of the returned devices. For * example, an app may choose to store large files on the device with the * most available space, as measured by {@link StatFs}. * <p> * No additional permissions are required for the calling app to read or * write files under the returned path. Write access outside of these paths * on secondary external storage devices is not available. * <p> * The returned paths may change over time if different shared storage media * is inserted, so only relative paths should be persisted. * * @return the absolute paths to application-specific directories. Some * individual paths may be {@code null} if that shared storage is * not currently available. The first path returned is the same as * {@link #getExternalCacheDir()}. * @see #getExternalCacheDir() * @see Environment#getExternalStorageState(File) * @see Environment#isExternalStorageEmulated(File) * @see Environment#isExternalStorageRemovable(File) */ public abstract File[] getExternalCacheDirs(); /** * Returns absolute paths to application-specific directories on all * shared/external storage devices where the application can place media * files. These files are scanned and made available to other apps through * {@link MediaStore}. * <p> * This is like {@link #getExternalFilesDirs} in that these files will be * deleted when the application is uninstalled, however there are some * important differences: * <ul> * <li>Shared storage may not always be available, since removable media can * be ejected by the user. Media state can be checked using * {@link Environment#getExternalStorageState(File)}. * <li>There is no security enforced with these files. For example, any * application holding * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to * these files. * </ul> * <p> * Shared storage devices returned here are considered a stable part of the * device, including physical media slots under a protective cover. The * returned paths do not include transient devices, such as USB flash drives * connected to handheld devices. * <p> * An application may store data on any or all of the returned devices. For * example, an app may choose to store large files on the device with the * most available space, as measured by {@link StatFs}. * <p> * No additional permissions are required for the calling app to read or * write files under the returned path. Write access outside of these paths * on secondary external storage devices is not available. * <p> * The returned paths may change over time if different shared storage media * is inserted, so only relative paths should be persisted. * * @return the absolute paths to application-specific directories. Some * individual paths may be {@code null} if that shared storage is * not currently available. * @see Environment#getExternalStorageState(File) * @see Environment#isExternalStorageEmulated(File) * @see Environment#isExternalStorageRemovable(File) */ public abstract File[] getExternalMediaDirs(); /** * Returns an array of strings naming the private files associated with * this Context's application package. * * @return Array of strings naming the private files. * * @see #openFileInput * @see #openFileOutput * @see #deleteFile */ public abstract String[] fileList(); /** * Retrieve, creating if needed, a new directory in which the application * can place its own custom data files. You can use the returned File * object to create and access files in this directory. Note that files * created through a File object will only be accessible by your own * application; you can only set the mode of the entire directory, not * of individual files. * <p> * The returned path may change over time if the calling app is moved to an * adopted storage device, so only relative paths should be persisted. * <p> * Apps require no extra permissions to read or write to the returned path, * since this path lives in their private storage. * * @param name Name of the directory to retrieve. This is a directory * that is created as part of your application data. * @param mode Operating mode. * * @return A {@link File} object for the requested directory. The directory * will have been created if it does not already exist. * * @see #openFileOutput(String, int) */ public abstract File getDir(String name, @FileMode int mode); /** * Open a new private SQLiteDatabase associated with this Context's * application package. Create the database file if it doesn't exist. * * @param name The name (unique in the application package) of the database. * @param mode Operating mode. * @param factory An optional factory class that is called to instantiate a * cursor when query is called. * @return The contents of a newly created database with the given name. * @throws android.database.sqlite.SQLiteException if the database file * could not be opened. * @see #MODE_PRIVATE * @see #MODE_ENABLE_WRITE_AHEAD_LOGGING * @see #MODE_NO_LOCALIZED_COLLATORS * @see #deleteDatabase */ public abstract SQLiteDatabase openOrCreateDatabase(String name, @DatabaseMode int mode, CursorFactory factory); /** * Open a new private SQLiteDatabase associated with this Context's * application package. Creates the database file if it doesn't exist. * <p> * Accepts input param: a concrete instance of {@link DatabaseErrorHandler} * to be used to handle corruption when sqlite reports database corruption. * </p> * * @param name The name (unique in the application package) of the database. * @param mode Operating mode. * @param factory An optional factory class that is called to instantiate a * cursor when query is called. * @param errorHandler the {@link DatabaseErrorHandler} to be used when * sqlite reports database corruption. if null, * {@link android.database.DefaultDatabaseErrorHandler} is * assumed. * @return The contents of a newly created database with the given name. * @throws android.database.sqlite.SQLiteException if the database file * could not be opened. * @see #MODE_PRIVATE * @see #MODE_ENABLE_WRITE_AHEAD_LOGGING * @see #MODE_NO_LOCALIZED_COLLATORS * @see #deleteDatabase */ public abstract SQLiteDatabase openOrCreateDatabase(String name, @DatabaseMode int mode, CursorFactory factory, @Nullable DatabaseErrorHandler errorHandler); /** * Move an existing database file from the given source storage context to * this context. This is typically used to migrate data between storage * locations after an upgrade, such as migrating to device protected * storage. * <p> * The database must be closed before being moved. * * @param sourceContext The source context which contains the existing * database to move. * @param name The name of the database file. * @return {@code true} if the move was successful or if the database didn't * exist in the source context, otherwise {@code false}. * @see #createDeviceProtectedStorageContext() */ public abstract boolean moveDatabaseFrom(Context sourceContext, String name); /** * Delete an existing private SQLiteDatabase associated with this Context's * application package. * * @param name The name (unique in the application package) of the * database. * * @return {@code true} if the database was successfully deleted; else {@code false}. * * @see #openOrCreateDatabase */ public abstract boolean deleteDatabase(String name); /** * Returns the absolute path on the filesystem where a database created with * {@link #openOrCreateDatabase} is stored. * <p> * The returned path may change over time if the calling app is moved to an * adopted storage device, so only relative paths should be persisted. * * @param name The name of the database for which you would like to get * its path. * * @return An absolute path to the given database. * * @see #openOrCreateDatabase */ public abstract File getDatabasePath(String name); /** * Returns an array of strings naming the private databases associated with * this Context's application package. * * @return Array of strings naming the private databases. * * @see #openOrCreateDatabase * @see #deleteDatabase */ public abstract String[] databaseList(); /** * @deprecated Use {@link android.app.WallpaperManager#getDrawable * WallpaperManager.get()} instead. */ @Deprecated public abstract Drawable getWallpaper(); /** * @deprecated Use {@link android.app.WallpaperManager#peekDrawable * WallpaperManager.peek()} instead. */ @Deprecated public abstract Drawable peekWallpaper(); /** * @deprecated Use {@link android.app.WallpaperManager#getDesiredMinimumWidth() * WallpaperManager.getDesiredMinimumWidth()} instead. */ @Deprecated public abstract int getWallpaperDesiredMinimumWidth(); /** * @deprecated Use {@link android.app.WallpaperManager#getDesiredMinimumHeight() * WallpaperManager.getDesiredMinimumHeight()} instead. */ @Deprecated public abstract int getWallpaperDesiredMinimumHeight(); /** * @deprecated Use {@link android.app.WallpaperManager#setBitmap(Bitmap) * WallpaperManager.set()} instead. * <p>This method requires the caller to hold the permission * {@link android.Manifest.permission#SET_WALLPAPER}. */ @Deprecated public abstract void setWallpaper(Bitmap bitmap) throws IOException; /** * @deprecated Use {@link android.app.WallpaperManager#setStream(InputStream) * WallpaperManager.set()} instead. * <p>This method requires the caller to hold the permission * {@link android.Manifest.permission#SET_WALLPAPER}. */ @Deprecated public abstract void setWallpaper(InputStream data) throws IOException; /** * @deprecated Use {@link android.app.WallpaperManager#clear * WallpaperManager.clear()} instead. * <p>This method requires the caller to hold the permission * {@link android.Manifest.permission#SET_WALLPAPER}. */ @Deprecated public abstract void clearWallpaper() throws IOException; /** * Same as {@link #startActivity(Intent, Bundle)} with no options * specified. * * @param intent The description of the activity to start. * * @throws ActivityNotFoundException &nbsp; *` * @see #startActivity(Intent, Bundle) * @see PackageManager#resolveActivity */ public abstract void startActivity(@RequiresPermission Intent intent); /** * Version of {@link #startActivity(Intent)} that allows you to specify the * user the activity will be started for. This is not available to applications * that are not pre-installed on the system image. * @param intent The description of the activity to start. * @param user The UserHandle of the user to start this activity for. * @throws ActivityNotFoundException &nbsp; * @hide */ @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL) public void startActivityAsUser(@RequiresPermission Intent intent, UserHandle user) { throw new RuntimeException("Not implemented. Must override in a subclass."); } /** * Launch a new activity. You will not receive any information about when * the activity exits. * * <p>Note that if this method is being called from outside of an * {@link android.app.Activity} Context, then the Intent must include * the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag. This is because, * without being started from an existing Activity, there is no existing * task in which to place the new activity and thus it needs to be placed * in its own separate task. * * <p>This method throws {@link ActivityNotFoundException} * if there was no Activity found to run the given Intent. * * @param intent The description of the activity to start. * @param options Additional options for how the Activity should be started. * May be null if there are no options. See {@link android.app.ActivityOptions} * for how to build the Bundle supplied here; there are no supported definitions * for building it manually. * * @throws ActivityNotFoundException &nbsp; * * @see #startActivity(Intent) * @see PackageManager#resolveActivity */ public abstract void startActivity(@RequiresPermission Intent intent, @Nullable Bundle options); /** * Version of {@link #startActivity(Intent, Bundle)} that allows you to specify the * user the activity will be started for. This is not available to applications * that are not pre-installed on the system image. * @param intent The description of the activity to start. * @param options Additional options for how the Activity should be started. * May be null if there are no options. See {@link android.app.ActivityOptions} * for how to build the Bundle supplied here; there are no supported definitions * for building it manually. * @param userId The UserHandle of the user to start this activity for. * @throws ActivityNotFoundException &nbsp; * @hide */ @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL) public void startActivityAsUser(@RequiresPermission Intent intent, @Nullable Bundle options, UserHandle userId) { throw new RuntimeException("Not implemented. Must override in a subclass."); } /** * Version of {@link #startActivity(Intent, Bundle)} that returns a result to the caller. This * is only supported for Views and Fragments. * @param who The identifier for the calling element that will receive the result. * @param intent The intent to start. * @param requestCode The code that will be returned with onActivityResult() identifying this * request. * @param options Additional options for how the Activity should be started. * May be null if there are no options. See {@link android.app.ActivityOptions} * for how to build the Bundle supplied here; there are no supported definitions * for building it manually. * @hide */ public void startActivityForResult( @NonNull String who, Intent intent, int requestCode, @Nullable Bundle options) { throw new RuntimeException("This method is only implemented for Activity-based Contexts. " + "Check canStartActivityForResult() before calling."); } /** * Identifies whether this Context instance will be able to process calls to * {@link #startActivityForResult(String, Intent, int, Bundle)}. * @hide */ public boolean canStartActivityForResult() { return false; } /** * Same as {@link #startActivities(Intent[], Bundle)} with no options * specified. * * @param intents An array of Intents to be started. * * @throws ActivityNotFoundException &nbsp; * * @see #startActivities(Intent[], Bundle) * @see PackageManager#resolveActivity */ public abstract void startActivities(@RequiresPermission Intent[] intents); /** * Launch multiple new activities. This is generally the same as calling * {@link #startActivity(Intent)} for the first Intent in the array, * that activity during its creation calling {@link #startActivity(Intent)} * for the second entry, etc. Note that unlike that approach, generally * none of the activities except the last in the array will be created * at this point, but rather will be created when the user first visits * them (due to pressing back from the activity on top). * * <p>This method throws {@link ActivityNotFoundException} * if there was no Activity found for <em>any</em> given Intent. In this * case the state of the activity stack is undefined (some Intents in the * list may be on it, some not), so you probably want to avoid such situations. * * @param intents An array of Intents to be started. * @param options Additional options for how the Activity should be started. * See {@link android.content.Context#startActivity(Intent, Bundle)} * Context.startActivity(Intent, Bundle)} for more details. * * @throws ActivityNotFoundException &nbsp; * * @see #startActivities(Intent[]) * @see PackageManager#resolveActivity */ public abstract void startActivities(@RequiresPermission Intent[] intents, Bundle options); /** * @hide * Launch multiple new activities. This is generally the same as calling * {@link #startActivity(Intent)} for the first Intent in the array, * that activity during its creation calling {@link #startActivity(Intent)} * for the second entry, etc. Note that unlike that approach, generally * none of the activities except the last in the array will be created * at this point, but rather will be created when the user first visits * them (due to pressing back from the activity on top). * * <p>This method throws {@link ActivityNotFoundException} * if there was no Activity found for <em>any</em> given Intent. In this * case the state of the activity stack is undefined (some Intents in the * list may be on it, some not), so you probably want to avoid such situations. * * @param intents An array of Intents to be started. * @param options Additional options for how the Activity should be started. * @param userHandle The user for whom to launch the activities * See {@link android.content.Context#startActivity(Intent, Bundle)} * Context.startActivity(Intent, Bundle)} for more details. * * @throws ActivityNotFoundException &nbsp; * * @see #startActivities(Intent[]) * @see PackageManager#resolveActivity */ @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL) public void startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) { throw new RuntimeException("Not implemented. Must override in a subclass."); } /** * Same as {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)} * with no options specified. * * @param intent The IntentSender to launch. * @param fillInIntent If non-null, this will be provided as the * intent parameter to {@link IntentSender#sendIntent}. * @param flagsMask Intent flags in the original IntentSender that you * would like to change. * @param flagsValues Desired values for any bits set in * <var>flagsMask</var> * @param extraFlags Always set to 0. * * @see #startActivity(Intent) * @see #startIntentSender(IntentSender, Intent, int, int, int, Bundle) */ public abstract void startIntentSender(IntentSender intent, @Nullable Intent fillInIntent, @Intent.MutableFlags int flagsMask, @Intent.MutableFlags int flagsValues, int extraFlags) throws IntentSender.SendIntentException; /** * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender * to start. If the IntentSender is for an activity, that activity will be started * as if you had called the regular {@link #startActivity(Intent)} * here; otherwise, its associated action will be executed (such as * sending a broadcast) as if you had called * {@link IntentSender#sendIntent IntentSender.sendIntent} on it. * * @param intent The IntentSender to launch. * @param fillInIntent If non-null, this will be provided as the * intent parameter to {@link IntentSender#sendIntent}. * @param flagsMask Intent flags in the original IntentSender that you * would like to change. * @param flagsValues Desired values for any bits set in * <var>flagsMask</var> * @param extraFlags Always set to 0. * @param options Additional options for how the Activity should be started. * See {@link android.content.Context#startActivity(Intent, Bundle)} * Context.startActivity(Intent, Bundle)} for more details. If options * have also been supplied by the IntentSender, options given here will * override any that conflict with those given by the IntentSender. * * @see #startActivity(Intent, Bundle) * @see #startIntentSender(IntentSender, Intent, int, int, int) */ public abstract void startIntentSender(IntentSender intent, @Nullable Intent fillInIntent, @Intent.MutableFlags int flagsMask, @Intent.MutableFlags int flagsValues, int extraFlags, @Nullable Bundle options) throws IntentSender.SendIntentException; /** * Broadcast the given intent to all interested BroadcastReceivers. This * call is asynchronous; it returns immediately, and you will continue * executing while the receivers are run. No results are propagated from * receivers and receivers can not abort the broadcast. If you want * to allow receivers to propagate results or abort the broadcast, you must * send an ordered broadcast using * {@link #sendOrderedBroadcast(Intent, String)}. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast. * * @see android.content.BroadcastReceiver * @see #registerReceiver * @see #sendBroadcast(Intent, String) * @see #sendOrderedBroadcast(Intent, String) * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle) */ public abstract void sendBroadcast(@RequiresPermission Intent intent); /** * Broadcast the given intent to all interested BroadcastReceivers, allowing * an optional required permission to be enforced. This * call is asynchronous; it returns immediately, and you will continue * executing while the receivers are run. No results are propagated from * receivers and receivers can not abort the broadcast. If you want * to allow receivers to propagate results or abort the broadcast, you must * send an ordered broadcast using * {@link #sendOrderedBroadcast(Intent, String)}. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast. * @param receiverPermission (optional) String naming a permission that * a receiver must hold in order to receive your broadcast. * If null, no permission is required. * * @see android.content.BroadcastReceiver * @see #registerReceiver * @see #sendBroadcast(Intent) * @see #sendOrderedBroadcast(Intent, String) * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle) */ public abstract void sendBroadcast(@RequiresPermission Intent intent, @Nullable String receiverPermission); /** * Broadcast the given intent to all interested BroadcastReceivers, allowing * an array of required permissions to be enforced. This call is asynchronous; it returns * immediately, and you will continue executing while the receivers are run. No results are * propagated from receivers and receivers can not abort the broadcast. If you want to allow * receivers to propagate results or abort the broadcast, you must send an ordered broadcast * using {@link #sendOrderedBroadcast(Intent, String)}. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast. * @param receiverPermissions Array of names of permissions that a receiver must hold * in order to receive your broadcast. * If null or empty, no permissions are required. * * @see android.content.BroadcastReceiver * @see #registerReceiver * @see #sendBroadcast(Intent) * @see #sendOrderedBroadcast(Intent, String) * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle) * @hide */ public abstract void sendBroadcastMultiplePermissions(Intent intent, String[] receiverPermissions); /** * Broadcast the given intent to all interested BroadcastReceivers, allowing * an optional required permission to be enforced. This * call is asynchronous; it returns immediately, and you will continue * executing while the receivers are run. No results are propagated from * receivers and receivers can not abort the broadcast. If you want * to allow receivers to propagate results or abort the broadcast, you must * send an ordered broadcast using * {@link #sendOrderedBroadcast(Intent, String)}. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast. * @param receiverPermission (optional) String naming a permission that * a receiver must hold in order to receive your broadcast. * If null, no permission is required. * @param options (optional) Additional sending options, generated from a * {@link android.app.BroadcastOptions}. * * @see android.content.BroadcastReceiver * @see #registerReceiver * @see #sendBroadcast(Intent) * @see #sendOrderedBroadcast(Intent, String) * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle) * @hide */ @SystemApi public abstract void sendBroadcast(Intent intent, @Nullable String receiverPermission, @Nullable Bundle options); /** * Like {@link #sendBroadcast(Intent, String)}, but also allows specification * of an associated app op as per {@link android.app.AppOpsManager}. * @hide */ public abstract void sendBroadcast(Intent intent, String receiverPermission, int appOp); /** * Broadcast the given intent to all interested BroadcastReceivers, delivering * them one at a time to allow more preferred receivers to consume the * broadcast before it is delivered to less preferred receivers. This * call is asynchronous; it returns immediately, and you will continue * executing while the receivers are run. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast. * @param receiverPermission (optional) String naming a permissions that * a receiver must hold in order to receive your broadcast. * If null, no permission is required. * * @see android.content.BroadcastReceiver * @see #registerReceiver * @see #sendBroadcast(Intent) * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle) */ public abstract void sendOrderedBroadcast(@RequiresPermission Intent intent, @Nullable String receiverPermission); /** * Version of {@link #sendBroadcast(Intent)} that allows you to * receive data back from the broadcast. This is accomplished by * supplying your own BroadcastReceiver when calling, which will be * treated as a final receiver at the end of the broadcast -- its * {@link BroadcastReceiver#onReceive} method will be called with * the result values collected from the other receivers. The broadcast will * be serialized in the same way as calling * {@link #sendOrderedBroadcast(Intent, String)}. * * <p>Like {@link #sendBroadcast(Intent)}, this method is * asynchronous; it will return before * resultReceiver.onReceive() is called. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast. * @param receiverPermission String naming a permissions that * a receiver must hold in order to receive your broadcast. * If null, no permission is required. * @param resultReceiver Your own BroadcastReceiver to treat as the final * receiver of the broadcast. * @param scheduler A custom Handler with which to schedule the * resultReceiver callback; if null it will be * scheduled in the Context's main thread. * @param initialCode An initial value for the result code. Often * Activity.RESULT_OK. * @param initialData An initial value for the result data. Often * null. * @param initialExtras An initial value for the result extras. Often * null. * * @see #sendBroadcast(Intent) * @see #sendBroadcast(Intent, String) * @see #sendOrderedBroadcast(Intent, String) * @see android.content.BroadcastReceiver * @see #registerReceiver * @see android.app.Activity#RESULT_OK */ public abstract void sendOrderedBroadcast(@RequiresPermission @NonNull Intent intent, @Nullable String receiverPermission, @Nullable BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras); /** * Version of {@link #sendBroadcast(Intent)} that allows you to * receive data back from the broadcast. This is accomplished by * supplying your own BroadcastReceiver when calling, which will be * treated as a final receiver at the end of the broadcast -- its * {@link BroadcastReceiver#onReceive} method will be called with * the result values collected from the other receivers. The broadcast will * be serialized in the same way as calling * {@link #sendOrderedBroadcast(Intent, String)}. * * <p>Like {@link #sendBroadcast(Intent)}, this method is * asynchronous; it will return before * resultReceiver.onReceive() is called. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast. * @param receiverPermission String naming a permissions that * a receiver must hold in order to receive your broadcast. * If null, no permission is required. * @param options (optional) Additional sending options, generated from a * {@link android.app.BroadcastOptions}. * @param resultReceiver Your own BroadcastReceiver to treat as the final * receiver of the broadcast. * @param scheduler A custom Handler with which to schedule the * resultReceiver callback; if null it will be * scheduled in the Context's main thread. * @param initialCode An initial value for the result code. Often * Activity.RESULT_OK. * @param initialData An initial value for the result data. Often * null. * @param initialExtras An initial value for the result extras. Often * null. * @see #sendBroadcast(Intent) * @see #sendBroadcast(Intent, String) * @see #sendOrderedBroadcast(Intent, String) * @see android.content.BroadcastReceiver * @see #registerReceiver * @see android.app.Activity#RESULT_OK * @hide */ @SystemApi public abstract void sendOrderedBroadcast(@NonNull Intent intent, @Nullable String receiverPermission, @Nullable Bundle options, @Nullable BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras); /** * Like {@link #sendOrderedBroadcast(Intent, String, BroadcastReceiver, android.os.Handler, * int, String, android.os.Bundle)}, but also allows specification * of an associated app op as per {@link android.app.AppOpsManager}. * @hide */ public abstract void sendOrderedBroadcast(Intent intent, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras); /** * Version of {@link #sendBroadcast(Intent)} that allows you to specify the * user the broadcast will be sent to. This is not available to applications * that are not pre-installed on the system image. * @param intent The intent to broadcast * @param user UserHandle to send the intent to. * @see #sendBroadcast(Intent) */ @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public abstract void sendBroadcastAsUser(@RequiresPermission Intent intent, UserHandle user); /** * Version of {@link #sendBroadcast(Intent, String)} that allows you to specify the * user the broadcast will be sent to. This is not available to applications * that are not pre-installed on the system image. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast. * @param user UserHandle to send the intent to. * @param receiverPermission (optional) String naming a permission that * a receiver must hold in order to receive your broadcast. * If null, no permission is required. * * @see #sendBroadcast(Intent, String) */ @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public abstract void sendBroadcastAsUser(@RequiresPermission Intent intent, UserHandle user, @Nullable String receiverPermission); /** * Version of {@link #sendBroadcast(Intent, String, Bundle)} that allows you to specify the * user the broadcast will be sent to. This is not available to applications * that are not pre-installed on the system image. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast. * @param user UserHandle to send the intent to. * @param receiverPermission (optional) String naming a permission that * a receiver must hold in order to receive your broadcast. * If null, no permission is required. * @param options (optional) Additional sending options, generated from a * {@link android.app.BroadcastOptions}. * * @see #sendBroadcast(Intent, String, Bundle) * @hide */ @SystemApi @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public abstract void sendBroadcastAsUser(@RequiresPermission Intent intent, UserHandle user, @Nullable String receiverPermission, @Nullable Bundle options); /** * Version of {@link #sendBroadcast(Intent, String)} that allows you to specify the * user the broadcast will be sent to. This is not available to applications * that are not pre-installed on the system image. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast. * @param user UserHandle to send the intent to. * @param receiverPermission (optional) String naming a permission that * a receiver must hold in order to receive your broadcast. * If null, no permission is required. * @param appOp The app op associated with the broadcast. * * @see #sendBroadcast(Intent, String) * * @hide */ @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public abstract void sendBroadcastAsUser(@RequiresPermission Intent intent, UserHandle user, @Nullable String receiverPermission, int appOp); /** * Version of * {@link #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)} * that allows you to specify the * user the broadcast will be sent to. This is not available to applications * that are not pre-installed on the system image. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast. * @param user UserHandle to send the intent to. * @param receiverPermission String naming a permissions that * a receiver must hold in order to receive your broadcast. * If null, no permission is required. * @param resultReceiver Your own BroadcastReceiver to treat as the final * receiver of the broadcast. * @param scheduler A custom Handler with which to schedule the * resultReceiver callback; if null it will be * scheduled in the Context's main thread. * @param initialCode An initial value for the result code. Often * Activity.RESULT_OK. * @param initialData An initial value for the result data. Often * null. * @param initialExtras An initial value for the result extras. Often * null. * * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle) */ @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public abstract void sendOrderedBroadcastAsUser(@RequiresPermission Intent intent, UserHandle user, @Nullable String receiverPermission, BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras); /** * Similar to above but takes an appOp as well, to enforce restrictions. * @see #sendOrderedBroadcastAsUser(Intent, UserHandle, String, * BroadcastReceiver, Handler, int, String, Bundle) * @hide */ @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public abstract void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, @Nullable String receiverPermission, int appOp, BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras); /** * Similar to above but takes an appOp as well, to enforce restrictions, and an options Bundle. * @see #sendOrderedBroadcastAsUser(Intent, UserHandle, String, * BroadcastReceiver, Handler, int, String, Bundle) * @hide */ @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public abstract void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, @Nullable String receiverPermission, int appOp, @Nullable Bundle options, BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras); /** * <p>Perform a {@link #sendBroadcast(Intent)} that is "sticky," meaning the * Intent you are sending stays around after the broadcast is complete, * so that others can quickly retrieve that data through the return * value of {@link #registerReceiver(BroadcastReceiver, IntentFilter)}. In * all other ways, this behaves the same as * {@link #sendBroadcast(Intent)}. * * @deprecated Sticky broadcasts should not be used. They provide no security (anyone * can access them), no protection (anyone can modify them), and many other problems. * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em> * has changed, with another mechanism for apps to retrieve the current value whenever * desired. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast, and the Intent will be held to * be re-broadcast to future receivers. * * @see #sendBroadcast(Intent) * @see #sendStickyOrderedBroadcast(Intent, BroadcastReceiver, Handler, int, String, Bundle) */ @Deprecated @RequiresPermission(android.Manifest.permission.BROADCAST_STICKY) public abstract void sendStickyBroadcast(@RequiresPermission Intent intent); /** * <p>Version of {@link #sendStickyBroadcast} that allows you to * receive data back from the broadcast. This is accomplished by * supplying your own BroadcastReceiver when calling, which will be * treated as a final receiver at the end of the broadcast -- its * {@link BroadcastReceiver#onReceive} method will be called with * the result values collected from the other receivers. The broadcast will * be serialized in the same way as calling * {@link #sendOrderedBroadcast(Intent, String)}. * * <p>Like {@link #sendBroadcast(Intent)}, this method is * asynchronous; it will return before * resultReceiver.onReceive() is called. Note that the sticky data * stored is only the data you initially supply to the broadcast, not * the result of any changes made by the receivers. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * @deprecated Sticky broadcasts should not be used. They provide no security (anyone * can access them), no protection (anyone can modify them), and many other problems. * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em> * has changed, with another mechanism for apps to retrieve the current value whenever * desired. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast. * @param resultReceiver Your own BroadcastReceiver to treat as the final * receiver of the broadcast. * @param scheduler A custom Handler with which to schedule the * resultReceiver callback; if null it will be * scheduled in the Context's main thread. * @param initialCode An initial value for the result code. Often * Activity.RESULT_OK. * @param initialData An initial value for the result data. Often * null. * @param initialExtras An initial value for the result extras. Often * null. * * @see #sendBroadcast(Intent) * @see #sendBroadcast(Intent, String) * @see #sendOrderedBroadcast(Intent, String) * @see #sendStickyBroadcast(Intent) * @see android.content.BroadcastReceiver * @see #registerReceiver * @see android.app.Activity#RESULT_OK */ @Deprecated @RequiresPermission(android.Manifest.permission.BROADCAST_STICKY) public abstract void sendStickyOrderedBroadcast(@RequiresPermission Intent intent, BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras); /** * <p>Remove the data previously sent with {@link #sendStickyBroadcast}, * so that it is as if the sticky broadcast had never happened. * * @deprecated Sticky broadcasts should not be used. They provide no security (anyone * can access them), no protection (anyone can modify them), and many other problems. * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em> * has changed, with another mechanism for apps to retrieve the current value whenever * desired. * * @param intent The Intent that was previously broadcast. * * @see #sendStickyBroadcast */ @Deprecated @RequiresPermission(android.Manifest.permission.BROADCAST_STICKY) public abstract void removeStickyBroadcast(@RequiresPermission Intent intent); /** * <p>Version of {@link #sendStickyBroadcast(Intent)} that allows you to specify the * user the broadcast will be sent to. This is not available to applications * that are not pre-installed on the system image. * * @deprecated Sticky broadcasts should not be used. They provide no security (anyone * can access them), no protection (anyone can modify them), and many other problems. * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em> * has changed, with another mechanism for apps to retrieve the current value whenever * desired. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast, and the Intent will be held to * be re-broadcast to future receivers. * @param user UserHandle to send the intent to. * * @see #sendBroadcast(Intent) */ @Deprecated @RequiresPermission(allOf = { android.Manifest.permission.INTERACT_ACROSS_USERS, android.Manifest.permission.BROADCAST_STICKY }) public abstract void sendStickyBroadcastAsUser(@RequiresPermission Intent intent, UserHandle user); /** * @hide * This is just here for sending CONNECTIVITY_ACTION. */ @Deprecated @RequiresPermission(allOf = { android.Manifest.permission.INTERACT_ACROSS_USERS, android.Manifest.permission.BROADCAST_STICKY }) public abstract void sendStickyBroadcastAsUser(@RequiresPermission Intent intent, UserHandle user, Bundle options); /** * <p>Version of * {@link #sendStickyOrderedBroadcast(Intent, BroadcastReceiver, Handler, int, String, Bundle)} * that allows you to specify the * user the broadcast will be sent to. This is not available to applications * that are not pre-installed on the system image. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * @deprecated Sticky broadcasts should not be used. They provide no security (anyone * can access them), no protection (anyone can modify them), and many other problems. * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em> * has changed, with another mechanism for apps to retrieve the current value whenever * desired. * * @param intent The Intent to broadcast; all receivers matching this * Intent will receive the broadcast. * @param user UserHandle to send the intent to. * @param resultReceiver Your own BroadcastReceiver to treat as the final * receiver of the broadcast. * @param scheduler A custom Handler with which to schedule the * resultReceiver callback; if null it will be * scheduled in the Context's main thread. * @param initialCode An initial value for the result code. Often * Activity.RESULT_OK. * @param initialData An initial value for the result data. Often * null. * @param initialExtras An initial value for the result extras. Often * null. * * @see #sendStickyOrderedBroadcast(Intent, BroadcastReceiver, Handler, int, String, Bundle) */ @Deprecated @RequiresPermission(allOf = { android.Manifest.permission.INTERACT_ACROSS_USERS, android.Manifest.permission.BROADCAST_STICKY }) public abstract void sendStickyOrderedBroadcastAsUser(@RequiresPermission Intent intent, UserHandle user, BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras); /** * <p>Version of {@link #removeStickyBroadcast(Intent)} that allows you to specify the * user the broadcast will be sent to. This is not available to applications * that are not pre-installed on the system image. * * <p>You must hold the {@link android.Manifest.permission#BROADCAST_STICKY} * permission in order to use this API. If you do not hold that * permission, {@link SecurityException} will be thrown. * * @deprecated Sticky broadcasts should not be used. They provide no security (anyone * can access them), no protection (anyone can modify them), and many other problems. * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em> * has changed, with another mechanism for apps to retrieve the current value whenever * desired. * * @param intent The Intent that was previously broadcast. * @param user UserHandle to remove the sticky broadcast from. * * @see #sendStickyBroadcastAsUser */ @Deprecated @RequiresPermission(allOf = { android.Manifest.permission.INTERACT_ACROSS_USERS, android.Manifest.permission.BROADCAST_STICKY }) public abstract void removeStickyBroadcastAsUser(@RequiresPermission Intent intent, UserHandle user); /** * Register a BroadcastReceiver to be run in the main activity thread. The * <var>receiver</var> will be called with any broadcast Intent that * matches <var>filter</var>, in the main application thread. * * <p>The system may broadcast Intents that are "sticky" -- these stay * around after the broadcast has finished, to be sent to any later * registrations. If your IntentFilter matches one of these sticky * Intents, that Intent will be returned by this function * <strong>and</strong> sent to your <var>receiver</var> as if it had just * been broadcast. * * <p>There may be multiple sticky Intents that match <var>filter</var>, * in which case each of these will be sent to <var>receiver</var>. In * this case, only one of these can be returned directly by the function; * which of these that is returned is arbitrarily decided by the system. * * <p>If you know the Intent your are registering for is sticky, you can * supply null for your <var>receiver</var>. In this case, no receiver is * registered -- the function simply returns the sticky Intent that * matches <var>filter</var>. In the case of multiple matches, the same * rules as described above apply. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * <p>As of {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}, receivers * registered with this method will correctly respect the * {@link Intent#setPackage(String)} specified for an Intent being broadcast. * Prior to that, it would be ignored and delivered to all matching registered * receivers. Be careful if using this for security.</p> * * <p class="note">Note: this method <em>cannot be called from a * {@link BroadcastReceiver} component;</em> that is, from a BroadcastReceiver * that is declared in an application's manifest. It is okay, however, to call * this method from another BroadcastReceiver that has itself been registered * at run time with {@link #registerReceiver}, since the lifetime of such a * registered BroadcastReceiver is tied to the object that registered it.</p> * * @param receiver The BroadcastReceiver to handle the broadcast. * @param filter Selects the Intent broadcasts to be received. * * @return The first sticky intent found that matches <var>filter</var>, * or null if there are none. * * @see #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler) * @see #sendBroadcast * @see #unregisterReceiver */ @Nullable public abstract Intent registerReceiver(@Nullable BroadcastReceiver receiver, IntentFilter filter); /** * Register to receive intent broadcasts, with the receiver optionally being * exposed to Instant Apps. See * {@link #registerReceiver(BroadcastReceiver, IntentFilter)} for more * information. By default Instant Apps cannot interact with receivers in other * applications, this allows you to expose a receiver that Instant Apps can * interact with. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * <p>As of {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}, receivers * registered with this method will correctly respect the * {@link Intent#setPackage(String)} specified for an Intent being broadcast. * Prior to that, it would be ignored and delivered to all matching registered * receivers. Be careful if using this for security.</p> * * @param receiver The BroadcastReceiver to handle the broadcast. * @param filter Selects the Intent broadcasts to be received. * @param flags Additional options for the receiver. May be 0 or * {@link #RECEIVER_VISIBLE_TO_INSTANT_APPS}. * * @return The first sticky intent found that matches <var>filter</var>, * or null if there are none. * * @see #registerReceiver(BroadcastReceiver, IntentFilter) * @see #sendBroadcast * @see #unregisterReceiver */ @Nullable public abstract Intent registerReceiver(@Nullable BroadcastReceiver receiver, IntentFilter filter, @RegisterReceiverFlags int flags); /** * Register to receive intent broadcasts, to run in the context of * <var>scheduler</var>. See * {@link #registerReceiver(BroadcastReceiver, IntentFilter)} for more * information. This allows you to enforce permissions on who can * broadcast intents to your receiver, or have the receiver run in * a different thread than the main application thread. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * <p>As of {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}, receivers * registered with this method will correctly respect the * {@link Intent#setPackage(String)} specified for an Intent being broadcast. * Prior to that, it would be ignored and delivered to all matching registered * receivers. Be careful if using this for security.</p> * * @param receiver The BroadcastReceiver to handle the broadcast. * @param filter Selects the Intent broadcasts to be received. * @param broadcastPermission String naming a permissions that a * broadcaster must hold in order to send an Intent to you. If null, * no permission is required. * @param scheduler Handler identifying the thread that will receive * the Intent. If null, the main thread of the process will be used. * * @return The first sticky intent found that matches <var>filter</var>, * or null if there are none. * * @see #registerReceiver(BroadcastReceiver, IntentFilter) * @see #sendBroadcast * @see #unregisterReceiver */ @Nullable public abstract Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, @Nullable String broadcastPermission, @Nullable Handler scheduler); /** * Register to receive intent broadcasts, to run in the context of * <var>scheduler</var>. See * {@link #registerReceiver(BroadcastReceiver, IntentFilter, int)} and * {@link #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler)} * for more information. * * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts. * * <p>As of {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}, receivers * registered with this method will correctly respect the * {@link Intent#setPackage(String)} specified for an Intent being broadcast. * Prior to that, it would be ignored and delivered to all matching registered * receivers. Be careful if using this for security.</p> * * @param receiver The BroadcastReceiver to handle the broadcast. * @param filter Selects the Intent broadcasts to be received. * @param broadcastPermission String naming a permissions that a * broadcaster must hold in order to send an Intent to you. If null, * no permission is required. * @param scheduler Handler identifying the thread that will receive * the Intent. If null, the main thread of the process will be used. * @param flags Additional options for the receiver. May be 0 or * {@link #RECEIVER_VISIBLE_TO_INSTANT_APPS}. * * @return The first sticky intent found that matches <var>filter</var>, * or null if there are none. * * @see #registerReceiver(BroadcastReceiver, IntentFilter, int) * @see #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler) * @see #sendBroadcast * @see #unregisterReceiver */ @Nullable public abstract Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, @Nullable String broadcastPermission, @Nullable Handler scheduler, @RegisterReceiverFlags int flags); /** * @hide * Same as {@link #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler) * but for a specific user. This receiver will receiver broadcasts that * are sent to the requested user. * * @param receiver The BroadcastReceiver to handle the broadcast. * @param user UserHandle to send the intent to. * @param filter Selects the Intent broadcasts to be received. * @param broadcastPermission String naming a permissions that a * broadcaster must hold in order to send an Intent to you. If null, * no permission is required. * @param scheduler Handler identifying the thread that will receive * the Intent. If null, the main thread of the process will be used. * * @return The first sticky intent found that matches <var>filter</var>, * or null if there are none. * * @see #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler) * @see #sendBroadcast * @see #unregisterReceiver */ @Nullable @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL) public abstract Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, IntentFilter filter, @Nullable String broadcastPermission, @Nullable Handler scheduler); /** * Unregister a previously registered BroadcastReceiver. <em>All</em> * filters that have been registered for this BroadcastReceiver will be * removed. * * @param receiver The BroadcastReceiver to unregister. * * @see #registerReceiver */ public abstract void unregisterReceiver(BroadcastReceiver receiver); /** * Request that a given application service be started. The Intent * should either contain the complete class name of a specific service * implementation to start, or a specific package name to target. If the * Intent is less specified, it logs a warning about this. In this case any of the * multiple matching services may be used. If this service * is not already running, it will be instantiated and started (creating a * process for it if needed); if it is running then it remains running. * * <p>Every call to this method will result in a corresponding call to * the target service's {@link android.app.Service#onStartCommand} method, * with the <var>intent</var> given here. This provides a convenient way * to submit jobs to a service without having to bind and call on to its * interface. * * <p>Using startService() overrides the default service lifetime that is * managed by {@link #bindService}: it requires the service to remain * running until {@link #stopService} is called, regardless of whether * any clients are connected to it. Note that calls to startService() * do not nest: no matter how many times you call startService(), * a single call to {@link #stopService} will stop it. * * <p>The system attempts to keep running services around as much as * possible. The only time they should be stopped is if the current * foreground application is using so many resources that the service needs * to be killed. If any errors happen in the service's process, it will * automatically be restarted. * * <p>This function will throw {@link SecurityException} if you do not * have permission to start the given service. * * <p class="note"><strong>Note:</strong> Each call to startService() * results in significant work done by the system to manage service * lifecycle surrounding the processing of the intent, which can take * multiple milliseconds of CPU time. Due to this cost, startService() * should not be used for frequent intent delivery to a service, and only * for scheduling significant work. Use {@link #bindService bound services} * for high frequency calls. * </p> * * @param service Identifies the service to be started. The Intent must be * fully explicit (supplying a component name). Additional values * may be included in the Intent extras to supply arguments along with * this specific start call. * * @return If the service is being started or is already running, the * {@link ComponentName} of the actual service that was started is * returned; else if the service does not exist null is returned. * * @throws SecurityException If the caller does not have permission to access the service * or the service can not be found. * @throws IllegalStateException If the application is in a state where the service * can not be started (such as not in the foreground in a state when services are allowed). * * @see #stopService * @see #bindService */ @Nullable public abstract ComponentName startService(Intent service); /** * Similar to {@link #startService(Intent)}, but with an implicit promise that the * Service will call {@link android.app.Service#startForeground(int, android.app.Notification) * startForeground(int, android.app.Notification)} once it begins running. The service is given * an amount of time comparable to the ANR interval to do this, otherwise the system * will automatically stop the service and declare the app ANR. * * <p>Unlike the ordinary {@link #startService(Intent)}, this method can be used * at any time, regardless of whether the app hosting the service is in a foreground * state. * * @param service Identifies the service to be started. The Intent must be * fully explicit (supplying a component name). Additional values * may be included in the Intent extras to supply arguments along with * this specific start call. * * @return If the service is being started or is already running, the * {@link ComponentName} of the actual service that was started is * returned; else if the service does not exist null is returned. * * @throws SecurityException If the caller does not have permission to access the service * or the service can not be found. * * @see #stopService * @see android.app.Service#startForeground(int, android.app.Notification) */ @Nullable public abstract ComponentName startForegroundService(Intent service); /** * @hide like {@link #startForegroundService(Intent)} but for a specific user. */ @Nullable @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public abstract ComponentName startForegroundServiceAsUser(Intent service, UserHandle user); /** * Request that a given application service be stopped. If the service is * not running, nothing happens. Otherwise it is stopped. Note that calls * to startService() are not counted -- this stops the service no matter * how many times it was started. * * <p>Note that if a stopped service still has {@link ServiceConnection} * objects bound to it with the {@link #BIND_AUTO_CREATE} set, it will * not be destroyed until all of these bindings are removed. See * the {@link android.app.Service} documentation for more details on a * service's lifecycle. * * <p>This function will throw {@link SecurityException} if you do not * have permission to stop the given service. * * @param service Description of the service to be stopped. The Intent must be either * fully explicit (supplying a component name) or specify a specific package * name it is targetted to. * * @return If there is a service matching the given Intent that is already * running, then it is stopped and {@code true} is returned; else {@code false} is returned. * * @throws SecurityException If the caller does not have permission to access the service * or the service can not be found. * @throws IllegalStateException If the application is in a state where the service * can not be started (such as not in the foreground in a state when services are allowed). * * @see #startService */ public abstract boolean stopService(Intent service); /** * @hide like {@link #startService(Intent)} but for a specific user. */ @Nullable @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public abstract ComponentName startServiceAsUser(Intent service, UserHandle user); /** * @hide like {@link #stopService(Intent)} but for a specific user. */ @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public abstract boolean stopServiceAsUser(Intent service, UserHandle user); /** * Connect to an application service, creating it if needed. This defines * a dependency between your application and the service. The given * <var>conn</var> will receive the service object when it is created and be * told if it dies and restarts. The service will be considered required * by the system only for as long as the calling context exists. For * example, if this Context is an Activity that is stopped, the service will * not be required to continue running until the Activity is resumed. * * <p>This function will throw {@link SecurityException} if you do not * have permission to bind to the given service. * * <p class="note">Note: this method <em>can not be called from a * {@link BroadcastReceiver} component</em>. A pattern you can use to * communicate from a BroadcastReceiver to a Service is to call * {@link #startService} with the arguments containing the command to be * sent, with the service calling its * {@link android.app.Service#stopSelf(int)} method when done executing * that command. See the API demo App/Service/Service Start Arguments * Controller for an illustration of this. It is okay, however, to use * this method from a BroadcastReceiver that has been registered with * {@link #registerReceiver}, since the lifetime of this BroadcastReceiver * is tied to another object (the one that registered it).</p> * * @param service Identifies the service to connect to. The Intent must * specify an explicit component name. * @param conn Receives information as the service is started and stopped. * This must be a valid ServiceConnection object; it must not be null. * @param flags Operation options for the binding. May be 0, * {@link #BIND_AUTO_CREATE}, {@link #BIND_DEBUG_UNBIND}, * {@link #BIND_NOT_FOREGROUND}, {@link #BIND_ABOVE_CLIENT}, * {@link #BIND_ALLOW_OOM_MANAGEMENT}, or * {@link #BIND_WAIVE_PRIORITY}. * @return If you have successfully bound to the service, {@code true} is returned; * {@code false} is returned if the connection is not made so you will not * receive the service object. However, you should still call * {@link #unbindService} to release the connection. * * @throws SecurityException If the caller does not have permission to access the service * or the service can not be found. * * @see #unbindService * @see #startService * @see #BIND_AUTO_CREATE * @see #BIND_DEBUG_UNBIND * @see #BIND_NOT_FOREGROUND */ public abstract boolean bindService(@RequiresPermission Intent service, @NonNull ServiceConnection conn, @BindServiceFlags int flags); /** * Same as {@link #bindService(Intent, ServiceConnection, int)}, but with an explicit userHandle * argument for use by system server and other multi-user aware code. * @hide */ @SystemApi @SuppressWarnings("unused") @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public boolean bindServiceAsUser(@RequiresPermission Intent service, ServiceConnection conn, int flags, UserHandle user) { throw new RuntimeException("Not implemented. Must override in a subclass."); } /** * Same as {@link #bindService(Intent, ServiceConnection, int, UserHandle)}, but with an * explicit non-null Handler to run the ServiceConnection callbacks on. * * @hide */ @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags, Handler handler, UserHandle user) { throw new RuntimeException("Not implemented. Must override in a subclass."); } /** * Disconnect from an application service. You will no longer receive * calls as the service is restarted, and the service is now allowed to * stop at any time. * * @param conn The connection interface previously supplied to * bindService(). This parameter must not be null. * * @see #bindService */ public abstract void unbindService(@NonNull ServiceConnection conn); /** * Start executing an {@link android.app.Instrumentation} class. The given * Instrumentation component will be run by killing its target application * (if currently running), starting the target process, instantiating the * instrumentation component, and then letting it drive the application. * * <p>This function is not synchronous -- it returns as soon as the * instrumentation has started and while it is running. * * <p>Instrumentation is normally only allowed to run against a package * that is either unsigned or signed with a signature that the * the instrumentation package is also signed with (ensuring the target * trusts the instrumentation). * * @param className Name of the Instrumentation component to be run. * @param profileFile Optional path to write profiling data as the * instrumentation runs, or null for no profiling. * @param arguments Additional optional arguments to pass to the * instrumentation, or null. * * @return {@code true} if the instrumentation was successfully started, * else {@code false} if it could not be found. */ public abstract boolean startInstrumentation(@NonNull ComponentName className, @Nullable String profileFile, @Nullable Bundle arguments); /** @hide */ @StringDef({ POWER_SERVICE, WINDOW_SERVICE, LAYOUT_INFLATER_SERVICE, ACCOUNT_SERVICE, ACTIVITY_SERVICE, ALARM_SERVICE, NOTIFICATION_SERVICE, ACCESSIBILITY_SERVICE, CAPTIONING_SERVICE, KEYGUARD_SERVICE, LOCATION_SERVICE, //@hide: COUNTRY_DETECTOR, SEARCH_SERVICE, SENSOR_SERVICE, STORAGE_SERVICE, STORAGE_STATS_SERVICE, WALLPAPER_SERVICE, TIME_ZONE_RULES_MANAGER_SERVICE, VIBRATOR_SERVICE, //@hide: STATUS_BAR_SERVICE, CONNECTIVITY_SERVICE, IPSEC_SERVICE, //@hide: UPDATE_LOCK_SERVICE, //@hide: NETWORKMANAGEMENT_SERVICE, NETWORK_STATS_SERVICE, //@hide: NETWORK_POLICY_SERVICE, WIFI_SERVICE, WIFI_AWARE_SERVICE, WIFI_P2P_SERVICE, WIFI_SCANNING_SERVICE, //@hide: LOWPAN_SERVICE, //@hide: WIFI_RTT_SERVICE, //@hide: ETHERNET_SERVICE, WIFI_RTT_SERVICE, NSD_SERVICE, AUDIO_SERVICE, FINGERPRINT_SERVICE, MEDIA_ROUTER_SERVICE, TELEPHONY_SERVICE, TELEPHONY_SUBSCRIPTION_SERVICE, CARRIER_CONFIG_SERVICE, TELECOM_SERVICE, CLIPBOARD_SERVICE, INPUT_METHOD_SERVICE, TEXT_SERVICES_MANAGER_SERVICE, TEXT_CLASSIFICATION_SERVICE, APPWIDGET_SERVICE, //@hide: VOICE_INTERACTION_MANAGER_SERVICE, //@hide: BACKUP_SERVICE, DROPBOX_SERVICE, //@hide: DEVICE_IDLE_CONTROLLER, DEVICE_POLICY_SERVICE, UI_MODE_SERVICE, DOWNLOAD_SERVICE, NFC_SERVICE, BLUETOOTH_SERVICE, //@hide: SIP_SERVICE, USB_SERVICE, LAUNCHER_APPS_SERVICE, //@hide: SERIAL_SERVICE, //@hide: HDMI_CONTROL_SERVICE, INPUT_SERVICE, DISPLAY_SERVICE, USER_SERVICE, RESTRICTIONS_SERVICE, APP_OPS_SERVICE, CAMERA_SERVICE, PRINT_SERVICE, CONSUMER_IR_SERVICE, //@hide: TRUST_SERVICE, TV_INPUT_SERVICE, //@hide: NETWORK_SCORE_SERVICE, USAGE_STATS_SERVICE, MEDIA_SESSION_SERVICE, BATTERY_SERVICE, JOB_SCHEDULER_SERVICE, //@hide: PERSISTENT_DATA_BLOCK_SERVICE, //@hide: OEM_LOCK_SERVICE, MEDIA_PROJECTION_SERVICE, MIDI_SERVICE, RADIO_SERVICE, HARDWARE_PROPERTIES_SERVICE, //@hide: SOUND_TRIGGER_SERVICE, SHORTCUT_SERVICE, //@hide: CONTEXTHUB_SERVICE, SYSTEM_HEALTH_SERVICE, //@hide: INCIDENT_SERVICE, COMPANION_DEVICE_SERVICE }) @Retention(RetentionPolicy.SOURCE) public @interface ServiceName {} /** * Return the handle to a system-level service by name. The class of the * returned object varies by the requested name. Currently available names * are: * * <dl> * <dt> {@link #WINDOW_SERVICE} ("window") * <dd> The top-level window manager in which you can place custom * windows. The returned object is a {@link android.view.WindowManager}. * <dt> {@link #LAYOUT_INFLATER_SERVICE} ("layout_inflater") * <dd> A {@link android.view.LayoutInflater} for inflating layout resources * in this context. * <dt> {@link #ACTIVITY_SERVICE} ("activity") * <dd> A {@link android.app.ActivityManager} for interacting with the * global activity state of the system. * <dt> {@link #POWER_SERVICE} ("power") * <dd> A {@link android.os.PowerManager} for controlling power * management. * <dt> {@link #ALARM_SERVICE} ("alarm") * <dd> A {@link android.app.AlarmManager} for receiving intents at the * time of your choosing. * <dt> {@link #NOTIFICATION_SERVICE} ("notification") * <dd> A {@link android.app.NotificationManager} for informing the user * of background events. * <dt> {@link #KEYGUARD_SERVICE} ("keyguard") * <dd> A {@link android.app.KeyguardManager} for controlling keyguard. * <dt> {@link #LOCATION_SERVICE} ("location") * <dd> A {@link android.location.LocationManager} for controlling location * (e.g., GPS) updates. * <dt> {@link #SEARCH_SERVICE} ("search") * <dd> A {@link android.app.SearchManager} for handling search. * <dt> {@link #VIBRATOR_SERVICE} ("vibrator") * <dd> A {@link android.os.Vibrator} for interacting with the vibrator * hardware. * <dt> {@link #CONNECTIVITY_SERVICE} ("connection") * <dd> A {@link android.net.ConnectivityManager ConnectivityManager} for * handling management of network connections. * <dt> {@link #WIFI_SERVICE} ("wifi") * <dd> A {@link android.net.wifi.WifiManager WifiManager} for management of Wi-Fi * connectivity. On releases before NYC, it should only be obtained from an application * context, and not from any other derived context to avoid memory leaks within the calling * process. * <dt> {@link #WIFI_AWARE_SERVICE} ("wifiaware") * <dd> A {@link android.net.wifi.aware.WifiAwareManager WifiAwareManager} for management of * Wi-Fi Aware discovery and connectivity. * <dt> {@link #WIFI_P2P_SERVICE} ("wifip2p") * <dd> A {@link android.net.wifi.p2p.WifiP2pManager WifiP2pManager} for management of * Wi-Fi Direct connectivity. * <dt> {@link #INPUT_METHOD_SERVICE} ("input_method") * <dd> An {@link android.view.inputmethod.InputMethodManager InputMethodManager} * for management of input methods. * <dt> {@link #UI_MODE_SERVICE} ("uimode") * <dd> An {@link android.app.UiModeManager} for controlling UI modes. * <dt> {@link #DOWNLOAD_SERVICE} ("download") * <dd> A {@link android.app.DownloadManager} for requesting HTTP downloads * <dt> {@link #BATTERY_SERVICE} ("batterymanager") * <dd> A {@link android.os.BatteryManager} for managing battery state * <dt> {@link #JOB_SCHEDULER_SERVICE} ("taskmanager") * <dd> A {@link android.app.job.JobScheduler} for managing scheduled tasks * <dt> {@link #NETWORK_STATS_SERVICE} ("netstats") * <dd> A {@link android.app.usage.NetworkStatsManager NetworkStatsManager} for querying network * usage statistics. * <dt> {@link #HARDWARE_PROPERTIES_SERVICE} ("hardware_properties") * <dd> A {@link android.os.HardwarePropertiesManager} for accessing hardware properties. * </dl> * * <p>Note: System services obtained via this API may be closely associated with * the Context in which they are obtained from. In general, do not share the * service objects between various different contexts (Activities, Applications, * Services, Providers, etc.) * * @param name The name of the desired service. * * @return The service or null if the name does not exist. * * @see #WINDOW_SERVICE * @see android.view.WindowManager * @see #LAYOUT_INFLATER_SERVICE * @see android.view.LayoutInflater * @see #ACTIVITY_SERVICE * @see android.app.ActivityManager * @see #POWER_SERVICE * @see android.os.PowerManager * @see #ALARM_SERVICE * @see android.app.AlarmManager * @see #NOTIFICATION_SERVICE * @see android.app.NotificationManager * @see #KEYGUARD_SERVICE * @see android.app.KeyguardManager * @see #LOCATION_SERVICE * @see android.location.LocationManager * @see #SEARCH_SERVICE * @see android.app.SearchManager * @see #SENSOR_SERVICE * @see android.hardware.SensorManager * @see #STORAGE_SERVICE * @see android.os.storage.StorageManager * @see #VIBRATOR_SERVICE * @see android.os.Vibrator * @see #CONNECTIVITY_SERVICE * @see android.net.ConnectivityManager * @see #WIFI_SERVICE * @see android.net.wifi.WifiManager * @see #AUDIO_SERVICE * @see android.media.AudioManager * @see #MEDIA_ROUTER_SERVICE * @see android.media.MediaRouter * @see #TELEPHONY_SERVICE * @see android.telephony.TelephonyManager * @see #TELEPHONY_SUBSCRIPTION_SERVICE * @see android.telephony.SubscriptionManager * @see #CARRIER_CONFIG_SERVICE * @see android.telephony.CarrierConfigManager * @see #INPUT_METHOD_SERVICE * @see android.view.inputmethod.InputMethodManager * @see #UI_MODE_SERVICE * @see android.app.UiModeManager * @see #DOWNLOAD_SERVICE * @see android.app.DownloadManager * @see #BATTERY_SERVICE * @see android.os.BatteryManager * @see #JOB_SCHEDULER_SERVICE * @see android.app.job.JobScheduler * @see #NETWORK_STATS_SERVICE * @see android.app.usage.NetworkStatsManager * @see android.os.HardwarePropertiesManager * @see #HARDWARE_PROPERTIES_SERVICE */ public abstract @Nullable Object getSystemService(@ServiceName @NonNull String name); /** * Return the handle to a system-level service by class. * <p> * Currently available classes are: * {@link android.view.WindowManager}, {@link android.view.LayoutInflater}, * {@link android.app.ActivityManager}, {@link android.os.PowerManager}, * {@link android.app.AlarmManager}, {@link android.app.NotificationManager}, * {@link android.app.KeyguardManager}, {@link android.location.LocationManager}, * {@link android.app.SearchManager}, {@link android.os.Vibrator}, * {@link android.net.ConnectivityManager}, * {@link android.net.wifi.WifiManager}, * {@link android.media.AudioManager}, {@link android.media.MediaRouter}, * {@link android.telephony.TelephonyManager}, {@link android.telephony.SubscriptionManager}, * {@link android.view.inputmethod.InputMethodManager}, * {@link android.app.UiModeManager}, {@link android.app.DownloadManager}, * {@link android.os.BatteryManager}, {@link android.app.job.JobScheduler}, * {@link android.app.usage.NetworkStatsManager}. * </p><p> * Note: System services obtained via this API may be closely associated with * the Context in which they are obtained from. In general, do not share the * service objects between various different contexts (Activities, Applications, * Services, Providers, etc.) * </p> * * @param serviceClass The class of the desired service. * @return The service or null if the class is not a supported system service. */ @SuppressWarnings("unchecked") public final @Nullable <T> T getSystemService(@NonNull Class<T> serviceClass) { // Because subclasses may override getSystemService(String) we cannot // perform a lookup by class alone. We must first map the class to its // service name then invoke the string-based method. String serviceName = getSystemServiceName(serviceClass); return serviceName != null ? (T)getSystemService(serviceName) : null; } /** * Gets the name of the system-level service that is represented by the specified class. * * @param serviceClass The class of the desired service. * @return The service name or null if the class is not a supported system service. */ public abstract @Nullable String getSystemServiceName(@NonNull Class<?> serviceClass); /** * Use with {@link #getSystemService} to retrieve a * {@link android.os.PowerManager} for controlling power management, * including "wake locks," which let you keep the device on while * you're running long tasks. */ public static final String POWER_SERVICE = "power"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.os.RecoverySystem} for accessing the recovery system * service. * * @see #getSystemService * @hide */ public static final String RECOVERY_SERVICE = "recovery"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.view.WindowManager} for accessing the system's window * manager. * * @see #getSystemService * @see android.view.WindowManager */ public static final String WINDOW_SERVICE = "window"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.view.LayoutInflater} for inflating layout resources in this * context. * * @see #getSystemService * @see android.view.LayoutInflater */ public static final String LAYOUT_INFLATER_SERVICE = "layout_inflater"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.accounts.AccountManager} for receiving intents at a * time of your choosing. * * @see #getSystemService * @see android.accounts.AccountManager */ public static final String ACCOUNT_SERVICE = "account"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.app.ActivityManager} for interacting with the global * system state. * * @see #getSystemService * @see android.app.ActivityManager */ public static final String ACTIVITY_SERVICE = "activity"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.app.AlarmManager} for receiving intents at a * time of your choosing. * * @see #getSystemService * @see android.app.AlarmManager */ public static final String ALARM_SERVICE = "alarm"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.app.NotificationManager} for informing the user of * background events. * * @see #getSystemService * @see android.app.NotificationManager */ public static final String NOTIFICATION_SERVICE = "notification"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.view.accessibility.AccessibilityManager} for giving the user * feedback for UI events through the registered event listeners. * * @see #getSystemService * @see android.view.accessibility.AccessibilityManager */ public static final String ACCESSIBILITY_SERVICE = "accessibility"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.view.accessibility.CaptioningManager} for obtaining * captioning properties and listening for changes in captioning * preferences. * * @see #getSystemService * @see android.view.accessibility.CaptioningManager */ public static final String CAPTIONING_SERVICE = "captioning"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.app.NotificationManager} for controlling keyguard. * * @see #getSystemService * @see android.app.KeyguardManager */ public static final String KEYGUARD_SERVICE = "keyguard"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.location.LocationManager} for controlling location * updates. * * @see #getSystemService * @see android.location.LocationManager */ public static final String LOCATION_SERVICE = "location"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.location.CountryDetector} for detecting the country that * the user is in. * * @hide */ public static final String COUNTRY_DETECTOR = "country_detector"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.app.SearchManager} for handling searches. * * @see #getSystemService * @see android.app.SearchManager */ public static final String SEARCH_SERVICE = "search"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.hardware.SensorManager} for accessing sensors. * * @see #getSystemService * @see android.hardware.SensorManager */ public static final String SENSOR_SERVICE = "sensor"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.os.storage.StorageManager} for accessing system storage * functions. * * @see #getSystemService * @see android.os.storage.StorageManager */ public static final String STORAGE_SERVICE = "storage"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.app.usage.StorageStatsManager} for accessing system storage * statistics. * * @see #getSystemService * @see android.app.usage.StorageStatsManager */ public static final String STORAGE_STATS_SERVICE = "storagestats"; /** * Use with {@link #getSystemService} to retrieve a * com.android.server.WallpaperService for accessing wallpapers. * * @see #getSystemService */ public static final String WALLPAPER_SERVICE = "wallpaper"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.os.Vibrator} for interacting with the vibration hardware. * * @see #getSystemService * @see android.os.Vibrator */ public static final String VIBRATOR_SERVICE = "vibrator"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.app.StatusBarManager} for interacting with the status bar. * * @see #getSystemService * @see android.app.StatusBarManager * @hide */ public static final String STATUS_BAR_SERVICE = "statusbar"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.net.ConnectivityManager} for handling management of * network connections. * * @see #getSystemService * @see android.net.ConnectivityManager */ public static final String CONNECTIVITY_SERVICE = "connectivity"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.net.IpSecManager} for encrypting Sockets or Networks with * IPSec. * * @hide * @see #getSystemService */ public static final String IPSEC_SERVICE = "ipsec"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.os.IUpdateLock} for managing runtime sequences that * must not be interrupted by headless OTA application or similar. * * @hide * @see #getSystemService * @see android.os.UpdateLock */ public static final String UPDATE_LOCK_SERVICE = "updatelock"; /** * Constant for the internal network management service, not really a Context service. * @hide */ public static final String NETWORKMANAGEMENT_SERVICE = "network_management"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.app.usage.NetworkStatsManager} for querying network usage stats. * * @see #getSystemService * @see android.app.usage.NetworkStatsManager */ public static final String NETWORK_STATS_SERVICE = "netstats"; /** {@hide} */ public static final String NETWORK_POLICY_SERVICE = "netpolicy"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.net.wifi.WifiManager} for handling management of * Wi-Fi access. * * @see #getSystemService * @see android.net.wifi.WifiManager */ public static final String WIFI_SERVICE = "wifi"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.net.wifi.p2p.WifiP2pManager} for handling management of * Wi-Fi peer-to-peer connections. * * @see #getSystemService * @see android.net.wifi.p2p.WifiP2pManager */ public static final String WIFI_P2P_SERVICE = "wifip2p"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.net.wifi.aware.WifiAwareManager} for handling management of * Wi-Fi Aware. * * @see #getSystemService * @see android.net.wifi.aware.WifiAwareManager */ public static final String WIFI_AWARE_SERVICE = "wifiaware"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.net.wifi.WifiScanner} for scanning the wifi universe * * @see #getSystemService * @see android.net.wifi.WifiScanner * @hide */ @SystemApi public static final String WIFI_SCANNING_SERVICE = "wifiscanner"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.net.wifi.RttManager} for ranging devices with wifi * * @see #getSystemService * @see android.net.wifi.RttManager * @hide */ @SystemApi public static final String WIFI_RTT_SERVICE = "rttmanager"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.net.lowpan.LowpanManager} for handling management of * LoWPAN access. * * @see #getSystemService * @see android.net.lowpan.LowpanManager * * @hide */ public static final String LOWPAN_SERVICE = "lowpan"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.net.EthernetManager} for handling management of * Ethernet access. * * @see #getSystemService * @see android.net.EthernetManager * * @hide */ public static final String ETHERNET_SERVICE = "ethernet"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.net.nsd.NsdManager} for handling management of network service * discovery * * @see #getSystemService * @see android.net.nsd.NsdManager */ public static final String NSD_SERVICE = "servicediscovery"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.media.AudioManager} for handling management of volume, * ringer modes and audio routing. * * @see #getSystemService * @see android.media.AudioManager */ public static final String AUDIO_SERVICE = "audio"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.hardware.fingerprint.FingerprintManager} for handling management * of fingerprints. * * @see #getSystemService * @see android.hardware.fingerprint.FingerprintManager */ public static final String FINGERPRINT_SERVICE = "fingerprint"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.media.MediaRouter} for controlling and managing * routing of media. * * @see #getSystemService * @see android.media.MediaRouter */ public static final String MEDIA_ROUTER_SERVICE = "media_router"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.media.session.MediaSessionManager} for managing media Sessions. * * @see #getSystemService * @see android.media.session.MediaSessionManager */ public static final String MEDIA_SESSION_SERVICE = "media_session"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.telephony.TelephonyManager} for handling management the * telephony features of the device. * * @see #getSystemService * @see android.telephony.TelephonyManager */ public static final String TELEPHONY_SERVICE = "phone"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.telephony.SubscriptionManager} for handling management the * telephony subscriptions of the device. * * @see #getSystemService * @see android.telephony.SubscriptionManager */ public static final String TELEPHONY_SUBSCRIPTION_SERVICE = "telephony_subscription_service"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.telecom.TelecomManager} to manage telecom-related features * of the device. * * @see #getSystemService * @see android.telecom.TelecomManager */ public static final String TELECOM_SERVICE = "telecom"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.telephony.CarrierConfigManager} for reading carrier configuration values. * * @see #getSystemService * @see android.telephony.CarrierConfigManager */ public static final String CARRIER_CONFIG_SERVICE = "carrier_config"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.telephony.euicc.EuiccManager} to manage the device eUICC (embedded SIM). * * @see #getSystemService * @see android.telephony.euicc.EuiccManager * TODO(b/35851809): Unhide this API. * @hide */ public static final String EUICC_SERVICE = "euicc_service"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.text.ClipboardManager} for accessing and modifying * {@link android.content.ClipboardManager} for accessing and modifying * the contents of the global clipboard. * * @see #getSystemService * @see android.content.ClipboardManager */ public static final String CLIPBOARD_SERVICE = "clipboard"; /** * Use with {@link #getSystemService} to retrieve a * {@link TextClassificationManager} for text classification services. * * @see #getSystemService * @see TextClassificationManager */ public static final String TEXT_CLASSIFICATION_SERVICE = "textclassification"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.view.inputmethod.InputMethodManager} for accessing input * methods. * * @see #getSystemService */ public static final String INPUT_METHOD_SERVICE = "input_method"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.view.textservice.TextServicesManager} for accessing * text services. * * @see #getSystemService */ public static final String TEXT_SERVICES_MANAGER_SERVICE = "textservices"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.appwidget.AppWidgetManager} for accessing AppWidgets. * * @see #getSystemService */ public static final String APPWIDGET_SERVICE = "appwidget"; /** * Official published name of the (internal) voice interaction manager service. * * @hide * @see #getSystemService */ public static final String VOICE_INTERACTION_MANAGER_SERVICE = "voiceinteraction"; /** * Official published name of the (internal) autofill service. * * @hide * @see #getSystemService */ public static final String AUTOFILL_MANAGER_SERVICE = "autofill"; /** * Use with {@link #getSystemService} to access the * {@link com.android.server.voiceinteraction.SoundTriggerService}. * * @hide * @see #getSystemService */ public static final String SOUND_TRIGGER_SERVICE = "soundtrigger"; /** * Use with {@link #getSystemService} to retrieve an * {@link android.app.backup.IBackupManager IBackupManager} for communicating * with the backup mechanism. * @hide * * @see #getSystemService */ @SystemApi public static final String BACKUP_SERVICE = "backup"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.os.DropBoxManager} instance for recording * diagnostic logs. * @see #getSystemService */ public static final String DROPBOX_SERVICE = "dropbox"; /** * System service name for the DeviceIdleController. There is no Java API for this. * @see #getSystemService * @hide */ public static final String DEVICE_IDLE_CONTROLLER = "deviceidle"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.app.admin.DevicePolicyManager} for working with global * device policy management. * * @see #getSystemService */ public static final String DEVICE_POLICY_SERVICE = "device_policy"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.app.UiModeManager} for controlling UI modes. * * @see #getSystemService */ public static final String UI_MODE_SERVICE = "uimode"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.app.DownloadManager} for requesting HTTP downloads. * * @see #getSystemService */ public static final String DOWNLOAD_SERVICE = "download"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.os.BatteryManager} for managing battery state. * * @see #getSystemService */ public static final String BATTERY_SERVICE = "batterymanager"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.nfc.NfcManager} for using NFC. * * @see #getSystemService */ public static final String NFC_SERVICE = "nfc"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.bluetooth.BluetoothManager} for using Bluetooth. * * @see #getSystemService */ public static final String BLUETOOTH_SERVICE = "bluetooth"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.net.sip.SipManager} for accessing the SIP related service. * * @see #getSystemService */ /** @hide */ public static final String SIP_SERVICE = "sip"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.hardware.usb.UsbManager} for access to USB devices (as a USB host) * and for controlling this device's behavior as a USB device. * * @see #getSystemService * @see android.hardware.usb.UsbManager */ public static final String USB_SERVICE = "usb"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.hardware.SerialManager} for access to serial ports. * * @see #getSystemService * @see android.hardware.SerialManager * * @hide */ public static final String SERIAL_SERVICE = "serial"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.hardware.hdmi.HdmiControlManager} for controlling and managing * HDMI-CEC protocol. * * @see #getSystemService * @see android.hardware.hdmi.HdmiControlManager * @hide */ @SystemApi public static final String HDMI_CONTROL_SERVICE = "hdmi_control"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.hardware.input.InputManager} for interacting with input devices. * * @see #getSystemService * @see android.hardware.input.InputManager */ public static final String INPUT_SERVICE = "input"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.hardware.display.DisplayManager} for interacting with display devices. * * @see #getSystemService * @see android.hardware.display.DisplayManager */ public static final String DISPLAY_SERVICE = "display"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.os.UserManager} for managing users on devices that support multiple users. * * @see #getSystemService * @see android.os.UserManager */ public static final String USER_SERVICE = "user"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.content.pm.LauncherApps} for querying and monitoring launchable apps across * profiles of a user. * * @see #getSystemService * @see android.content.pm.LauncherApps */ public static final String LAUNCHER_APPS_SERVICE = "launcherapps"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.content.RestrictionsManager} for retrieving application restrictions * and requesting permissions for restricted operations. * @see #getSystemService * @see android.content.RestrictionsManager */ public static final String RESTRICTIONS_SERVICE = "restrictions"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.app.AppOpsManager} for tracking application operations * on the device. * * @see #getSystemService * @see android.app.AppOpsManager */ public static final String APP_OPS_SERVICE = "appops"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.hardware.camera2.CameraManager} for interacting with * camera devices. * * @see #getSystemService * @see android.hardware.camera2.CameraManager */ public static final String CAMERA_SERVICE = "camera"; /** * {@link android.print.PrintManager} for printing and managing * printers and print tasks. * * @see #getSystemService * @see android.print.PrintManager */ public static final String PRINT_SERVICE = "print"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.companion.CompanionDeviceManager} for managing companion devices * * @see #getSystemService * @see android.companion.CompanionDeviceManager */ public static final String COMPANION_DEVICE_SERVICE = "companiondevice"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.hardware.ConsumerIrManager} for transmitting infrared * signals from the device. * * @see #getSystemService * @see android.hardware.ConsumerIrManager */ public static final String CONSUMER_IR_SERVICE = "consumer_ir"; /** * {@link android.app.trust.TrustManager} for managing trust agents. * @see #getSystemService * @see android.app.trust.TrustManager * @hide */ public static final String TRUST_SERVICE = "trust"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.media.tv.TvInputManager} for interacting with TV inputs * on the device. * * @see #getSystemService * @see android.media.tv.TvInputManager */ public static final String TV_INPUT_SERVICE = "tv_input"; /** * {@link android.net.NetworkScoreManager} for managing network scoring. * @see #getSystemService * @see android.net.NetworkScoreManager * @hide */ @SystemApi public static final String NETWORK_SCORE_SERVICE = "network_score"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.app.usage.UsageStatsManager} for querying device usage stats. * * @see #getSystemService * @see android.app.usage.UsageStatsManager */ public static final String USAGE_STATS_SERVICE = "usagestats"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.app.job.JobScheduler} instance for managing occasional * background tasks. * @see #getSystemService * @see android.app.job.JobScheduler */ public static final String JOB_SCHEDULER_SERVICE = "jobscheduler"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.service.persistentdata.PersistentDataBlockManager} instance * for interacting with a storage device that lives across factory resets. * * @see #getSystemService * @see android.service.persistentdata.PersistentDataBlockManager * @hide */ @SystemApi public static final String PERSISTENT_DATA_BLOCK_SERVICE = "persistent_data_block"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.service.oemlock.OemLockManager} instance for managing the OEM lock. * * @see #getSystemService * @see android.service.oemlock.OemLockManager * @hide */ @SystemApi public static final String OEM_LOCK_SERVICE = "oem_lock"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.media.projection.MediaProjectionManager} instance for managing * media projection sessions. * @see #getSystemService * @see android.media.projection.MediaProjectionManager */ public static final String MEDIA_PROJECTION_SERVICE = "media_projection"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.media.midi.MidiManager} for accessing the MIDI service. * * @see #getSystemService */ public static final String MIDI_SERVICE = "midi"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.hardware.radio.RadioManager} for accessing the broadcast radio service. * * @see #getSystemService * @hide */ public static final String RADIO_SERVICE = "broadcastradio"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.os.HardwarePropertiesManager} for accessing the hardware properties service. * * @see #getSystemService */ public static final String HARDWARE_PROPERTIES_SERVICE = "hardware_properties"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.content.pm.ShortcutManager} for accessing the launcher shortcut service. * * @see #getSystemService * @see android.content.pm.ShortcutManager */ public static final String SHORTCUT_SERVICE = "shortcut"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.hardware.location.ContextHubManager} for accessing context hubs. * * @see #getSystemService * @see android.hardware.location.ContextHubManager * * @hide */ @SystemApi public static final String CONTEXTHUB_SERVICE = "contexthub"; /** * Use with {@link #getSystemService} to retrieve a * {@link android.os.health.SystemHealthManager} for accessing system health (battery, power, * memory, etc) metrics. * * @see #getSystemService */ public static final String SYSTEM_HEALTH_SERVICE = "systemhealth"; /** * Gatekeeper Service. * @hide */ public static final String GATEKEEPER_SERVICE = "android.service.gatekeeper.IGateKeeperService"; /** * Service defining the policy for access to device identifiers. * @hide */ public static final String DEVICE_IDENTIFIERS_SERVICE = "device_identifiers"; /** * Service to report a system health "incident" * @hide */ public static final String INCIDENT_SERVICE = "incident"; /** * Use with {@link #getSystemService} to retrieve a {@link * android.content.om.OverlayManager} for managing overlay packages. * * @see #getSystemService * @see android.content.om.OverlayManager * @hide */ public static final String OVERLAY_SERVICE = "overlay"; /** * Use with {@link #getSystemService} to retrieve a * {@link VrManager} for accessing the VR service. * * @see #getSystemService * @hide */ @SystemApi public static final String VR_SERVICE = "vrmanager"; /** * Use with {@link #getSystemService} to retrieve an * {@link android.app.timezone.ITimeZoneRulesManager}. * @hide * * @see #getSystemService */ public static final String TIME_ZONE_RULES_MANAGER_SERVICE = "timezone"; /** * Determine whether the given permission is allowed for a particular * process and user ID running in the system. * * @param permission The name of the permission being checked. * @param pid The process ID being checked against. Must be > 0. * @param uid The user ID being checked against. A uid of 0 is the root * user, which will pass every permission check. * * @return {@link PackageManager#PERMISSION_GRANTED} if the given * pid/uid is allowed that permission, or * {@link PackageManager#PERMISSION_DENIED} if it is not. * * @see PackageManager#checkPermission(String, String) * @see #checkCallingPermission */ @CheckResult(suggest="#enforcePermission(String,int,int,String)") @PackageManager.PermissionResult public abstract int checkPermission(@NonNull String permission, int pid, int uid); /** @hide */ @PackageManager.PermissionResult public abstract int checkPermission(@NonNull String permission, int pid, int uid, IBinder callerToken); /** * Determine whether the calling process of an IPC you are handling has been * granted a particular permission. This is basically the same as calling * {@link #checkPermission(String, int, int)} with the pid and uid returned * by {@link android.os.Binder#getCallingPid} and * {@link android.os.Binder#getCallingUid}. One important difference * is that if you are not currently processing an IPC, this function * will always fail. This is done to protect against accidentally * leaking permissions; you can use {@link #checkCallingOrSelfPermission} * to avoid this protection. * * @param permission The name of the permission being checked. * * @return {@link PackageManager#PERMISSION_GRANTED} if the calling * pid/uid is allowed that permission, or * {@link PackageManager#PERMISSION_DENIED} if it is not. * * @see PackageManager#checkPermission(String, String) * @see #checkPermission * @see #checkCallingOrSelfPermission */ @CheckResult(suggest="#enforceCallingPermission(String,String)") @PackageManager.PermissionResult public abstract int checkCallingPermission(@NonNull String permission); /** * Determine whether the calling process of an IPC <em>or you</em> have been * granted a particular permission. This is the same as * {@link #checkCallingPermission}, except it grants your own permissions * if you are not currently processing an IPC. Use with care! * * @param permission The name of the permission being checked. * * @return {@link PackageManager#PERMISSION_GRANTED} if the calling * pid/uid is allowed that permission, or * {@link PackageManager#PERMISSION_DENIED} if it is not. * * @see PackageManager#checkPermission(String, String) * @see #checkPermission * @see #checkCallingPermission */ @CheckResult(suggest="#enforceCallingOrSelfPermission(String,String)") @PackageManager.PermissionResult public abstract int checkCallingOrSelfPermission(@NonNull String permission); /** * Determine whether <em>you</em> have been granted a particular permission. * * @param permission The name of the permission being checked. * * @return {@link PackageManager#PERMISSION_GRANTED} if you have the * permission, or {@link PackageManager#PERMISSION_DENIED} if not. * * @see PackageManager#checkPermission(String, String) * @see #checkCallingPermission(String) */ @PackageManager.PermissionResult public abstract int checkSelfPermission(@NonNull String permission); /** * If the given permission is not allowed for a particular process * and user ID running in the system, throw a {@link SecurityException}. * * @param permission The name of the permission being checked. * @param pid The process ID being checked against. Must be &gt; 0. * @param uid The user ID being checked against. A uid of 0 is the root * user, which will pass every permission check. * @param message A message to include in the exception if it is thrown. * * @see #checkPermission(String, int, int) */ public abstract void enforcePermission( @NonNull String permission, int pid, int uid, @Nullable String message); /** * If the calling process of an IPC you are handling has not been * granted a particular permission, throw a {@link * SecurityException}. This is basically the same as calling * {@link #enforcePermission(String, int, int, String)} with the * pid and uid returned by {@link android.os.Binder#getCallingPid} * and {@link android.os.Binder#getCallingUid}. One important * difference is that if you are not currently processing an IPC, * this function will always throw the SecurityException. This is * done to protect against accidentally leaking permissions; you * can use {@link #enforceCallingOrSelfPermission} to avoid this * protection. * * @param permission The name of the permission being checked. * @param message A message to include in the exception if it is thrown. * * @see #checkCallingPermission(String) */ public abstract void enforceCallingPermission( @NonNull String permission, @Nullable String message); /** * If neither you nor the calling process of an IPC you are * handling has been granted a particular permission, throw a * {@link SecurityException}. This is the same as {@link * #enforceCallingPermission}, except it grants your own * permissions if you are not currently processing an IPC. Use * with care! * * @param permission The name of the permission being checked. * @param message A message to include in the exception if it is thrown. * * @see #checkCallingOrSelfPermission(String) */ public abstract void enforceCallingOrSelfPermission( @NonNull String permission, @Nullable String message); /** * Grant permission to access a specific Uri to another package, regardless * of whether that package has general permission to access the Uri's * content provider. This can be used to grant specific, temporary * permissions, typically in response to user interaction (such as the * user opening an attachment that you would like someone else to * display). * * <p>Normally you should use {@link Intent#FLAG_GRANT_READ_URI_PERMISSION * Intent.FLAG_GRANT_READ_URI_PERMISSION} or * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} with the Intent being used to * start an activity instead of this function directly. If you use this * function directly, you should be sure to call * {@link #revokeUriPermission} when the target should no longer be allowed * to access it. * * <p>To succeed, the content provider owning the Uri must have set the * {@link android.R.styleable#AndroidManifestProvider_grantUriPermissions * grantUriPermissions} attribute in its manifest or included the * {@link android.R.styleable#AndroidManifestGrantUriPermission * &lt;grant-uri-permissions&gt;} tag. * * @param toPackage The package you would like to allow to access the Uri. * @param uri The Uri you would like to grant access to. * @param modeFlags The desired access modes. * * @see #revokeUriPermission */ public abstract void grantUriPermission(String toPackage, Uri uri, @Intent.GrantUriMode int modeFlags); /** * Remove all permissions to access a particular content provider Uri * that were previously added with {@link #grantUriPermission} or <em>any other</em> mechanism. * The given Uri will match all previously granted Uris that are the same or a * sub-path of the given Uri. That is, revoking "content://foo/target" will * revoke both "content://foo/target" and "content://foo/target/sub", but not * "content://foo". It will not remove any prefix grants that exist at a * higher level. * * <p>Prior to {@link android.os.Build.VERSION_CODES#LOLLIPOP}, if you did not have * regular permission access to a Uri, but had received access to it through * a specific Uri permission grant, you could not revoke that grant with this * function and a {@link SecurityException} would be thrown. As of * {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this function will not throw a security * exception, but will remove whatever permission grants to the Uri had been given to the app * (or none).</p> * * <p>Unlike {@link #revokeUriPermission(String, Uri, int)}, this method impacts all permission * grants matching the given Uri, for any package they had been granted to, through any * mechanism this had happened (such as indirectly through the clipboard, activity launch, * service start, etc). That means this can be potentially dangerous to use, as it can * revoke grants that another app could be strongly expecting to stick around.</p> * * @param uri The Uri you would like to revoke access to. * @param modeFlags The access modes to revoke. * * @see #grantUriPermission */ public abstract void revokeUriPermission(Uri uri, @Intent.AccessUriMode int modeFlags); /** * Remove permissions to access a particular content provider Uri * that were previously added with {@link #grantUriPermission} for a specific target * package. The given Uri will match all previously granted Uris that are the same or a * sub-path of the given Uri. That is, revoking "content://foo/target" will * revoke both "content://foo/target" and "content://foo/target/sub", but not * "content://foo". It will not remove any prefix grants that exist at a * higher level. * * <p>Unlike {@link #revokeUriPermission(Uri, int)}, this method will <em>only</em> * revoke permissions that had been explicitly granted through {@link #grantUriPermission} * and only for the package specified. Any matching grants that have happened through * other mechanisms (clipboard, activity launching, service starting, etc) will not be * removed.</p> * * @param toPackage The package you had previously granted access to. * @param uri The Uri you would like to revoke access to. * @param modeFlags The access modes to revoke. * * @see #grantUriPermission */ public abstract void revokeUriPermission(String toPackage, Uri uri, @Intent.AccessUriMode int modeFlags); /** * Determine whether a particular process and user ID has been granted * permission to access a specific URI. This only checks for permissions * that have been explicitly granted -- if the given process/uid has * more general access to the URI's content provider then this check will * always fail. * * @param uri The uri that is being checked. * @param pid The process ID being checked against. Must be &gt; 0. * @param uid The user ID being checked against. A uid of 0 is the root * user, which will pass every permission check. * @param modeFlags The access modes to check. * * @return {@link PackageManager#PERMISSION_GRANTED} if the given * pid/uid is allowed to access that uri, or * {@link PackageManager#PERMISSION_DENIED} if it is not. * * @see #checkCallingUriPermission */ @CheckResult(suggest="#enforceUriPermission(Uri,int,int,String)") @PackageManager.PermissionResult public abstract int checkUriPermission(Uri uri, int pid, int uid, @Intent.AccessUriMode int modeFlags); /** @hide */ @PackageManager.PermissionResult public abstract int checkUriPermission(Uri uri, int pid, int uid, @Intent.AccessUriMode int modeFlags, IBinder callerToken); /** * Determine whether the calling process and user ID has been * granted permission to access a specific URI. This is basically * the same as calling {@link #checkUriPermission(Uri, int, int, * int)} with the pid and uid returned by {@link * android.os.Binder#getCallingPid} and {@link * android.os.Binder#getCallingUid}. One important difference is * that if you are not currently processing an IPC, this function * will always fail. * * @param uri The uri that is being checked. * @param modeFlags The access modes to check. * * @return {@link PackageManager#PERMISSION_GRANTED} if the caller * is allowed to access that uri, or * {@link PackageManager#PERMISSION_DENIED} if it is not. * * @see #checkUriPermission(Uri, int, int, int) */ @CheckResult(suggest="#enforceCallingUriPermission(Uri,int,String)") @PackageManager.PermissionResult public abstract int checkCallingUriPermission(Uri uri, @Intent.AccessUriMode int modeFlags); /** * Determine whether the calling process of an IPC <em>or you</em> has been granted * permission to access a specific URI. This is the same as * {@link #checkCallingUriPermission}, except it grants your own permissions * if you are not currently processing an IPC. Use with care! * * @param uri The uri that is being checked. * @param modeFlags The access modes to check. * * @return {@link PackageManager#PERMISSION_GRANTED} if the caller * is allowed to access that uri, or * {@link PackageManager#PERMISSION_DENIED} if it is not. * * @see #checkCallingUriPermission */ @CheckResult(suggest="#enforceCallingOrSelfUriPermission(Uri,int,String)") @PackageManager.PermissionResult public abstract int checkCallingOrSelfUriPermission(Uri uri, @Intent.AccessUriMode int modeFlags); /** * Check both a Uri and normal permission. This allows you to perform * both {@link #checkPermission} and {@link #checkUriPermission} in one * call. * * @param uri The Uri whose permission is to be checked, or null to not * do this check. * @param readPermission The permission that provides overall read access, * or null to not do this check. * @param writePermission The permission that provides overall write * access, or null to not do this check. * @param pid The process ID being checked against. Must be &gt; 0. * @param uid The user ID being checked against. A uid of 0 is the root * user, which will pass every permission check. * @param modeFlags The access modes to check. * * @return {@link PackageManager#PERMISSION_GRANTED} if the caller * is allowed to access that uri or holds one of the given permissions, or * {@link PackageManager#PERMISSION_DENIED} if it is not. */ @CheckResult(suggest="#enforceUriPermission(Uri,String,String,int,int,int,String)") @PackageManager.PermissionResult public abstract int checkUriPermission(@Nullable Uri uri, @Nullable String readPermission, @Nullable String writePermission, int pid, int uid, @Intent.AccessUriMode int modeFlags); /** * If a particular process and user ID has not been granted * permission to access a specific URI, throw {@link * SecurityException}. This only checks for permissions that have * been explicitly granted -- if the given process/uid has more * general access to the URI's content provider then this check * will always fail. * * @param uri The uri that is being checked. * @param pid The process ID being checked against. Must be &gt; 0. * @param uid The user ID being checked against. A uid of 0 is the root * user, which will pass every permission check. * @param modeFlags The access modes to enforce. * @param message A message to include in the exception if it is thrown. * * @see #checkUriPermission(Uri, int, int, int) */ public abstract void enforceUriPermission( Uri uri, int pid, int uid, @Intent.AccessUriMode int modeFlags, String message); /** * If the calling process and user ID has not been granted * permission to access a specific URI, throw {@link * SecurityException}. This is basically the same as calling * {@link #enforceUriPermission(Uri, int, int, int, String)} with * the pid and uid returned by {@link * android.os.Binder#getCallingPid} and {@link * android.os.Binder#getCallingUid}. One important difference is * that if you are not currently processing an IPC, this function * will always throw a SecurityException. * * @param uri The uri that is being checked. * @param modeFlags The access modes to enforce. * @param message A message to include in the exception if it is thrown. * * @see #checkCallingUriPermission(Uri, int) */ public abstract void enforceCallingUriPermission( Uri uri, @Intent.AccessUriMode int modeFlags, String message); /** * If the calling process of an IPC <em>or you</em> has not been * granted permission to access a specific URI, throw {@link * SecurityException}. This is the same as {@link * #enforceCallingUriPermission}, except it grants your own * permissions if you are not currently processing an IPC. Use * with care! * * @param uri The uri that is being checked. * @param modeFlags The access modes to enforce. * @param message A message to include in the exception if it is thrown. * * @see #checkCallingOrSelfUriPermission(Uri, int) */ public abstract void enforceCallingOrSelfUriPermission( Uri uri, @Intent.AccessUriMode int modeFlags, String message); /** * Enforce both a Uri and normal permission. This allows you to perform * both {@link #enforcePermission} and {@link #enforceUriPermission} in one * call. * * @param uri The Uri whose permission is to be checked, or null to not * do this check. * @param readPermission The permission that provides overall read access, * or null to not do this check. * @param writePermission The permission that provides overall write * access, or null to not do this check. * @param pid The process ID being checked against. Must be &gt; 0. * @param uid The user ID being checked against. A uid of 0 is the root * user, which will pass every permission check. * @param modeFlags The access modes to enforce. * @param message A message to include in the exception if it is thrown. * * @see #checkUriPermission(Uri, String, String, int, int, int) */ public abstract void enforceUriPermission( @Nullable Uri uri, @Nullable String readPermission, @Nullable String writePermission, int pid, int uid, @Intent.AccessUriMode int modeFlags, @Nullable String message); /** @hide */ @IntDef(flag = true, prefix = { "CONTEXT_" }, value = { CONTEXT_INCLUDE_CODE, CONTEXT_IGNORE_SECURITY, CONTEXT_RESTRICTED, CONTEXT_DEVICE_PROTECTED_STORAGE, CONTEXT_CREDENTIAL_PROTECTED_STORAGE, CONTEXT_REGISTER_PACKAGE, }) @Retention(RetentionPolicy.SOURCE) public @interface CreatePackageOptions {} /** * Flag for use with {@link #createPackageContext}: include the application * code with the context. This means loading code into the caller's * process, so that {@link #getClassLoader()} can be used to instantiate * the application's classes. Setting this flags imposes security * restrictions on what application context you can access; if the * requested application can not be safely loaded into your process, * java.lang.SecurityException will be thrown. If this flag is not set, * there will be no restrictions on the packages that can be loaded, * but {@link #getClassLoader} will always return the default system * class loader. */ public static final int CONTEXT_INCLUDE_CODE = 0x00000001; /** * Flag for use with {@link #createPackageContext}: ignore any security * restrictions on the Context being requested, allowing it to always * be loaded. For use with {@link #CONTEXT_INCLUDE_CODE} to allow code * to be loaded into a process even when it isn't safe to do so. Use * with extreme care! */ public static final int CONTEXT_IGNORE_SECURITY = 0x00000002; /** * Flag for use with {@link #createPackageContext}: a restricted context may * disable specific features. For instance, a View associated with a restricted * context would ignore particular XML attributes. */ public static final int CONTEXT_RESTRICTED = 0x00000004; /** * Flag for use with {@link #createPackageContext}: point all file APIs at * device-protected storage. * * @hide */ public static final int CONTEXT_DEVICE_PROTECTED_STORAGE = 0x00000008; /** * Flag for use with {@link #createPackageContext}: point all file APIs at * credential-protected storage. * * @hide */ public static final int CONTEXT_CREDENTIAL_PROTECTED_STORAGE = 0x00000010; /** * @hide Used to indicate we should tell the activity manager about the process * loading this code. */ public static final int CONTEXT_REGISTER_PACKAGE = 0x40000000; /** * Return a new Context object for the given application name. This * Context is the same as what the named application gets when it is * launched, containing the same resources and class loader. Each call to * this method returns a new instance of a Context object; Context objects * are not shared, however they share common state (Resources, ClassLoader, * etc) so the Context instance itself is fairly lightweight. * * <p>Throws {@link android.content.pm.PackageManager.NameNotFoundException} if there is no * application with the given package name. * * <p>Throws {@link java.lang.SecurityException} if the Context requested * can not be loaded into the caller's process for security reasons (see * {@link #CONTEXT_INCLUDE_CODE} for more information}. * * @param packageName Name of the application's package. * @param flags Option flags. * * @return A {@link Context} for the application. * * @throws SecurityException &nbsp; * @throws PackageManager.NameNotFoundException if there is no application with * the given package name. */ public abstract Context createPackageContext(String packageName, @CreatePackageOptions int flags) throws PackageManager.NameNotFoundException; /** * Similar to {@link #createPackageContext(String, int)}, but with a * different {@link UserHandle}. For example, {@link #getContentResolver()} * will open any {@link Uri} as the given user. * * @hide */ public abstract Context createPackageContextAsUser( String packageName, @CreatePackageOptions int flags, UserHandle user) throws PackageManager.NameNotFoundException; /** * Creates a context given an {@link android.content.pm.ApplicationInfo}. * * @hide */ public abstract Context createApplicationContext(ApplicationInfo application, @CreatePackageOptions int flags) throws PackageManager.NameNotFoundException; /** * Return a new Context object for the given split name. The new Context has a ClassLoader and * Resources object that can access the split's and all of its dependencies' code/resources. * Each call to this method returns a new instance of a Context object; * Context objects are not shared, however common state (ClassLoader, other Resources for * the same split) may be so the Context itself can be fairly lightweight. * * @param splitName The name of the split to include, as declared in the split's * <code>AndroidManifest.xml</code>. * @return A {@link Context} with the given split's code and/or resources loaded. */ public abstract Context createContextForSplit(String splitName) throws PackageManager.NameNotFoundException; /** * Get the userId associated with this context * @return user id * * @hide */ @TestApi public abstract @UserIdInt int getUserId(); /** * Return a new Context object for the current Context but whose resources * are adjusted to match the given Configuration. Each call to this method * returns a new instance of a Context object; Context objects are not * shared, however common state (ClassLoader, other Resources for the * same configuration) may be so the Context itself can be fairly lightweight. * * @param overrideConfiguration A {@link Configuration} specifying what * values to modify in the base Configuration of the original Context's * resources. If the base configuration changes (such as due to an * orientation change), the resources of this context will also change except * for those that have been explicitly overridden with a value here. * * @return A {@link Context} with the given configuration override. */ public abstract Context createConfigurationContext( @NonNull Configuration overrideConfiguration); /** * Return a new Context object for the current Context but whose resources * are adjusted to match the metrics of the given Display. Each call to this method * returns a new instance of a Context object; Context objects are not * shared, however common state (ClassLoader, other Resources for the * same configuration) may be so the Context itself can be fairly lightweight. * * The returned display Context provides a {@link WindowManager} * (see {@link #getSystemService(String)}) that is configured to show windows * on the given display. The WindowManager's {@link WindowManager#getDefaultDisplay} * method can be used to retrieve the Display from the returned Context. * * @param display A {@link Display} object specifying the display * for whose metrics the Context's resources should be tailored and upon which * new windows should be shown. * * @return A {@link Context} for the display. */ public abstract Context createDisplayContext(@NonNull Display display); /** * Return a new Context object for the current Context but whose storage * APIs are backed by device-protected storage. * <p> * On devices with direct boot, data stored in this location is encrypted * with a key tied to the physical device, and it can be accessed * immediately after the device has booted successfully, both * <em>before and after</em> the user has authenticated with their * credentials (such as a lock pattern or PIN). * <p> * Because device-protected data is available without user authentication, * you should carefully limit the data you store using this Context. For * example, storing sensitive authentication tokens or passwords in the * device-protected area is strongly discouraged. * <p> * If the underlying device does not have the ability to store * device-protected and credential-protected data using different keys, then * both storage areas will become available at the same time. They remain as * two distinct storage locations on disk, and only the window of * availability changes. * <p> * Each call to this method returns a new instance of a Context object; * Context objects are not shared, however common state (ClassLoader, other * Resources for the same configuration) may be so the Context itself can be * fairly lightweight. * * @see #isDeviceProtectedStorage() */ public abstract Context createDeviceProtectedStorageContext(); /** * Return a new Context object for the current Context but whose storage * APIs are backed by credential-protected storage. This is the default * storage area for apps unless * {@link android.R.attr#defaultToDeviceProtectedStorage} was requested. * <p> * On devices with direct boot, data stored in this location is encrypted * with a key tied to user credentials, which can be accessed * <em>only after</em> the user has entered their credentials (such as a * lock pattern or PIN). * <p> * If the underlying device does not have the ability to store * device-protected and credential-protected data using different keys, then * both storage areas will become available at the same time. They remain as * two distinct storage locations on disk, and only the window of * availability changes. * <p> * Each call to this method returns a new instance of a Context object; * Context objects are not shared, however common state (ClassLoader, other * Resources for the same configuration) may be so the Context itself can be * fairly lightweight. * * @see #isCredentialProtectedStorage() * @hide */ @SystemApi public abstract Context createCredentialProtectedStorageContext(); /** * Gets the display adjustments holder for this context. This information * is provided on a per-application or activity basis and is used to simulate lower density * display metrics for legacy applications and restricted screen sizes. * * @param displayId The display id for which to get compatibility info. * @return The compatibility info holder, or null if not required by the application. * @hide */ public abstract DisplayAdjustments getDisplayAdjustments(int displayId); /** * @hide */ public abstract Display getDisplay(); /** * @hide */ public abstract void updateDisplay(int displayId); /** * Indicates whether this Context is restricted. * * @return {@code true} if this Context is restricted, {@code false} otherwise. * * @see #CONTEXT_RESTRICTED */ public boolean isRestricted() { return false; } /** * Indicates if the storage APIs of this Context are backed by * device-protected storage. * * @see #createDeviceProtectedStorageContext() */ public abstract boolean isDeviceProtectedStorage(); /** * Indicates if the storage APIs of this Context are backed by * credential-protected storage. * * @see #createCredentialProtectedStorageContext() * @hide */ @SystemApi public abstract boolean isCredentialProtectedStorage(); /** * Returns true if the context can load unsafe resources, e.g. fonts. * @hide */ public abstract boolean canLoadUnsafeResources(); /** * @hide */ public IBinder getActivityToken() { throw new RuntimeException("Not implemented. Must override in a subclass."); } /** * @hide */ @Nullable public IServiceConnection getServiceDispatcher(ServiceConnection conn, Handler handler, int flags) { throw new RuntimeException("Not implemented. Must override in a subclass."); } /** * @hide */ public IApplicationThread getIApplicationThread() { throw new RuntimeException("Not implemented. Must override in a subclass."); } /** * @hide */ public Handler getMainThreadHandler() { throw new RuntimeException("Not implemented. Must override in a subclass."); } /** * @hide */ public AutofillClient getAutofillClient() { return null; } /** * @hide */ public void setAutofillClient(AutofillClient client) { } /** * Throws an exception if the Context is using system resources, * which are non-runtime-overlay-themable and may show inconsistent UI. * @hide */ public void assertRuntimeOverlayThemable() { // Resources.getSystem() is a singleton and the only Resources not managed by // ResourcesManager; therefore Resources.getSystem() is not themable. if (getResources() == Resources.getSystem()) { throw new IllegalArgumentException("Non-UI context used to display UI; " + "get a UI context from ActivityThread#getSystemUiContext()"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.servicefabric; import com.azure.core.util.Context; /** Samples for Services List. */ public final class ServicesListSamples { /* * operationId: Services_List * api-version: 2021-06-01 * x-ms-examples: Get a list of service resources */ /** * Sample code: Get a list of service resources. * * @param manager Entry point to ServiceFabricManager. */ public static void getAListOfServiceResources( com.azure.resourcemanager.servicefabric.ServiceFabricManager manager) { manager.services().listWithResponse("resRg", "myCluster", "myApp", Context.NONE); } }
/* * Copyright <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://www.apache.org/licenses/LICENSE-2.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 software.amazon.timestream.jdbc; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EmptySource; import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.util.Arrays; import java.util.Properties; import java.util.function.Function; class TimestreamDriverTest { private MockTimestreamDriver driver; @BeforeEach void init() { driver = new MockTimestreamDriver(); } @ParameterizedTest @ValueSource(strings = { Constants.URL_PREFIX, Constants.URL_PREFIX + " ", " " + Constants.URL_PREFIX, Constants.URL_PREFIX + Constants.URL_BRIDGE, Constants.URL_PREFIX + Constants.URL_BRIDGE + " ", " " + Constants.URL_PREFIX + Constants.URL_BRIDGE, Constants.URL_PREFIX + Constants.URL_BRIDGE + "foo"}) void testAcceptsURLWithValidUrlPrefix(final String url) { Assertions.assertTrue(driver.acceptsURL(url)); } @ParameterizedTest @NullAndEmptySource @ValueSource(strings = { "jDbC:TimeSTREam", "jdbc:timestream ://", Constants.URL_PREFIX + " " + Constants.URL_BRIDGE, "foo", Constants.URL_PREFIX + "foo"}) void testAcceptsURLWithInvalidUrl(final String url) { Assertions.assertFalse(driver.acceptsURL(url)); } @Test void testConnectWithNullUrlNullProperties() throws SQLException { Assertions.assertNull(driver.connect(null, null)); } @ParameterizedTest @ValueSource(strings = { Constants.URL_PREFIX, Constants.URL_PREFIX + Constants.URL_BRIDGE, Constants.URL_PREFIX + " ", Constants.URL_PREFIX + Constants.URL_BRIDGE + " "}) void testConnectWithValidUrlNullProperties(final String url) throws SQLException { final TimestreamConnection connection = driver.connect(url, null); final Properties constructedProperties = connection.getClientInfo(); Assertions.assertNotNull(connection); Assertions.assertEquals(new Properties(), constructedProperties); } @ParameterizedTest @ValueSource(strings = { Constants.URL_PREFIX + Constants.URL_BRIDGE + "ApplicationName=Tableau", Constants.URL_PREFIX + Constants.URL_BRIDGE + "ApplicationName =Tableau", Constants.URL_PREFIX + Constants.URL_BRIDGE + " ApplicationName=Tableau", Constants.URL_PREFIX + Constants.URL_BRIDGE + " ApplicationName =Tableau; UnsupportedProperty =value"}) void testConnectWithValidAndHasPropertiesInUrlNullProperties(final String url) throws SQLException { final TimestreamConnection connection = driver.connect(url, null); final Properties constructedProperties = connection.getClientInfo(); final Properties expectedProperties = new Properties(); expectedProperties.put("ApplicationName", "Tableau"); Assertions.assertNotNull(connection); Assertions.assertEquals(expectedProperties, constructedProperties); } @Test void testConnectWithNullUrlValidProperties() throws SQLException { final Properties prop = new Properties(); prop.put(TimestreamConnectionProperty.ACCESS_KEY_ID.getConnectionProperty(), "foo"); prop.put(TimestreamConnectionProperty.SECRET_ACCESS_KEY.getConnectionProperty(), "bar"); Assertions.assertNull(driver.connect(null, prop)); } @ParameterizedTest @ValueSource(strings = { Constants.URL_PREFIX, Constants.URL_PREFIX + Constants.URL_BRIDGE}) void testConnectWithValidUrlValidProperties(final String url) throws SQLException { final Properties inputProperties = new Properties(); inputProperties.put(TimestreamConnectionProperty.ACCESS_KEY_ID.getConnectionProperty(), "foo"); inputProperties.put(TimestreamConnectionProperty.SECRET_ACCESS_KEY.getConnectionProperty(), "bar"); final TimestreamConnection connection = driver.connect(url, inputProperties); final Properties constructedProperties = connection.getClientInfo(); final Properties expected = new Properties(); expected.put(TimestreamConnectionProperty.ACCESS_KEY_ID.getConnectionProperty(), "foo"); expected.put(TimestreamConnectionProperty.SECRET_ACCESS_KEY.getConnectionProperty(), "bar"); Assertions.assertNotNull(connection); Assertions.assertEquals(expected, constructedProperties); } @ParameterizedTest @ValueSource(strings = { Constants.URL_PREFIX + Constants.URL_BRIDGE + "endpoint=endpoint.com", Constants.URL_PREFIX + Constants.URL_BRIDGE + "region=ca-central-1"}) void testConnectWithInvalidCasingUrlEmptyProperties(final String url) throws SQLException { final TimestreamConnection connection = driver.connect(url, new Properties()); final Properties constructedProperties = connection.getClientInfo(); Assertions.assertNotNull(connection); Assertions.assertEquals(new Properties(), constructedProperties); } @ParameterizedTest @ValueSource(strings = { Constants.URL_PREFIX, Constants.URL_PREFIX + Constants.URL_BRIDGE}) void testConnectWithValidUrlInvalidCasingProperties(final String url) throws SQLException { final Properties inputProperties = new Properties(); inputProperties.put(TimestreamConnectionProperty.REGION.getConnectionProperty().toLowerCase(), "ca-central-1"); inputProperties.put(TimestreamConnectionProperty.ENDPOINT.getConnectionProperty().toLowerCase(), "endpoint.com"); final TimestreamConnection connection = driver.connect(url, inputProperties); final Properties constructedProperties = connection.getClientInfo(); Assertions.assertNotNull(connection); Assertions.assertEquals(new Properties(), constructedProperties); } @Test void testConnectWithDifferentProperties() throws SQLException { final String url = Constants.URL_PREFIX + Constants.URL_BRIDGE + TimestreamConnectionProperty.ACCESS_KEY_ID .getConnectionProperty() + "=foo"; final Properties inputProperties = new Properties(); inputProperties.put(TimestreamConnectionProperty.SECRET_ACCESS_KEY.getConnectionProperty(), "bar"); final TimestreamConnection connection = driver.connect(url, inputProperties); final Properties constructedProperties = connection.getClientInfo(); final Properties expected = new Properties(); expected.put(TimestreamConnectionProperty.ACCESS_KEY_ID.getConnectionProperty(), "foo"); expected.put(TimestreamConnectionProperty.SECRET_ACCESS_KEY.getConnectionProperty(), "bar"); Assertions.assertNotNull(connection); Assertions.assertEquals(expected, constructedProperties); } @Test void testConnectWithDuplicateProperties() throws SQLException { final String url = Constants.URL_PREFIX + Constants.URL_BRIDGE + TimestreamConnectionProperty.ACCESS_KEY_ID .getConnectionProperty() + "=foo"; final Properties info = new Properties(); info.put(TimestreamConnectionProperty.ACCESS_KEY_ID.getConnectionProperty(), "bar"); final TimestreamConnection connection = driver.connect(url, info); Assertions.assertNotNull(connection); final Properties constructedProperties = connection.getClientInfo(); final Properties expected = new Properties(); expected.put(TimestreamConnectionProperty.ACCESS_KEY_ID.getConnectionProperty(), "foo"); Assertions.assertEquals(expected, constructedProperties); } @ParameterizedTest @ValueSource(strings = { Constants.URL_PREFIX + Constants.URL_BRIDGE + "=", Constants.URL_PREFIX + Constants.URL_BRIDGE + " =", Constants.URL_PREFIX + Constants.URL_BRIDGE + "foo=", Constants.URL_PREFIX + Constants.URL_BRIDGE + "=bar", Constants.URL_PREFIX + Constants.URL_BRIDGE + " =bar", Constants.URL_PREFIX + Constants.URL_BRIDGE + "foo==bar", Constants.URL_PREFIX + Constants.URL_BRIDGE + "=foo=bar="}) void testGetPropertyInfoWithInvalidUrl(final String invalidUrl) { Assertions.assertThrows( SQLException.class, () -> driver.getPropertyInfo(invalidUrl, new Properties())); } @Test void testGetPropertyInfoWithValidUrl() throws SQLException { final String validUrl = Constants.URL_PREFIX + Constants.URL_BRIDGE + TimestreamConnectionProperty.ACCESS_KEY_ID.getConnectionProperty() + "=bar"; final DriverPropertyInfo[] expected = createExpectedDriverPropertyList(val -> { final String value; if (val == TimestreamConnectionProperty.ACCESS_KEY_ID) { value = "bar"; } else { value = null; } return createDefaultDriverInfo(val, value); }); validateDriverPropertyInfo(expected, driver.getPropertyInfo(validUrl, new Properties())); } @ParameterizedTest @EmptySource @ValueSource(strings = { Constants.URL_PREFIX, Constants.URL_PREFIX + Constants.URL_BRIDGE, "foo"}) void testGetPropertyInfoWithProperty(final String url) throws SQLException { final Properties prop = new Properties(); prop.put(TimestreamConnectionProperty.ACCESS_KEY_ID.getConnectionProperty(), "foo"); prop.put(TimestreamConnectionProperty.SECRET_ACCESS_KEY.getConnectionProperty(), "bar"); final DriverPropertyInfo[] expected = createExpectedDriverPropertyList(val -> { final String value; if (val == TimestreamConnectionProperty.ACCESS_KEY_ID) { value = "foo"; } else if (val == TimestreamConnectionProperty.SECRET_ACCESS_KEY) { value = "bar"; } else { value = null; } return createDefaultDriverInfo(val, value); }); validateDriverPropertyInfo(expected, driver.getPropertyInfo(url, prop)); } @Test void testGetPropertyInfoWithUrlAndProperty() throws SQLException { final String validUrl = Constants.URL_PREFIX + Constants.URL_BRIDGE + TimestreamConnectionProperty.ACCESS_KEY_ID .getConnectionProperty() + "=bar"; final Properties prop = new Properties(); prop.put(TimestreamConnectionProperty.ACCESS_KEY_ID.getConnectionProperty(), "foo"); final DriverPropertyInfo[] expected = createExpectedDriverPropertyList(val -> { final String value; if (val == TimestreamConnectionProperty.ACCESS_KEY_ID) { value = "bar"; } else { value = null; } return createDefaultDriverInfo(val, value); }); validateDriverPropertyInfo(expected, driver.getPropertyInfo(validUrl, prop)); } /** * Initializes a {@link DriverPropertyInfo} using the given {@link TimestreamConnectionProperty} * and the given value. * * @param property A supported connection property. * @param value The property's value. * @return a {@link DriverPropertyInfo}. */ private DriverPropertyInfo createDefaultDriverInfo(TimestreamConnectionProperty property, final String value) { final DriverPropertyInfo driverPropertyInfo = new DriverPropertyInfo( property.getConnectionProperty(), value); driverPropertyInfo.description = property.getDescription(); return driverPropertyInfo; } /** * Compare the given expected {@link DriverPropertyInfo} array with the actual {@link * DriverPropertyInfo} array retrieved by {@link TimestreamDriver#getPropertyInfo(String, * Properties)}. * * @param expected The expected {@link DriverPropertyInfo} array * @param actual The actual {@link DriverPropertyInfo} array retrieved by {@link * TimestreamDriver#getPropertyInfo(String, Properties)} */ private void validateDriverPropertyInfo( final DriverPropertyInfo[] expected, final DriverPropertyInfo[] actual) { for (int i = 0; i < expected.length; i++) { final DriverPropertyInfo expectedProperty = expected[i]; final DriverPropertyInfo actualProperty = actual[i]; Assertions.assertEquals(expectedProperty.name, actualProperty.name); Assertions.assertEquals(expectedProperty.value, actualProperty.value); Assertions.assertEquals(expectedProperty.description, actualProperty.description); } } /** * Creates a {@link DriverPropertyInfo} array using the populateFunction. * * @param populateFunction A lambda that creates a {@link DriverPropertyInfo} given a {@link * TimestreamConnectionProperty} * @return A {@link DriverPropertyInfo} array. */ private DriverPropertyInfo[] createExpectedDriverPropertyList( Function<TimestreamConnectionProperty, DriverPropertyInfo> populateFunction) { return Arrays .stream(TimestreamConnectionProperty.values()) .map(populateFunction) .toArray(DriverPropertyInfo[]::new); } }
/* * 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.phoenix.spark.datasource.v2; import java.util.Optional; import java.util.Properties; import org.apache.phoenix.spark.datasource.v2.reader.PhoenixDataSourceReader; import org.apache.phoenix.spark.datasource.v2.writer.PhoenixDataSourceWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.spark.sql.SaveMode; import org.apache.spark.sql.sources.DataSourceRegister; import org.apache.spark.sql.sources.v2.DataSourceOptions; import org.apache.spark.sql.sources.v2.DataSourceV2; import org.apache.spark.sql.sources.v2.ReadSupport; import org.apache.spark.sql.sources.v2.WriteSupport; import org.apache.spark.sql.sources.v2.reader.DataSourceReader; import org.apache.spark.sql.sources.v2.writer.DataSourceWriter; import org.apache.spark.sql.types.StructType; /** * Implements the DataSourceV2 api to read and write from Phoenix tables */ public class PhoenixDataSource implements DataSourceV2, ReadSupport, WriteSupport, DataSourceRegister { private static final Logger logger = LoggerFactory.getLogger(PhoenixDataSource.class); public static final String SKIP_NORMALIZING_IDENTIFIER = "skipNormalizingIdentifier"; public static final String ZOOKEEPER_URL = "zkUrl"; public static final String PHOENIX_CONFIGS = "phoenixconfigs"; @Override public DataSourceReader createReader(DataSourceOptions options) { return new PhoenixDataSourceReader(options); } @Override public Optional<DataSourceWriter> createWriter(String writeUUID, StructType schema, SaveMode mode, DataSourceOptions options) { return Optional.of(new PhoenixDataSourceWriter(mode, schema, options)); } /** * Extract HBase and Phoenix properties that need to be set in both the driver and workers. * We expect these properties to be passed against the key * {@link PhoenixDataSource#PHOENIX_CONFIGS}. The corresponding value should be a * comma-separated string containing property names and property values. For example: * prop1=val1,prop2=val2,prop3=val3 * @param options DataSource options passed in * @return Properties map */ public static Properties extractPhoenixHBaseConfFromOptions(final DataSourceOptions options) { Properties confToSet = new Properties(); if (options != null) { Optional phoenixConfigs = options.get(PHOENIX_CONFIGS); if (phoenixConfigs.isPresent()) { String phoenixConf = String.valueOf(phoenixConfigs.get()); String[] confs = phoenixConf.split(","); for (String conf : confs) { String[] confKeyVal = conf.split("="); try { confToSet.setProperty(confKeyVal[0], confKeyVal[1]); } catch (ArrayIndexOutOfBoundsException e) { throw new RuntimeException("Incorrect format for phoenix/HBase configs. " + "Expected format: <prop1>=<val1>,<prop2>=<val2>,<prop3>=<val3>..", e); } } } if (logger.isDebugEnabled()) { logger.debug("Got the following Phoenix/HBase config:\n" + confToSet); } } return confToSet; } @Override public String shortName() { return "phoenix"; } }
package com.gmail.jannyboy11.customrecipes.commands; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.Random; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import com.gmail.jannyboy11.customrecipes.CustomRecipesPlugin; import com.gmail.jannyboy11.customrecipes.impl.crafting.CRCraftingRecipe; import com.gmail.jannyboy11.customrecipes.impl.crafting.custom.recipe.PermissionRecipe; import com.gmail.jannyboy11.customrecipes.impl.crafting.custom.recipe.tobukkit.CRPermissionRecipe; import com.gmail.jannyboy11.customrecipes.impl.crafting.vanilla.recipe.CRShapedRecipe; import com.gmail.jannyboy11.customrecipes.impl.crafting.vanilla.recipe.CRShapelessRecipe; import com.gmail.jannyboy11.customrecipes.impl.furnace.CRFurnaceRecipe; import com.gmail.jannyboy11.customrecipes.impl.furnace.custom.NMSFurnaceRecipe; import com.gmail.jannyboy11.customrecipes.util.NBTUtil; import com.gmail.jannyboy11.customrecipes.util.ReflectionUtil; import net.minecraft.server.v1_12_R1.CraftingManager; import net.minecraft.server.v1_12_R1.IRecipe; import net.minecraft.server.v1_12_R1.ItemStack; import net.minecraft.server.v1_12_R1.MinecraftKey; import net.minecraft.server.v1_12_R1.NBTTagCompound; import net.minecraft.server.v1_12_R1.NBTTagList; import net.minecraft.server.v1_12_R1.NonNullList; import net.minecraft.server.v1_12_R1.RecipeItemStack; import net.minecraft.server.v1_12_R1.RecipesFurnace; import net.minecraft.server.v1_12_R1.ShapedRecipes; import net.minecraft.server.v1_12_R1.ShapelessRecipes; public class MigrateRecipesCommandExecutor implements CommandExecutor { private Random random = new Random(); private int incr = random.nextInt(); private final CustomRecipesPlugin plugin; public MigrateRecipesCommandExecutor(CustomRecipesPlugin plugin) { this.plugin = plugin; } private MinecraftKey nextCustomKey() { return new MinecraftKey("customrecipes", "migrated_" + String.valueOf(incr++)); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { File pluginDataFolder = plugin.getDataFolder(); if (!pluginDataFolder.exists()) { sender.sendMessage(ChatColor.GREEN + "Plugin data folder does not exists, no recipes were migrated."); return true; } File extraRecipesFolder = new File(pluginDataFolder, "extra_recipes"); if (extraRecipesFolder.exists() && extraRecipesFolder.isDirectory()) { migrateExtraRecipes(sender, extraRecipesFolder); } else { sender.sendMessage(ChatColor.RED + "Could not migrate extra recipes, the extra_recipes file does not exist or is not a directory."); } File disabledRecipesFolder = new File(pluginDataFolder, "disabled_recipes"); if (disabledRecipesFolder.exists() && disabledRecipesFolder.isDirectory()) { migrateDisabledRecipes(sender, disabledRecipesFolder); } else { sender.sendMessage(ChatColor.RED + "Could not migrate disabled recipes, the disabled_recipes file does not exist or is not a directory."); } sender.sendMessage(ChatColor.GREEN + "Migration complete! Restart your server for the migrated recipes to take effect."); return true; } private void migrateExtraRecipes(CommandSender sender, File extraFolder) { sender.sendMessage(ChatColor.YELLOW + "Migrating shaped recipes"); //shaped File folder = new File(extraFolder, "shaped_recipes"); if (folder.exists() && folder.isDirectory()) { for (File file : folder.listFiles()) { String name = file.getName(); try { NBTTagCompound readTag = NBTUtil.readNBTTagCompound(file); NBTTagCompound resultTag = readTag.getCompound("Result"); ItemStack result = resultTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(resultTag); int width = readTag.getInt("Width"); int height = readTag.getInt("Height"); NBTTagList nbtIngredients = readTag.getList("Ingredients", NBTUtil.COMPOUND); NonNullList<RecipeItemStack> ingredients = NonNullList.a(width * height, RecipeItemStack.a); for (int i = 0; i < nbtIngredients.size(); i++) { NBTTagCompound ingredientTag = nbtIngredients.get(i); ItemStack ingredientStack = ingredientTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(ingredientTag); RecipeItemStack ingredient = RecipeItemStack.a(new ItemStack[] {ingredientStack}); ingredients.set(i, ingredient); } ShapedRecipes shaped = new ShapedRecipes("", height, height, ingredients, result); MinecraftKey key = nextCustomKey(); shaped.setKey(key); CRShapedRecipe<ShapedRecipes> cr = new CRShapedRecipe<>(shaped); plugin.saveCraftingRecipeFile("shaped", cr); } catch (IOException e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "Something went wrong when migrating shaped recipe " + name + ", please check your console for errors."); } } } sender.sendMessage(ChatColor.YELLOW + "Migrating shapeless recipes"); //shapeless folder = new File(extraFolder, "shapeless_recipes"); if (folder.exists() && folder.isDirectory()) { for (File file : folder.listFiles()) { String name = file.getName(); try { NBTTagCompound readTag = NBTUtil.readNBTTagCompound(file); NBTTagCompound resultTag = readTag.getCompound("Result"); ItemStack result = resultTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(resultTag); NBTTagList nbtIngredients = readTag.getList("Ingredients", NBTUtil.COMPOUND); NonNullList<RecipeItemStack> ingredients = NonNullList.a(nbtIngredients.size(), RecipeItemStack.a); for (int i = 0; i < nbtIngredients.size(); i++) { NBTTagCompound ingredientTag = nbtIngredients.get(i); ItemStack ingredientStack = ingredientTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(ingredientTag); RecipeItemStack ingredient = RecipeItemStack.a(new ItemStack[] {ingredientStack}); ingredients.set(i, ingredient); } ShapelessRecipes shaped = new ShapelessRecipes("", result, ingredients); MinecraftKey key = nextCustomKey(); shaped.setKey(key); CRShapelessRecipe<ShapelessRecipes> cr = new CRShapelessRecipe<>(shaped); plugin.saveCraftingRecipeFile("shapeless", cr); } catch (IOException e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "Something went wrong when migrating shapeless recipe " + name + ", please check your console for errors."); } } } sender.sendMessage(ChatColor.YELLOW + "Migrating permission recipes"); //permission folder = new File(extraFolder, "permission_recipes"); if (folder.exists() && folder.isDirectory()) { for (File file : folder.listFiles()) { String name = file.getName(); try { NBTTagCompound readTag = NBTUtil.readNBTTagCompound(file); NBTTagCompound resultTag = readTag.getCompound("Result"); ItemStack result = resultTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(resultTag); int width = readTag.getInt("Width"); int height = readTag.getInt("Height"); NBTTagList nbtIngredients = readTag.getList("Ingredients", NBTUtil.COMPOUND); NonNullList<RecipeItemStack> ingredients = NonNullList.a(width * height, RecipeItemStack.a); for (int i = 0; i < nbtIngredients.size(); i++) { NBTTagCompound ingredientTag = nbtIngredients.get(i); ItemStack ingredientStack = ingredientTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(ingredientTag); RecipeItemStack ingredient = RecipeItemStack.a(new ItemStack[] {ingredientStack}); ingredients.set(i, ingredient); } String permission = readTag.getString("Permission"); PermissionRecipe shaped = new PermissionRecipe("", height, height, ingredients, result, permission); MinecraftKey key = nextCustomKey(); shaped.setKey(key); CRPermissionRecipe cr = new CRPermissionRecipe(shaped); plugin.saveCraftingRecipeFile("permission", cr); } catch (IOException e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "Something went wrong when migrating permission recipe " + name + ", please check your console for errors."); } } } sender.sendMessage(ChatColor.YELLOW + "Migrating furnace recipes"); //furnace folder = new File(extraFolder, "furnace_recipes"); if (folder.exists() && folder.isDirectory()) { RecipesFurnace recipesFurnace = new RecipesFurnace(); for (File file : folder.listFiles()) { String name = file.getName(); try { NBTTagCompound readTag = NBTUtil.readNBTTagCompound(file); NBTTagCompound resultTag = readTag.getCompound("Result"); ItemStack result = resultTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(resultTag); NBTTagCompound ingredientTag = readTag.getCompound("Ingredient"); ItemStack ingredient = ingredientTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(ingredientTag); float xp = readTag.hasKeyOfType("Experience", NBTUtil.FLOAT) ? readTag.getFloat("Experience") : 0F; RecipeItemStack recipeItemStack = RecipeItemStack.a(new ItemStack[]{ingredient}); NMSFurnaceRecipe furnaceRecipe = new NMSFurnaceRecipe(nextCustomKey(), recipeItemStack, result, xp); CRFurnaceRecipe cr = new CRFurnaceRecipe(furnaceRecipe); plugin.saveFurnaceRecipeFile(cr); } catch (IOException e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "Something went wrong when migrating furnace recipe " + name + ", please check your console for errors."); } } } } private void migrateDisabledRecipes(CommandSender sender, File disabledFolder) { sender.sendMessage(ChatColor.YELLOW + "Migrating disabled shaped recipes"); //shaped File folder = new File(disabledFolder, "shaped_recipes"); if (folder.exists() && folder.isDirectory()) { for (File file : folder.listFiles()) { String name = file.getName(); try { NBTTagCompound readTag = NBTUtil.readNBTTagCompound(file); NBTTagCompound resultTag = readTag.getCompound("Result"); ItemStack result = resultTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(resultTag); int width = readTag.getInt("Width"); int height = readTag.getInt("Height"); NBTTagList nbtIngredients = readTag.getList("Ingredients", NBTUtil.COMPOUND); NonNullList<ItemStack> ingredients = NonNullList.a(width * height, ItemStack.a); for (int i = 0; i < nbtIngredients.size(); i++) { NBTTagCompound ingredientTag = nbtIngredients.get(i); ItemStack ingredientStack = ingredientTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(ingredientTag); ingredients.set(i, ingredientStack); } LegacyShapedRecipe legacyShaped = new LegacyShapedRecipe(width, height, result, ingredients); ShapedRecipes match = null; Iterator<IRecipe> iterator = CraftingManager.recipes.iterator(); //loop until a match was found while (iterator.hasNext() && match == null) { IRecipe serverRecipe = iterator.next(); if (serverRecipe instanceof ShapedRecipes) { ShapedRecipes shaped = (ShapedRecipes) serverRecipe; if (legacyShaped.equalsRecipe(shaped)) { match = shaped; } } } if (match != null) { //very nice! great success! CRShapedRecipe<ShapedRecipes> crShapedRecipe = new CRShapedRecipe<>(match); plugin.disableCraftingRecipeFile("shaped", crShapedRecipe); } else { sender.sendMessage(ChatColor.RED + "Couln't migrate disabled shaped recipe \"" + name + "\", no match was found in the crafting manager. Is it already disabled?"); } } catch (IOException e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "Something went wrong when migrating disabled shaped recipe " + name + ", please check your console for errors."); } } } sender.sendMessage(ChatColor.YELLOW + "Migrating disabled shapeless recipes"); //shapeless folder = new File(disabledFolder, "shapeless_recipes"); if (folder.exists() && folder.isDirectory()) { for (File file : folder.listFiles()) { String name = file.getName(); try { NBTTagCompound readTag = NBTUtil.readNBTTagCompound(file); NBTTagCompound resultTag = readTag.getCompound("Result"); ItemStack result = resultTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(resultTag); NBTTagList nbtIngredients = readTag.getList("Ingredients", NBTUtil.COMPOUND); NonNullList<ItemStack> ingredients = NonNullList.a(nbtIngredients.size(), ItemStack.a); for (int i = 0; i < nbtIngredients.size(); i++) { NBTTagCompound ingredientTag = nbtIngredients.get(i); ItemStack ingredientStack = ingredientTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(ingredientTag); ingredients.set(i, ingredientStack); } LegacyShapelessRecipe legacyShapeless = new LegacyShapelessRecipe(result, ingredients); ShapelessRecipes match = null; Iterator<IRecipe> iterator = CraftingManager.recipes.iterator(); //loop until a match was found while (iterator.hasNext() && match == null) { IRecipe serverRecipe = iterator.next(); if (serverRecipe instanceof ShapelessRecipes) { ShapelessRecipes shapeless = (ShapelessRecipes) serverRecipe; if (legacyShapeless.equalsRecipe(shapeless)) { match = shapeless; } } } if (match != null) { //very nice! great success! CRShapelessRecipe<ShapelessRecipes> crShapedRecipe = new CRShapelessRecipe<>(match); plugin.disableCraftingRecipeFile("shapeless", crShapedRecipe); } else { sender.sendMessage(ChatColor.RED + "Couln't migrate disabled shapeless recipe \"" + name + "\", no match was found in the crafting manager. Is it already disabled?"); } } catch (IOException e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "Something went wrong when migrating disabled shapeless recipe " + name + ", please check your console for errors."); } } } //no disabled permission recipes sender.sendMessage(ChatColor.YELLOW + "Migrating disabled furnace recipes"); //furnace folder = new File(disabledFolder, "furnace_recipes"); if (folder.exists() && folder.isDirectory()) { RecipesFurnace recipesFurnace = new RecipesFurnace(); for (File file : folder.listFiles()) { String name = file.getName(); try { NBTTagCompound readTag = NBTUtil.readNBTTagCompound(file); NBTTagCompound resultTag = readTag.getCompound("Result"); ItemStack result = resultTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(resultTag); NBTTagCompound ingredientTag = readTag.getCompound("Ingredient"); ItemStack ingredient = ingredientTag.isEmpty() ? ItemStack.a : NBTUtil.deserializeItemStack(ingredientTag); float xp = readTag.hasKeyOfType("Experience", NBTUtil.FLOAT) ? readTag.getFloat("Experience") : 0F; RecipeItemStack recipeItemStack = RecipeItemStack.a(new ItemStack[]{ingredient}); NMSFurnaceRecipe furnaceRecipe = new NMSFurnaceRecipe(nextCustomKey(), recipeItemStack, result, xp); CRFurnaceRecipe cr = new CRFurnaceRecipe(furnaceRecipe); plugin.disableFurnaceRecipeFile(cr); } catch (IOException e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "Something went wrong when migrating disabled furnace recipe " + name + ", please check your console for errors."); } } } } //shaped recipe as in minecraft 1.11 and earlier versions. ingredients was just a list of itemstacks private static class LegacyShapedRecipe { private int width; private int heigth; private ItemStack result; private NonNullList<ItemStack> ingredients; public LegacyShapedRecipe(int width, int heigth, ItemStack result, NonNullList<ItemStack> ingredients) { this.width = width; this.heigth = heigth; this.result = result; this.ingredients = ingredients; } public boolean equalsRecipe(ShapedRecipes oneTwelveVersion) { int width = (int) ReflectionUtil.getDeclaredFieldValue(oneTwelveVersion, "width"); if (width != this.width) return false; int heigth = (int) ReflectionUtil.getDeclaredFieldValue(oneTwelveVersion, "height"); if (heigth != this.heigth) return false; ItemStack result = (ItemStack) ReflectionUtil.getDeclaredFieldValue(oneTwelveVersion, "result"); if (!ItemStack.fastMatches(result, this.result)) return false; NonNullList<RecipeItemStack> ingredients = (NonNullList<RecipeItemStack>) ReflectionUtil.getDeclaredFieldValue(oneTwelveVersion, "items"); for (int i = 0; i < ingredients.size(); i++) { RecipeItemStack ingredient = ingredients.get(i); if (!ingredient.a(this.ingredients.get(i))) return false; //legacy ingredient was not accepted by the 1.12 ingredient } return true; } } //shapeless recipe as in minecraft 1.11 and earlier versions private static class LegacyShapelessRecipe { private ItemStack result; private NonNullList<ItemStack> ingredients; public LegacyShapelessRecipe(ItemStack result, NonNullList<ItemStack> ingredients) { this.result = result; this.ingredients = ingredients; } public boolean equalsRecipe(ShapelessRecipes oneTwelveVersion) { ItemStack result = (ItemStack) ReflectionUtil.getDeclaredFieldValue(oneTwelveVersion, "result"); if (!ItemStack.fastMatches(result, this.result)) return false; NonNullList<RecipeItemStack> ingredients = (NonNullList<RecipeItemStack>) ReflectionUtil.getDeclaredFieldValue(oneTwelveVersion, "ingredients"); for (int i = 0; i < ingredients.size(); i++) { RecipeItemStack ingredient = ingredients.get(i); if (!ingredient.a(this.ingredients.get(i))) return false; //legacy ingredient was not accepted by the 1.12 ingredient } return true; } } }
package com.github.Eddyosos.integracao20171.esus.cds.avaliacaoelegibilidade; import br.gov.saude.esus.cds.transport.generated.thrift.avaliacaoelegibilidade.FichaAvaliacaoElegibilidadeThrift; import com.github.Eddyosos.integracao20171.compactor.SerializadorThrift; import com.github.Eddyosos.integracao20171.esus.cds.common.EnderecoLocalPermanencia; import com.github.Eddyosos.integracao20171.esus.cds.common.UnicaLotacaoHeader; import com.github.Eddyosos.integracao20171.esus.transport.DadoTransporte; import com.github.Eddyosos.integracao20171.utils.IDS.CNS; import com.github.eddyosos.e_sus_ab_factory.cds.common.IEnderecoLocalPermanencia; import com.github.eddyosos.e_sus_ab_factory.cds.common.IUnicaLotacaoHeader; import com.github.eddyosos.e_sus_ab_factory.cds.esus.cds.avaliacaoelegibilidade.IFichaAvaliacaoElegibilidade; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class FichaAvaliacaoElegibilidade implements IFichaAvaliacaoElegibilidade { private FichaAvaliacaoElegibilidadeThrift instancia ; private long TIPO_DADO_SERIALIZADO_FICHA_PROCEDIMENTO = 11; private final static String EXTENSAO_EXPORT = ".esus13"; private DadoTransporte dadoTransporteThrift; public FichaAvaliacaoElegibilidade(){ this.instancia = new FichaAvaliacaoElegibilidadeThrift(); } public FichaAvaliacaoElegibilidade(FichaAvaliacaoElegibilidadeThrift fichaAvaliacaoElegibilidade){ this.instancia = fichaAvaliacaoElegibilidade; } /** * Remove todos os dados da ficha. */ @Override public void clear() { instancia.clear(); } /** * Código UUID para identificar a ficha na base de dados nacional. * * Presenca obrigatória. * Tamanho mínimo: 36 * Tamanho maximo: 44 * Regras: É recomendado concatenar o CNES na frente do UUID, * de modo que os 7 digitos (CNES) + 1 de hífen somados aos 36 (32 caracteres + 4 hífen) * do UUID são a limitação de 44 bytes do campo. Formato canônico. * * @return Código uuid. */ @Override public String getUuidFicha() { return instancia.getUuidFicha(); } /** * Define o código uuid da ficha. * @param uuidFicha Código uuid da ficha. */ @Override public void setUuidFicha(String uuidFicha) { instancia.setUuidFicha(uuidFicha); } /** * Remove o código uuid da ficha. */ @Override public void unsetUuidFicha() { instancia.unsetUuidFicha(); } /** * Verifica se o código uuid da ficha foi declarado. * @return True caso o código uuid da ficha tenha sido declarado. */ @Override public boolean isSetUuidFicha() { return instancia.isSetUuidFicha(); } /** * Declara o estado do código uuid da ficha. * @param value True caso o código uuid da ficha tenha sido inserido. */ @Override public void setUuidFichaIsSet(boolean value) { instancia.setUuidFichaIsSet(value); } /** * Tipo de origem dos dados do registro. * @return Tipo de origem dos dados do registro. */ @Override public int getTpCdsOrigem() { return instancia.getTpCdsOrigem(); } /** * Define o tipo de origem dos dados do registro. * * Presenca obrigatória. * Observação: Utilizar valor 3 (sistemas terceiros). * * @param tpCdsOrigem Tipo de origem dos dados do registro. */ @Override public void setTpCdsOrigem(int tpCdsOrigem) { instancia.setTpCdsOrigem(tpCdsOrigem); } /** * Remove o tipo de origem dos dados do registro. */ @Override public void unsetTpCdsOrigem() { instancia.unsetTpCdsOrigem(); } /** * Verifica se o tipo de origem dos dados do registro foi declarado. * @return True caso o tipo de origem dos dados do registro tenha sido inserido. */ @Override public boolean isSetTpCdsOrigem() { return instancia.isSetTpCdsOrigem(); } /** * Declara se o tipo de origem dos dados do registro foi inserido. * @param value True caso o tipo de origem dos dados do registro tenha sido inserido. */ @Override public void setTpCdsOrigemIsSet(boolean value) { instancia.setTpCdsOrigemIsSet(value); } /** * Profissional que realizou a visita. * @return Profissional que realizou a visita. */ @Override public IUnicaLotacaoHeader getHeaderTransport() { return new UnicaLotacaoHeader(instancia.getHeaderTransport()); } /** * Define o profissional que realizou a visita. * * Presenca obrigatória. * * @param headerTransport Profissional que realizou a visita. */ @Override public void setHeaderTransport(IUnicaLotacaoHeader headerTransport) { instancia.setHeaderTransport(headerTransport.getInstance()); } /** * Remove o profissional que realizou a visita. */ @Override public void unsetHeaderTransport() { instancia.unsetHeaderTransport(); } /** * Verifica se o profissional que realizou a visita foi declarado. * @return True caso o profissional que realizou a visita tenha sido inserido. */ @Override public boolean isSetHeaderTransport() { return instancia.isSetHeaderTransport(); } /** * Define se o profissional que realizou a visita doi inserido. * @param value True caso profissional que realizou a visita tenha sido inserido. */ @Override public void setHeaderTransportIsSet(boolean value) { instancia.setHeaderTransportIsSet(value); } /** * CNS do cidadão. * @return CNS do cidadão. */ @Override public String getNumeroCartaoSus() { return instancia.getNumeroCartaoSus(); } /** * CNS do cidadão. * * Presenca obrigatória. * Regras: CNS válido de acordo com o algoritmo. * Tamanho: 15 digitos. * * @param numeroCartaoSus */ @Override public void setNumeroCartaoSus(String numeroCartaoSus) { instancia.setNumeroCartaoSus(numeroCartaoSus); } /** * Remove o CNS do cidadão. */ @Override public void unsetNumeroCartaoSus() { instancia.unsetNumeroCartaoSus(); } /** * Verifica se o CNS do cidadão foi declarado. * @return True caso o CNS do cidadão tenhe sido inserido. */ @Override public boolean isSetNumeroCartaoSus() { return instancia.isSetNumeroCartaoSus(); } /** * Declara se o CNS do cidadão foi inserido. * @param value True caso o CNS do cidadão dtenha sido inserido. */ @Override public void setNumeroCartaoSusIsSet(boolean value) { instancia.setNumeroCartaoSusIsSet(value); } /** * Nome do cidadão. * @return Nome do cidadão */ @Override public String getNomeCidadao() { return instancia.getNomeCidadao(); } /** * Define o nome do cidadão. * * Regra:Ter ao menos duas palavras. * Regra: Somente texto e apóstrofo ('). * Regra:Opcional caso conclusaoDestinoElegivel for diferente de 1 (admissão própria emad). * Tamanho mínimo: 5 * Tamanho máximo: 100; * * @param nomeCidadao Nome do cidadão. */ @Override public void setNomeCidadao(String nomeCidadao) { instancia.setNomeCidadao(nomeCidadao); } /** * Remove o nome do cidadão. */ @Override public void unsetNomeCidadao() { instancia.unsetNomeCidadao(); } /** * Verifica se o nome do cidadão foi declarado. * @return True caso o nome do cidadão tenha sido inserido. */ @Override public boolean isSetNomeCidadao() { return instancia.isSetNomeCidadao(); } /** * Declase se o nome do cidadão foi inserido. * @param value True caso o nome do cidadão tenha sido inserido. */ @Override public void setNomeCidadaoIsSet(boolean value) { instancia.setNomeCidadaoIsSet(value); } /** * Nome social do cidadão. * @return Nome social do cidadão. */ @Override public String getNomeSocialCidadao() { return instancia.getNomeSocialCidadao(); } /** * Define o nome social do cidadão. * * Regra: Somente texto e apóstrofo ('). * Tamanho minimo: 0 * Tamanho máximo: 100 * * @param nomeSocialCidadao Nome social do cidadão. */ @Override public void setNomeSocialCidadao(String nomeSocialCidadao) { instancia.setNomeSocialCidadao(nomeSocialCidadao); } /** * Remove o nome social do cidadão. */ @Override public void unsetNomeSocialCidadao() { instancia.unsetNomeSocialCidadao(); } /** * Verifica se o nome social do cidadão foi declarado. * @return */ @Override public boolean isSetNomeSocialCidadao() { return instancia.isSetNomeSocialCidadao(); } /** * Declara se o cidadão possui um nome social. * @param value True caso o cidadão possua um nome social. */ @Override public void setNomeSocialCidadaoIsSet(boolean value) { instancia.setNomeSocialCidadaoIsSet(value); } /** * Data de nascimento do cidadão. * * Presença obrigatória. * Regras: Não pode ser posterior a dataAtendimento e anterior a 130 anos a partir da dataAtendimento. * * @return Data de nascimento do cidadão no formato epoch time. */ @Override public long getDataNascimentoCidadao() { return instancia.getDataNascimentoCidadao(); } /** * Define a data de nascimento do cidadão. * @param dataNascimentoCidadao Data de nascimento do cidadão */ @Override public void setDataNascimentoCidadao(long dataNascimentoCidadao) { instancia.setDataNascimentoCidadao(dataNascimentoCidadao); } /** * Remove a data de nascimento do cidadão, */ @Override public void unsetDataNascimentoCidadao() { instancia.unsetDataNascimentoCidadao(); } /** * Verifica se a data de nascimento do cidadão foi declarada. * @return True caso a data de nascimento do cidadão tenha sido inserida. */ @Override public boolean isSetDataNascimentoCidadao() { return instancia.isSetDataNascimentoCidadao(); } /** * Define se a data de nascimento do cidadão foi inserida. * @param value True caso a data de nascimento do cidadão tenha sido inserida */ @Override public void setDataNascimentoCidadaoIsSet(boolean value) { instancia.setDataNascimentoCidadaoIsSet(value); } /** * sexo do cidadão. * @return Código do sexo do cidadão. */ @Override public long getSexoCidadao() { return instancia.getSexoCidadao(); } /** * Define o sexo do cidadão. * * Presença obrigatória. * * @param sexoCidadao Código do sexo do cidadão. */ @Override public void setSexoCidadao(long sexoCidadao) { instancia.setSexoCidadao(sexoCidadao); } /** * Remove o sexo do cidadão. */ @Override public void unsetSexoCidadao() { instancia.unsetSexoCidadao(); } /** * Verifica se o sexo foi definido. * @return True caso o sexo tenha sido definido. */ @Override public boolean isSetSexoCidadao() { return instancia.isSetSexoCidadao(); } /** * Retorna se o sexo do cidadão foi definido. * @param value True caso o sexo tenha sido definido. */ @Override public void setSexoCidadaoIsSet(boolean value) { instancia.setSexoCidadaoIsSet(value); } /** * Raça / cor do cidadão. * * @return Código da raça / cor do cidadão. */ @Override public long getRacaCorCidadao() { return instancia.getRacaCorCidadao(); } /** * Raça / cor do cidadão. * * Regra: Opcional caso conclusaoDestinoElegivel for diferente de 1 (admissão própria emad). * * @param racaCorCidadao Código da raça / cor do cidadão. */ @Override public void setRacaCorCidadao(long racaCorCidadao) { instancia.setRacaCorCidadao(racaCorCidadao); } /** * Remove a raça / cor do cidadão. */ @Override public void unsetRacaCorCidadao() { instancia.unsetRacaCorCidadao(); } /** * Verifica se a raça / cor do cidadão foi declarada. * @return True Caso a raça / cor do cidadão tenha sido inserida. */ @Override public boolean isSetRacaCorCidadao() { return instancia.isSetRacaCorCidadao(); } /** * Declara se a raça / cor do cidadão foi inserida * * @param value True caso a raça / cor do cidadão tenha sido inserido. */ @Override public void setRacaCorCidadaoIsSet(boolean value) { instancia.setRacaCorCidadaoIsSet(value); } /** * Nome da mãe do cidadão. * * @return Nome da mãe do cidadão. */ @Override public String getNomeMaeCidadao() { return instancia.getNomeMaeCidadao(); } /** * Define o Nome da mãe do cidadão. * * Regra: Ter ao menos duas palavras. * Regra: Somente texto e apóstrofo ('). * Regra: Não pode ser preenchido se o campo desconheceNomeMae = true. * * @param nomeMaeCidadao Nome da mãe do cidadão. */ @Override public void setNomeMaeCidadao(String nomeMaeCidadao) { instancia.setNomeMaeCidadao(nomeMaeCidadao); } /** * Remove o nome da mãe do cidadão */ @Override public void unsetNomeMaeCidadao() { instancia.unsetNomeMaeCidadao(); } /** * Verifica se o nome da mãe do cidadão foi declarado. * * @return True caso o nome da mãe do cidadão tenha sido declarado. */ @Override public boolean isSetNomeMaeCidadao() { return instancia.isSetNomeMaeCidadao(); } /** * Declara se o nome da mãe do cidadão foi inserido. * * @param value True caso o nome da mãe tenha sido inserido. */ @Override public void setNomeMaeCidadaoIsSet(boolean value) { instancia.setNomeMaeCidadaoIsSet(value); } /** * Verifica se o cidadão conhece o nome da mãe. * * @return True caso o cidadão não conheça o nome da mãe. */ @Override public boolean isDesconheceNomeMae() { return instancia.isDesconheceNomeMae(); } /** * Define se o cidadão não conhece sua mãe. * * @param desconheceNomeMae True caso o cidadão não conheça o nome de sua mãe. */ @Override public void setDesconheceNomeMae(boolean desconheceNomeMae) { instancia.setDesconheceNomeMae(desconheceNomeMae); } /** * Remove o estado de nome da mãe desconhecido. */ @Override public void unsetDesconheceNomeMae() { instancia.unsetDesconheceNomeMae(); } /** * Verifica se o cidadão informou desconhecer o nome da mãe. * * @return True caso desconhecer o nome da mãe tenha sido declarado. */ @Override public boolean isSetDesconheceNomeMae() { return instancia.isSetDesconheceNomeMae(); } /** * Declara se o campo desconhece nome da mãe foi inserido. * @param value True Caso desconhece nome da mãe tenha sido inserido. */ @Override public void setDesconheceNomeMaeIsSet(boolean value) { instancia.setDesconheceNomeMaeIsSet(value); } /** * Município de nascimento do cidadão.. * * @return Código IBGE do município */ @Override public String getCodigoIbgeMunicipioNascimento() { return instancia.getCodigoIbgeMunicipioNascimento(); } /** * Define o município de nascimento do cidadão * * Regras: Não pode ser preenchido se codigoNacionalidade for diferente de 1 (brasileiro). * * @param codigoIbgeMunicipioNascimento Código IBGE do município. */ @Override public void setCodigoIbgeMunicipioNascimento(String codigoIbgeMunicipioNascimento) { instancia.setCodigoIbgeMunicipioNascimento(codigoIbgeMunicipioNascimento); } /** * Remove o município de nascimento do cidadão. */ @Override public void unsetCodigoIbgeMunicipioNascimento() { instancia.unsetCodigoIbgeMunicipioNascimento(); } /** * Verifica se o município de nascimento do cidadão foi declarado. * * @return True Caso o município tenha sido inserido * @return False caso o município não tenha sido inserido. */ @Override public boolean isSetCodigoIbgeMunicipioNascimento() { return instancia.isSetCodigoIbgeMunicipioNascimento(); } /** * Declara se o município de nascimento foi inserido. * * @param value True caso deseje informar que o município foi inserido. */ @Override public void setCodigoIbgeMunicipioNascimentoIsSet(boolean value) { instancia.setCodigoIbgeMunicipioNascimentoIsSet(value); } /** * Indica se o cidadão é brasileiro, naturalizado ou estrangeiro. * * @return Código do marcador que indica se o cidadão é brasileiro, naturalizado ou estrangeiro. */ @Override public long getCodigoNacionalidade() { return instancia.getCodigoNacionalidade(); } /** * Define se o cidadão é brasileiro, naturalizado ou estrangeiro. * * Regra: Opcional caso conclusaoDestinoElegivel for diferente de 1 (admissão própria emad). * * @param codigoNacionalidade Código do marcador que indica se o cidadão é brasileiro, naturalizado ou estrangeiro. */ @Override public void setCodigoNacionalidade(long codigoNacionalidade) { instancia.setCodigoNacionalidade(codigoNacionalidade); } /** * Remove a nacionalidade do cidadão. */ @Override public void unsetCodigoNacionalidade() { instancia.unsetCodigoNacionalidade(); } /** * Verifica se o código de nacionalidade foi declarado. * * @return True Caso o cidadão possua um código de nacionalidade ou False caso o código de nacionalidade não tenha sido informado. */ @Override public boolean isSetCodigoNacionalidade() { return instancia.isSetCodigoNacionalidade(); } /** * Declara que a nacionalidade do cidadão foi inserido. * * @param value True caso deseje informar que a nacionalidade foi inserida. Falso caso ela não tenha sido inserida. */ @Override public void setCodigoNacionalidadeIsSet(boolean value) { instancia.setCodigoNacionalidadeIsSet(value); } /** * Email do cidadão. * * @return Email do cidadão. */ @Override public String getEmailCidadao() { return instancia.getEmailCidadao(); } /** * Define o email do cidadão. * * Regras: Requerido seguir o padrão endereco@domínio.extensão. * Tamanho mínimo: 6 * Tamanho máximo: 255 * * @param emailCidadao Email do cidadão. */ @Override public void setEmailCidadao(String emailCidadao) { instancia.setEmailCidadao(emailCidadao); } /** * Remove o email do cidadão. */ @Override public void unsetEmailCidadao() { instancia.unsetEmailCidadao(); } /** * Verifica se o email do cidadão foi declarado. * * @return True caso o email do cidadão tenha sido declarado, False caso o email não tenha sido declarado. */ @Override public boolean isSetEmailCidadao() { return instancia.isSetEmailCidadao(); } /** * Declara se o email do cidadão foi inserido. * * @param value True caso deseje informar que o email foi inserido, False caso deseje declarar que o cidadão não possui email. */ @Override public void setEmailCidadaoIsSet(boolean value) { instancia.setEmailCidadaoIsSet(value); } /** * Número do PIS/PASEP do cidadão. * * @return Número do PIS/PASEP do cidadão. */ @Override public String getNumeroNisPisPasep() { return instancia.getNumeroNisPisPasep(); } /** * Define o número do PIS/PASEP do cidadão * * Regra: Apenas números. * Tamanho: 11 dígitos * * @param numeroNisPisPasep Número do PIS/PASEP do cidadão. */ @Override public void setNumeroNisPisPasep(String numeroNisPisPasep) { instancia.setNumeroNisPisPasep(numeroNisPisPasep); } /** * Remove o número do PIS/PASEP do cidadão. */ @Override public void unsetNumeroNisPisPasep() { instancia.unsetNumeroNisPisPasep(); } /** * Verifica se o número do PIS/PASEP do cidadão foi declarado. * * @return True caso o número do PIS/PASEP do cidadão tenha sido declarado, False caso o número não tenha sido declarado. */ @Override public boolean isSetNumeroNisPisPasep() { return instancia.isSetNumeroNisPisPasep(); } /** * Declara que o número do PIS/PASEP do cidadão foi inserido. * * @param value True caso deseje informar que o número do PIS/PASEP do cidadão foi inserido, False caso não tenha. */ @Override public void setNumeroNisPisPasepIsSet(boolean value) { instancia.setNumeroNisPisPasepIsSet(value); } /** * Informações sobre o endereço do domicílio * * @return Informações sobre o endereço do domicílio */ @Override public IEnderecoLocalPermanencia getEndereco() { return new EnderecoLocalPermanencia(instancia.getEndereco()); } /** * Define as informações sobre o endereço do domicílio. * * Regra: Opcional caso conclusaoDestinoElegivel for diferente de 1 (admissão própria emad). * * @param endereco Informações sobre o endereço do domicílio. */ @Override public void setEndereco(IEnderecoLocalPermanencia endereco) { instancia.setEndereco(endereco.getInstance()); } /** * Remove as informações sobre o endereço do domicílio. */ @Override public void unsetEndereco() { instancia.unsetEndereco(); } /** * Verifica se as I * informações sobre o endereço do domicílio foram declaradas. * * @return True caso as informações sobre o endereço do domicílio tenham sido declaradas, False caso não tenham. */ @Override public boolean isSetEndereco() { return instancia.isSetEndereco(); } /** * Declara que as informações sobre o endereço do domicílio foram inseridas. * * @param value True caso deseje informar que informações sobre o endereço do domicílio foram inseridas, False caso contrario. */ @Override public void setEnderecoIsSet(boolean value) { instancia.setEnderecoIsSet(value); } /** * Local de atendimento de origem do cidadão * * @return Código do local de atendimento de origem do cidadão. */ @Override public long getAtencaoDomiciliarOrigem() { return instancia.getAtencaoDomiciliarOrigem(); } /** * Define o local de atendimento de origem do cidadão. * * Presença obrigatória. * * @param atencaoDomiciliarOrigem Código do local de atendimento de origem do cidadão. */ @Override public void setAtencaoDomiciliarOrigem(long atencaoDomiciliarOrigem) { instancia.setAtencaoDomiciliarOrigem(atencaoDomiciliarOrigem); } /** * Remove o local de atendimento de origem do cidadão */ @Override public void unsetAtencaoDomiciliarOrigem() { instancia.unsetAtencaoDomiciliarOrigem(); } /** * Verifica se o local de atendimento de origem do cidadão foi declarado. * * @return True caso o local de atendimento de origem do cidadão tenha sido declarado, False caso não tenha sido declarado. */ @Override public boolean isSetAtencaoDomiciliarOrigem() { return instancia.isSetAtencaoDomiciliarOrigem(); } /** * Declara que o local de atendimento de origem do cidadão foi inserido. * * @param value True caso deseje informar que o local de atendimento de origem do cidadão foi inserido, False caso contrario. */ @Override public void setAtencaoDomiciliarOrigemIsSet(boolean value) { instancia.setAtencaoDomiciliarOrigemIsSet(value); } /** * Opções de modalidade, indica se o cidadão é elegível ou inelegível. * * @return Código das opções de modalidade. */ @Override public long getAtencaoDomiciliarModalidade() { return instancia.getAtencaoDomiciliarModalidade(); } /** * Define a modalidade. * * Presença obrigatória. * * @param atencaoDomiciliarModalidade Código das opções de modalidade, indica se o cidadão é elegível ou inelegível */ @Override public void setAtencaoDomiciliarModalidade(long atencaoDomiciliarModalidade) { instancia.setAtencaoDomiciliarModalidade(atencaoDomiciliarModalidade); } /** * Remove a modalidade. */ @Override public void unsetAtencaoDomiciliarModalidade() { instancia.unsetAtencaoDomiciliarModalidade(); } /** * Verifica se a modalidade foi declarada. * * @return True caso a modalidade tenha sido declarada, False caso não tenha sido declarada. */ @Override public boolean isSetAtencaoDomiciliarModalidade() { return instancia.isSetAtencaoDomiciliarModalidade(); } /** * Declara que a modalidade foi inserida. * * @param value True caso deseje declarar a modalidade, False caso contrario. */ @Override public void setAtencaoDomiciliarModalidadeIsSet(boolean value) { instancia.setAtencaoDomiciliarModalidadeIsSet(value); } /** * Quantidade de situações presentes. * * @return Quantidade de situações presentes. */ @Override public int getSituacoesPresentesSize() { return instancia.getSituacoesPresentesSize(); } /** * Situações presentes. * @return Marcadores de situações presentes. */ @Override public Iterator<Long> getSituacoesPresentesIterator() { return instancia.getSituacoesPresentesIterator(); } /** * Adiciona uma situação presente a lista de situações presentes. * * Máximo: 24 * * @param elem */ @Override public void addToSituacoesPresentes(long elem) { instancia.addToSituacoesPresentes(elem); } /** * Marcadores de situações presentes. * @return Lista com marcadores de situações presentes. */ @Override public List<Long> getSituacoesPresentes() { return instancia.getSituacoesPresentes(); } /** * Define um conjunto de marcadores de situações presentes. * * Tamanho mínimo: 1 * Tamanho máximo: 24 * * @param situacoesPresentes */ @Override public void setSituacoesPresentes(List<Long> situacoesPresentes) { instancia.setSituacoesPresentes(situacoesPresentes); } /** * Remove as situações presentes. */ @Override public void unsetSituacoesPresentes() { instancia.unsetSituacoesPresentes(); } /** * Verifica se foi declarada alguma situação presente. * @return True Caso situações presentes tenham sido declaradas, False caso contrario. */ @Override public boolean isSetSituacoesPresentes() { return instancia.isSetSituacoesPresentes(); } /** * Declara que situações presentes foram inseridas. * @param value True caso deseje informar que a fiha possui situações presentes, False caso contrario. */ @Override public void setSituacoesPresentesIsSet(boolean value) { instancia.setSituacoesPresentesIsSet(value); } /** * Código do CID10 registrado na avaliação * @return Código do CID10 registrado na avaliação */ @Override public String getCid10Principal() { return instancia.getCid10Principal(); } /** * Define o código do CID10 registrado da avaliação. * * Regra: Não pode ser igual ao CID10Segundo nem CID10Terceiro. * * @param cid10Principal Código do CID10 registrado da avaliação. */ @Override public void setCid10Principal(String cid10Principal) { instancia.setCid10Principal(cid10Principal); } /** * Remove o código do CID10 principal. */ @Override public void unsetCid10Principal() { instancia.unsetCid10Principal(); } /** * Verifica se o código do CID10 principal foi declarado. * * @return True caso o código do CID10 principal tenha sido declarado, False caso contrario. */ @Override public boolean isSetCid10Principal() { return instancia.isSetCid10Principal(); } /** * Declara que o código do CID10 principal foi inserido. * * @param value True caso deseje declarar o código do CID10 principal, false caso contrario. */ @Override public void setCid10PrincipalIsSet(boolean value) { instancia.setCid10PrincipalIsSet(value); } /** * Código do CID10 secundário. * * @return Código do CID10 secundário. */ @Override public String getCid10Segundo() { return instancia.getCid10Segundo(); } /** * Define o código do CID10 secundário. * * Regra: Não pode ser igual ao CID10Principal nem CID10Terceiro. * * @param cid10Segundo Código do CID10 secundário */ @Override public void setCid10Segundo(String cid10Segundo) { instancia.setCid10Segundo(cid10Segundo); } /** * Remove o código do CID10 secundário. */ @Override public void unsetCid10Segundo() { instancia.unsetCid10Segundo(); } /** * Verifica se o código do CID10 secundário foi declarado. * * @return True caso o código do CID10 secundário tenha sido declarado, False caso contrario. */ @Override public boolean isSetCid10Segundo() { return instancia.isSetCid10Segundo(); } /** * Delcara que o código do CID10 secundário foi inserido. * * @param value True caso o código do CID10 secundário tenha sido inserido, False caso contrario. */ @Override public void setCid10SegundoIsSet(boolean value) { instancia.setCid10SegundoIsSet(value); } /** * Código do CID10 terciário. * @return código do CID10 terciário. */ @Override public String getCid10Terceiro() { return instancia.getCid10Terceiro(); } /** * Define o código do CID10 terciário. * * Regra: Não pode ser igual ao CID10Principal nem CID10Segundo. * * @param cid10Terceiro Código do CID10 terciário. */ @Override public void setCid10Terceiro(String cid10Terceiro) { instancia.setCid10Terceiro(cid10Terceiro); } /** * Remove o código do CID10 terciário. */ @Override public void unsetCid10Terceiro() { instancia.unsetCid10Terceiro(); } /** * Verifica se o código do CID10 terciário foi declarado. * * @return True caso o código do CID10 terciário tenha sido declarado, False caso contrario. */ @Override public boolean isSetCid10Terceiro() { return instancia.isSetCid10Terceiro(); } /** * Declara que o código do CID10 terciário foi inserido. * * @param value True caso código do CID10 terciário tenha sido inserido, False caso contrario. */ @Override public void setCid10TerceiroIsSet(boolean value) { instancia.setCid10TerceiroIsSet(value); } /** * Código da conduta adotada caso cidadão seja Elegível. * * @return Código da conduta adotada caso cidadão seja Elegível. */ @Override public long getConclusaoDestinoElegivel() { return instancia.getConclusaoDestinoElegivel(); } /** * Define o código da conduta adotada caso cidadão seja Elegível. * * Regra: Só pode ser preenchido se atencaoDomiciliarModalidade for diferente de 4 (inelegível). * * @param conclusaoDestinoElegivel Código da conduta adotada caso cidadão seja Elegível. */ @Override public void setConclusaoDestinoElegivel(long conclusaoDestinoElegivel) { instancia.setConclusaoDestinoElegivel(conclusaoDestinoElegivel); } /** * Remove o código da conduta adotada caso cidadão seja Elegível. */ @Override public void unsetConclusaoDestinoElegivel() { instancia.unsetConclusaoDestinoElegivel(); } /** * Verifica se o código da conduta adotada caso cidadão seja Elegível foi declarado. * * @return True caso o código da conduta adotada caso cidadão seja Elegível tenha sido declarado, False caso contrario. */ @Override public boolean isSetConclusaoDestinoElegivel() { return instancia.isSetConclusaoDestinoElegivel(); } /** * Declara que o código da conduta adotada caso cidadão seja Elegível foi inserido. * * @param value True caso o código da conduta adotada caso cidadão seja Elegível tenha sido inserido, False caso contrario. */ @Override public void setConclusaoDestinoElegivelIsSet(boolean value) { instancia.setConclusaoDestinoElegivelIsSet(value); } /** * Quantidade de códigos da conduta adotada caso cidadão seja Inelegível. * * @return Código da conduta adotada caso cidadão seja Inelegível. */ @Override public int getConclusaoDestinoInelegivelSize() { return instancia.getConclusaoDestinoInelegivelSize(); } /** * Código da conduta adotada caso cidadão seja Inelegível. * * @return Código da conduta adotada caso cidadão seja Inelegível. */ @Override public Iterator<Long> getConclusaoDestinoInelegivelIterator() { return instancia.getConclusaoDestinoInelegivelIterator(); } /** * Adiciona um código da conduta adotada caso cidadão seja Inelegível. * * @param elem Código da conduta adotada caso cidadão seja Inelegível., */ @Override public void addToConclusaoDestinoInelegivel(long elem) { instancia.addToConclusaoDestinoInelegivel(elem); } /** * Código da conduta adotada caso cidadão seja Inelegível. * * @return Código da conduta adotada caso cidadão seja Inelegível. */ @Override public List<Long> getConclusaoDestinoInelegivel() { return instancia.getConclusaoDestinoInelegivel(); } /** * Define Código da conduta adotada caso cidadão seja Inelegível * * Regra: Só pode ser preenchido se atencaoDomiciliarModalidade for igual a de 4 (inelegível) * máximo: 5 * * @param conclusaoDestinoInelegivel */ @Override public void setConclusaoDestinoInelegivel(List<Long> conclusaoDestinoInelegivel) { instancia.setConclusaoDestinoInelegivel(conclusaoDestinoInelegivel); } /** * remove o código da conduta adotada caso cidadão seja Inelegível */ @Override public void unsetConclusaoDestinoInelegivel() { instancia.unsetConclusaoDestinoInelegivel(); } /** * Verifica se o Código da conduta adotada caso cidadão seja Inelegível foi declarado. * * @return True caso o Código da conduta adotada caso cidadão seja Inelegível tenha sido declarado, False caso contrario. */ @Override public boolean isSetConclusaoDestinoInelegivel() { return instancia.isSetConclusaoDestinoInelegivel(); } /** * Declara que o código da conduta adotada caso cidadão seja Inelegível foi inserido. * * @param value True caso o código da conduta adotada caso cidadão seja Inelegível tenha sido inserido. */ @Override public void setConclusaoDestinoInelegivelIsSet(boolean value) { instancia.setConclusaoDestinoInelegivelIsSet(value); } /** * Relação de parentesco do cuidador com o cidadão em atenção domiciliar. * * @return Código da relação de parentesco do cuidador com o cidadão em atenção domiciliar. */ @Override public long getCuidadorCidadao() { return instancia.getCuidadorCidadao(); } /** * Define a relação de parentesco do cuidador com o cidadão em atenção domiciliar. * * @param cuidadorCidadao Código da relação de parentesco do cuidador com o cidadão em atenção domiciliar. */ @Override public void setCuidadorCidadao(long cuidadorCidadao) { instancia.setCuidadorCidadao(cuidadorCidadao); } /** * Remove a relação de parentesco do cuidador com o cidadão em atenção domiciliar. */ @Override public void unsetCuidadorCidadao() { instancia.unsetCuidadorCidadao(); } /** * Verifica se a relação de parentesco do cuidador com o cidadão em atenção domiciliar foi declarada. * * @return True caso a relação de parentesco do cuidador com o cidadão em atenção domiciliar tenha sido declarada, False caso contrario. */ @Override public boolean isSetCuidadorCidadao() { return instancia.isSetCuidadorCidadao(); } /** * Declara que a relação de parentesco do cuidador com o cidadão em atenção domiciliar foi inserida. * @param value True caso a relação de parentesco do cuidador com o cidadão em atenção domiciliar tenha sido inserida, false caso contrario. */ @Override public void setCuidadorCidadaoIsSet(boolean value) { instancia.setCuidadorCidadaoIsSet(value); } /** * Valida se o conteudo da instancia está consistente. * @return True caso as informações sejam validas. */ @Override public boolean validate() { return validateUuidFicha() && validatetTpCdsOrigem() && validateHeaderTransport() && validateNumeroCartaoSus() && validateNome() && validateNomeSocial() && validaDataNascimentoCidadao() && validateRacaCorCidadao() && validateNomeMae() && validateNacionalidade() && validateEmail() && validateNumeroNisPisPasep() && validateEndereco() && validateAtencaoDomiciliarOrigem() && validateAtencaoDomiciliarModalidade() && validateSituacoesPresentes() && validateCid10Principal() && validateCid10Segundo() && validateCid10Terceiro() && validateConclusaoDestinoElegivel() && validateConclusaoDestinoInelegivel(); } /** * Retorna uma copia da instancia thrift. * @return Instancia thrift da classe. */ @Override public FichaAvaliacaoElegibilidadeThrift getInstance(){ return instancia; } /** * Código UUID para identificar a ficha na base de dados nacional. * Obrigatório! * Regras: É recomendado concatenar o CNES na frente do UUID, de modo que os * 7 digitos (CNES) + 1 de hífen somados aos 36 (32 caracteres + 4 hífen) do * UUID são a limitação de 44 bytes do campo. * @return True caso valido, false caso esteja inconsistente */ @Override public boolean validateUuidFicha(){ return instancia.getUuidFicha() != null && instancia.getUuidFicha().length() >= 36 && instancia.getUuidFicha().length() <= 44; } /** * Valida se o tipo de origem foi declarado. * * @return True caso o tipo de origem dos dados tenha sido declarado. */ @Override public boolean validatetTpCdsOrigem(){ return instancia.isSetTpCdsOrigem(); } /** * Profissional que realizou a visita. * * @return True caso o header transport seja valido */ @Override public boolean validateHeaderTransport(){ return instancia.getHeaderTransport() != null && instancia.isSetHeaderTransport() && new UnicaLotacaoHeader(instancia.getHeaderTransport()).validates(); } /** * CNS do cidadão que participou da atividade. * @return True Caso não tenha sido informado e caso tenha sido informado corretamente. */ @Override public boolean validateNumeroCartaoSus(){ if(this.isSetNumeroCartaoSus()){ return CNS.validateCNS(instancia.getNumeroCartaoSus()); } return true; } /** * Valida o nome do cidadão. * * Regras: * Ter ao menos duas palavras. * Somente texto e apóstrofo ('). * Opcional caso conclusaoDestinoElegivel for diferente de 1 (admissão própria emad). * * Tamanho mínimo: 5 * Tamanho máximo: 100 * * @return True caso seja um nome valido ou caso não possua nome e conclusaoDestinoElegivel seja diferente de 1, False caso contrario. */ @Override public boolean validateNome(){ if(this.isSetNomeCidadao()){ return this.getNomeCidadao().length() >= 5 && this.getNomeCidadao().length() <= 100; }else { return this.getConclusaoDestinoElegivel() != 1; } } /** * Valida o nome social do cidadão. * * Regras: * Somente texto e apóstrofo ('). * * Tamanho mínimo: 0 * Tamanho máximo: 100 * * @return True caso seja um nome valido ou caso não possua nome e conclusaoDestinoElegivel seja diferente de 1, False caso contrario. */ @Override public boolean validateNomeSocial(){ if(this.isSetNomeSocialCidadao()){ return this.getNomeSocialCidadao().length() >= 0 && this.getNomeSocialCidadao().length() <= 100; }else { return true; } } /** * Valida Data de nascimento do cidadão no formato epoch time. * @return Data de nascimento do cidadão no formato epoch time. * Valida se o campo é null * Valida: Não pode ser posterior a dataAtendimento e anterior a 130 anos a partir da dataAtendimento. * Não pode ser posterior a dataAtendimento e anterior a 130 anos a partir da dataAtendimento. */ @Override public boolean validaDataNascimentoCidadao(){ if(!instancia.isSetDataNascimentoCidadao()) return false; long dataNascimento = instancia.getDataNascimentoCidadao(); long dataAtendimento = instancia.getHeaderTransport().getDataAtendimento(); if(dataNascimento > dataAtendimento) return false; long idadeAoAtender = dataNascimento - dataAtendimento; /** * Transformando 1 ano em segundo */ long anoEpoch = 60*60*24*365; /** * Descobrindo se a idade do cidadão no atendimento é maior que 130 anos */ if(idadeAoAtender > anoEpoch*130) return false; return true; } /** * Valida a raça/cor do cidadão. * * regra: Opcional caso conclusaoDestinoElegivel for diferente de 1 (admissão própria emad) * * @return True caso esteje presente ou caso conclusaoDestinoElegivel for diferente de 1, False caso contrario. */ @Override public boolean validateRacaCorCidadao(){ if(instancia.isSetRacaCorCidadao()){ return true; }else{ return instancia.getConclusaoDestinoElegivel() != 1; } } /** * Valida o nome da mãe do cidadão. * * Regras: * Ter ao menos duas palavras. * Somente texto e apóstrofo ('). * Não pode ser preenchido se o campo desconheceNomeMae = true. * * Tamanho mínimo: 5 * Tamanho máximo: 100 * * @return True caso seja um nome valido ou caso não possua nome e conclusaoDestinoElegivel seja diferente de 1, False caso contrario. */ @Override public boolean validateNomeMae(){ if(this.isSetNomeMaeCidadao() && ! instancia.isDesconheceNomeMae()){ return this.getNomeCidadao().length() >= 5 && this.getNomeCidadao().length() <= 100; }else{ return instancia.isDesconheceNomeMae(); } } /** * Valida a nacionalidade do cidadão. * * Regra: Opcional caso conclusaoDestinoElegivel for diferente de 1 (admissão própria emad) * * @return True caso esteja presente ou caso conclusaoDestinoElegivel for diferente de 1, False caso contrario. */ @Override public boolean validateNacionalidade(){ if(instancia.isSetCodigoNacionalidade()){ return true; }else{ return instancia.getConclusaoDestinoElegivel() != 1; } } /** * Valida o email do cidadão. * * regra: Requerido seguir o padrão endereco@domínio.extensão. * * Tamanho mínimo:6 * Tamanho máximo:255 * * @return True caso esteja de acordo com a regra ou caso não tenha sido declarado, False caso contrario. */ @Override public boolean validateEmail(){ if(instancia.isSetEmailCidadao()){ if(instancia.getEmailCidadao().length() >=6 && instancia.getEmailCidadao().length() <= 255){ Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); Matcher matcher = VALID_EMAIL_ADDRESS_REGEX .matcher(instancia.getEmailCidadao()); return matcher.find(); }else{ return false; } } return true; } /** * Valida o número do PIS/PASEP do cidadão. * * Regras: Apenas números. * * Tamanho: 11 * * @return True caso seja valido ou caso não seja declarado, False caso contrario. */ @Override public boolean validateNumeroNisPisPasep(){ if(instancia.isSetNumeroNisPisPasep()){ if(instancia.getNumeroNisPisPasep().matches("[0-9]+") && instancia.getNumeroNisPisPasep().length() == 11){ return true; }else{ return false; } } return true; } /** * Valida as informações sobre o endereço do domicílio. * * Regra: Opcional caso conclusaoDestinoElegivel for diferente de 1 (admissão própria emad) * * @return True caso seja valido ou caso conclusaoDestinoElegivel for diferente de 1, False caso contrario. */ @Override public boolean validateEndereco(){ if(instancia.isSetEndereco()){ return new EnderecoLocalPermanencia(instancia.getEndereco()).validates(); }else{ return instancia.getConclusaoDestinoElegivel() != 1; } } /** * Valida o local de atendimento de origem do cidadão. * * @return True caso esteja presente, falso caso contrario. */ @Override public boolean validateAtencaoDomiciliarOrigem(){ return instancia.isSetAtencaoDomiciliarOrigem(); } /** * Valida as opções de modalidade, indica se o cidadão é elegível ou inelegível. * * @return True caso esteja presente, falso caso contrario. */ @Override public boolean validateAtencaoDomiciliarModalidade(){ return instancia.isSetAtencaoDomiciliarModalidade(); } /** * Valida os marcadores de situações presentes. * * Mínimo: 1 * Máximo: 24 * * @return True caso atendam as regras ou caso não seja declarado, False caso contrario. */ @Override public boolean validateSituacoesPresentes(){ if(instancia.isSetSituacoesPresentes()){ return instancia.getSituacoesPresentesSize() >= 1 && instancia.getSituacoesPresentesSize() <= 24; } return true; } /** * Valida o código do CID10 principal registrado na avaliação. * * Regra: Não pode ser igual ao CID10Segundo nem CID10Terceiro. * * @return True caso esteja de acordo com as regras, False caso contrario. */ @Override public boolean validateCid10Principal(){ if(instancia.isSetCid10Principal()){ return ( ! instancia.getCid10Principal().equalsIgnoreCase(instancia.getCid10Segundo()) && ! instancia.getCid10Principal().equalsIgnoreCase(instancia.getCid10Terceiro())); } return false; } /** * Valida o código do CID10 registrado na avaliação. * * Regras: Não pode ser igual ao CID10Principal nem CID10Terceiro. * * @return True caso esteja de acordo com a regra ou não seja declarado, False caso contrario. */ @Override public boolean validateCid10Segundo(){ if(instancia.isSetCid10Segundo()){ return ( ! instancia.getCid10Segundo().equalsIgnoreCase(instancia.getCid10Principal()) && ! instancia.getCid10Segundo().equalsIgnoreCase(instancia.getCid10Terceiro())); } return true; } /** * Valida o código do CID10 registrado na avaliação. * * Regras: Não pode ser igual ao CID10Principal nem CID10Segundo. * * @return True caso esteja de acordo com a regra ou não seja declarado, False caso contrario. */ @Override public boolean validateCid10Terceiro(){ if(instancia.isSetCid10Segundo()){ return ( ! instancia.getCid10Terceiro().equalsIgnoreCase(instancia.getCid10Principal()) && ! instancia.getCid10Terceiro().equalsIgnoreCase(instancia.getCid10Segundo())); } return true; } /** * Valida conduta adotada caso cidadão seja Elegível. * * Regra: Só pode ser preenchido se atencaoDomiciliarModalidade for diferente de 4 (inelegível). * Regra: só pode ser existir se conclusaoDestinoInelegivel não existir. * * @return True caso atenda as regras, False caso contrario. */ @Override public boolean validateConclusaoDestinoElegivel(){ if(instancia.isSetConclusaoDestinoElegivel()){ return !(instancia.getAtencaoDomiciliarModalidade() == 4 && instancia.isSetConclusaoDestinoInelegivel()); } return instancia.isSetConclusaoDestinoInelegivel(); } /** * Valida conduta adotada caso cidadão seja Inelegível. * * Regra: Só pode ser preenchido se atencaoDomiciliarModalidade for igual a de 4 (inelegível). * Regra: só pode ser existir se conclusaoDestinoElegivel não existir. * * Máximo: 5 * * @return True caso atenda as regras, False caso contrario. */ @Override public boolean validateConclusaoDestinoInelegivel(){ if(instancia.isSetConclusaoDestinoInelegivel()){ if( ! instancia.isSetConclusaoDestinoElegivel() && instancia.getConclusaoDestinoInelegivelSize() < 5){ return instancia.getAtencaoDomiciliarModalidade() == 4 ; } } return instancia.isSetConclusaoDestinoElegivel(); } /** * necessário para gerar o zip * @param dadoTransporteThrift */ public void setDadoTransporte(DadoTransporte dadoTransporteThrift){ this.dadoTransporteThrift = dadoTransporteThrift; } public DadoTransporte getDadoTransporte(){ return this.dadoTransporteThrift; } public void zipGenerate(){ if(!this.validate() && this.dadoTransporteThrift != null){ return; } byte[] fichaSerializada = SerializadorThrift.serializar(this.instancia); dadoTransporteThrift.setTipoDadoSerializado(TIPO_DADO_SERIALIZADO_FICHA_PROCEDIMENTO); dadoTransporteThrift.setDadoSerializado(fichaSerializada); try { File zipFile = new File(System.getProperty("user.home") + "/fichaAvaliacaoElegibilidade.zip"); ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFile)); String entryName = dadoTransporteThrift.getUuidDadoSerializado() + EXTENSAO_EXPORT; outputStream.putNextEntry(new ZipEntry(entryName)); byte[] dadoTransporteSerializado = SerializadorThrift.serializar(dadoTransporteThrift.getInstance()); outputStream.write(dadoTransporteSerializado); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
/* * Copyright 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 therian; import java.util.Objects; /** * Exception thrown to signify a problem with the definition of an {@link Operator}. */ public class OperatorDefinitionException extends RuntimeException { /** Serialization version */ private static final long serialVersionUID = -7571972458679149796L; private final Operator<?> operator; public OperatorDefinitionException(Operator<?> operator) { this.operator = Objects.requireNonNull(operator); } public OperatorDefinitionException(Operator<?> operator, String message, Object... args) { super(String.format(message, args)); this.operator = Objects.requireNonNull(operator); } public OperatorDefinitionException(Operator<?> operator, Throwable throwable, String message, Object... args) { super(String.format(message, args), throwable); this.operator = Objects.requireNonNull(operator); } public OperatorDefinitionException(Operator<?> operator, Throwable throwable) { super(throwable); this.operator = Objects.requireNonNull(operator); } public Operator<?> getOperator() { return operator; } }
/* * Copyright 2016-2020 Chronicle Software * * https://chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.wire.reuse; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.core.pool.ClassAliasPool; import net.openhft.chronicle.core.threads.ThreadDump; import net.openhft.chronicle.wire.*; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import java.util.function.Function; import static org.junit.Assert.assertEquals; @Ignore("TODO FIX") @SuppressWarnings("rawtypes") @RunWith(value = Parameterized.class) public class WireCollectionTest extends WireTestCommon { static { ClassAliasPool.CLASS_ALIASES.addAlias(WireProperty.class); } private final Function<Bytes, Wire> wireType; private WireCollection collection;// = new WireModel(); private ThreadDump threadDump; public WireCollectionTest(Function<Bytes, Wire> wireType) { this.wireType = wireType; } @Parameterized.Parameters public static Collection<Object[]> combinations() { return Arrays.asList( new Object[]{WireType.TEXT}, new Object[]{(Function<Bytes, Wire>) bytes -> new BinaryWire(bytes, false, true, false, 128, "binary", false)}, new Object[]{WireType.BINARY}, new Object[]{WireType.BINARY_LIGHT}, new Object[]{WireType.FIELDLESS_BINARY}, new Object[]{WireType.JSON} ); } @Before public void threadDump() { threadDump = new ThreadDump(); } @After public void checkThreadDump() { threadDump.assertNoNewThreads(); } @Before public void setUp() { collection = WireUtils.randomWireCollection(); } @Test public void testMultipleReads() { Bytes bytes = Bytes.elasticByteBuffer(); Wire wire = wireType.apply(bytes); assert wire.startUse(); wire.writeDocument(true, collection); System.out.println(Wires.fromSizePrefixedBlobs(bytes)); @NotNull WireCollection results = new WireCollection(); wire.readDocument(results, null); assertEquals(collection.toString(), results.toString()); WireUtils.compareWireCollection(collection, results); } }
/* * Copyright 2017 Capital One Services, LLC and Bitwise, 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 hydrograph.engine.jaxb.normalize; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import hydrograph.engine.jaxb.commontypes.TypeInputField; /** * <p>Java class for type-operation-input-field complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="type-operation-input-field"> * &lt;complexContent> * &lt;restriction base="{hydrograph/engine/jaxb/commontypes}type-input-field"> * &lt;attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="inSocketId" use="required" type="{http://www.w3.org/2001/XMLSchema}string" fixed="in0" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "type-operation-input-field", namespace = "hydrograph/engine/jaxb/normalize") public class TypeOperationInputField extends TypeInputField { }
/* * 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.v2; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class AtlasModelFactory { public static final String GENERATED_PATH = "$ATLASMAP"; private AtlasModelFactory() { } public static <T extends BaseMapping> T createMapping() { return createMapping(MappingType.MAP); } @SuppressWarnings("unchecked") public static <T extends BaseMapping> T createMapping(MappingType type) { T fm = null; if (type == null) { return null; } switch (type) { case COLLECTION: fm = (T) new Collection(); ((Collection) fm).setMappingType(type); return fm; case COMBINE: case LOOKUP: case MAP: case SEPARATE: fm = (T) new Mapping(); ((Mapping) fm).setMappingType(type); return fm; default: throw new IllegalStateException(String.format("Unsupported mappingType=%s", type.value())); } } public static AtlasMapping createAtlasMapping() { AtlasMapping mapping = new AtlasMapping(); mapping.setMappings(new Mappings()); mapping.setProperties(new Properties()); mapping.setLookupTables(new LookupTables()); return mapping; } public static Collection createCollection() { Collection collectionMapping = new Collection(); collectionMapping.setMappings(new Mappings()); collectionMapping.setMappingType(MappingType.COLLECTION); return collectionMapping; } public static MockDocument createMockDocument() { MockDocument mockDocument = new MockDocument(); mockDocument.setFields(new Fields()); return mockDocument; } public static MockField createMockField() { return new MockField(); } public static PropertyField createPropertyField() { return new PropertyField(); } public static BaseMapping cloneMapping(BaseMapping baseMapping, boolean deepClone) { if (baseMapping.getMappingType().equals(MappingType.COLLECTION)) { Collection mapping = (Collection) baseMapping; Collection clone = new Collection(); clone.setAlias(mapping.getAlias()); clone.setDescription(mapping.getDescription()); clone.setMappingType(mapping.getMappingType()); if (deepClone) { clone.setMappings(new Mappings()); for (BaseMapping m : mapping.getMappings().getMapping()) { clone.getMappings().getMapping().add(cloneMapping(m, deepClone)); } } return clone; } // Non-collection mapping Mapping mapping = (Mapping) baseMapping; Mapping clone = new Mapping(); clone.setAlias(mapping.getAlias()); clone.setDelimiter(mapping.getDelimiter()); clone.setDelimiterString(mapping.getDelimiterString()); clone.setDescription(mapping.getDescription()); clone.setLookupTableName(mapping.getLookupTableName()); if (mapping.getMappingType() != null) { clone.setMappingType(MappingType.fromValue(mapping.getMappingType().value())); } clone.setStrategy(mapping.getStrategy()); clone.setStrategyClassName(mapping.getStrategyClassName()); if (deepClone) { for (Field f : mapping.getInputField()) { clone.getInputField().add(cloneField(f)); } for (Field f : mapping.getOutputField()) { clone.getOutputField().add(cloneField(f)); } } return clone; } public static Field cloneField(Field f) { throw new IllegalArgumentException("Use module specific factories to clone fields"); } /** * This is a shallow copy, it doesn't handle children. * Each module should handle their own deep clone. * @param fg {@code FieldGroup} * @return copied FieldGroup */ public static FieldGroup copyFieldGroup(FieldGroup fg) { if (fg == null) { return null; } FieldGroup newfg = new FieldGroup(); copyField(fg, newfg, true); return newfg; } public static SimpleField cloneFieldToSimpleField(Field field) { if (field == null) { return null; } SimpleField f = new SimpleField(); copyField(field, f, true); return f; } public static void copyField(Field from, Field to, boolean withActions) { if (withActions) { to.setActions(cloneFieldActions(from.getActions())); } if (from.getArrayDimensions() != null) { to.setArrayDimensions(Integer.valueOf(from.getArrayDimensions())); } if (from.getArraySize() != null) { to.setArraySize(Integer.valueOf(from.getArraySize())); } if (from.getCollectionType() != null) { to.setCollectionType(CollectionType.fromValue(from.getCollectionType().value())); } if (from.getDocId() != null) { to.setDocId(from.getDocId()); } if (from.getFieldType() != null) { to.setFieldType(FieldType.fromValue(from.getFieldType().value())); } if (from.getIndex() != null) { to.setIndex(Integer.valueOf(from.getIndex())); } if (from.getPath() != null) { to.setPath(from.getPath()); } if (from.isRequired() != null) { to.setRequired(Boolean.valueOf(from.isRequired())); } if (from.getStatus() != null) { to.setStatus(FieldStatus.fromValue(from.getStatus().value())); } if (from.getName() != null) { to.setName(from.getName()); } // We can't clone so don't set value } public static FieldGroup createFieldGroupFrom(Field field, boolean withActions) { FieldGroup answer = new FieldGroup(); copyField(field, answer, withActions); return answer; } public static ArrayList<Action> cloneFieldActions(ArrayList<Action> actions) { if (actions == null) { return null; } ArrayList<Action> n = new ArrayList<Action>(); if (actions == null || actions.isEmpty()) { return n; } for (Action a : actions) { n.add(cloneAction(a)); } return n; } public static Action cloneAction(Action action) { if (action == null) { return null; } try { ObjectMapper mapper = new ObjectMapper() .enable(MapperFeature.BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES); String s = mapper.writeValueAsString(action); System.out.println(s); return mapper.readerFor(Action.class).readValue(s); } catch (IOException e) { throw new RuntimeException(e); } } protected static String baseFieldToString(Field f) { if (f == null) { return ""; } StringBuilder tmp = new StringBuilder(); tmp.append(" arrayDimensions=" + f.getArrayDimensions()); tmp.append(" arraySize=" + f.getArraySize()); tmp.append(" collectionType=" + (f.getCollectionType() != null ? f.getCollectionType().value() : null)); tmp.append(" docId=" + f.getDocId()); if (f.getActions() != null && f.getActions() != null) { if (!f.getActions().isEmpty()) { tmp.append(" fieldActions#=" + f.getActions().size()); } else { tmp.append(" fieldActions#=0"); } } else { tmp.append(" fieldActions#="); } tmp.append(" fieldType=" + (f.getFieldType() != null ? f.getFieldType().value() : null)); tmp.append(" index=" + f.getIndex()); tmp.append(" path=" + f.getPath()); tmp.append(" fieldStatus=" + (f.getStatus() != null ? f.getStatus().value() : null)); tmp.append(" value=" + f.getValue()); return tmp.toString(); } public static String toString(PropertyField f) { StringBuilder tmp = new StringBuilder("PropertyField [name="); if (f != null && f.getName() != null) { tmp.append(f.getName()); } tmp.append(baseFieldToString(f)); tmp.append("]"); return tmp.toString(); } public static String toString(Field f) { StringBuilder tmp = new StringBuilder("Field [name="); if (f != null) { tmp.append(f.getClass().getSimpleName()); } tmp.append(baseFieldToString(f)); tmp.append("]"); return tmp.toString(); } public static Field wrapWithField(Object val) { return wrapWithField(val, "/"); } public static Field wrapWithField(Object val, String parentPath) { if (val instanceof java.util.Collection) { Object[] collection = ((java.util.Collection)val).toArray(); FieldGroup group = new FieldGroup(); group.setPath(parentPath + GENERATED_PATH); for (int i=0; i<collection.length; i++) { Field sub = wrapWithField(collection[i], group.getPath()); sub.setPath(sub.getPath() + "[" + i + "]"); group.getField().add(sub); } return group; } SimpleField answer = new SimpleField(); answer.setPath(GENERATED_PATH); answer.setValue(val); return answer; } public static Object unwrapField(Field f) { if (f == null) { return null; } if (f instanceof FieldGroup) { List<Object> l = new LinkedList<>(); for (Field sub : ((FieldGroup)f).getField()) { l.add(unwrapField(sub)); } return l; } else { return f.getValue(); } } }
/* * 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. */ import data.Dataset; import data.SVMFileReader; import data.Sample; import libsvm.svm_node; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Iterator; /** * Created by edwardlol on 17-4-18. */ public final class UtilTests { //~ Methods ---------------------------------------------------------------- @Test public void sampleTest() { Sample sample = new Sample(); svm_node node1 = new svm_node(); node1.index = 1; node1.value = 1.0d; sample.add(node1); svm_node node2 = new svm_node(); node2.index = 2; node2.value = 2.0d; sample.add(node2); sample.setLabel(1.0d); System.out.println(sample.featureNum()); } @Test public void cloneTest() { Sample sample = new Sample(); svm_node node1 = new svm_node(); node1.index = 1; node1.value = 1.0d; sample.add(node1); svm_node node2 = new svm_node(); node2.index = 2; node2.value = 2.0d; sample.add(node2); sample.setLabel(1.0d); Sample sample2 = sample.clone(); System.out.println(sample); System.out.println(sample2); } @Test public void logTest() { final Logger logger = LoggerFactory.getLogger(UtilTests.class); logger.debug("Hello world, I'm a DEBUG level message"); logger.info("Hello world, I'm an INFO level message"); logger.warn("Hello world, I'm a WARNING level message"); logger.error("Hello world, I'm an ERROR level message"); } @Test public void iterTest() { SVMFileReader reader = SVMFileReader.getInstance(); Dataset data = reader.read("./datasets/train"); Iterator<double[]> itr = data.columnIter(); while (itr.hasNext()) { double[] column = itr.next(); System.out.println(column[0]); } } } // End UtilTests.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.process.logging; import static org.jboss.logging.Logger.Level.ERROR; import static org.jboss.logging.Logger.Level.INFO; import static org.jboss.logging.Logger.Level.WARN; import java.io.EOFException; import java.io.IOException; import java.io.UTFDataFormatException; import java.net.InetAddress; import java.net.ServerSocket; import org.jboss.as.process.CommandLineConstants; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * Date: 29.06.2011 * * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> * @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a> */ @MessageLogger(projectCode = "WFLYPC", length = 4) public interface ProcessLogger extends BasicLogger { /** * The root logger with a category of the package. */ ProcessLogger ROOT_LOGGER = Logger.getMessageLogger(ProcessLogger.class, "org.jboss.as.process"); /** * A logger with the category {@code org.jboss.as.process-controller.client}. */ ProcessLogger CLIENT_LOGGER = Logger.getMessageLogger(ProcessLogger.class, "org.jboss.as.process-controller.client"); /** * A logger with the category {@code org.jboss.as.process.protocol} */ ProcessLogger PROTOCOL_LOGGER = Logger.getMessageLogger(ProcessLogger.class, "org.jboss.as.process.protocol"); /** * A logger with the category {@code org.jboss.as.process.protocol.client} */ ProcessLogger PROTOCOL_CLIENT_LOGGER = Logger.getMessageLogger(ProcessLogger.class, "org.jboss.as.protocol.client"); /** * A logger with the category {@code org.jboss.as.process.protocol.client} */ ProcessLogger PROTOCOL_CONNECTION_LOGGER = Logger.getMessageLogger(ProcessLogger.class, "org.jboss.as.protocol.connection"); /** * A logger with the category {@code org.jboss.as.process-controller.server}. */ ProcessLogger SERVER_LOGGER = Logger.getMessageLogger(ProcessLogger.class, "org.jboss.as.process-controller.server"); /** * Logs a warning message indicating an attempt to reconnect a non-existent process. * * @param processName the name of the process. */ @LogMessage(level = WARN) @Message(id = 1, value = "Attempted to reconnect non-existent process '%s'") void attemptToReconnectNonExistentProcess(String processName); /** * Logs a warning message indicating an attempt to remove a non-existent process. * * @param processName the name of the process. */ @LogMessage(level = WARN) @Message(id = 2, value = "Attempted to remove non-existent process '%s'") void attemptToRemoveNonExistentProcess(String processName); /** * Logs a warning message indicating an attempt to start a non-existent process. * * @param processName the name of the process. */ @LogMessage(level = WARN) @Message(id = 3, value = "Attempted to start non-existent process '%s'") void attemptToStartNonExistentProcess(String processName); /** * Logs a warning message indicating an attempt to stop a non-existent process. * * @param processName the name of the process. */ @LogMessage(level = WARN) @Message(id = 4, value = "Attempted to stop non-existent process '%s'") void attemptToStopNonExistentProcess(String processName); /** * Logs a warning message indicating an attempt to register a duplicate named process. * * @param processName the duplicate name. */ @LogMessage(level = WARN) @Message(id = 5, value = "Attempted to register duplicate named process '%s'") void duplicateProcessName(String processName); /** * Logs a warning message indicating the authentication key failed to send to the process. * * @param processName the process name. * @param error th error. */ @LogMessage(level = WARN) @Message(id = 6, value = "Failed to send authentication key to process '%s': %s") void failedToSendAuthKey(String processName, Throwable error); /** * Logs an error message indicating the data bytes failed to send to the process input stream. * * @param cause the cause of the error. * @param processName the process name. */ @LogMessage(level = ERROR) @Message(id = 7, value = "Failed to send data bytes to process '%s' input stream") void failedToSendDataBytes(@Cause Throwable cause, String processName); /** * Logs an error message indicating the reconnect message failed to send to the process input stream. * * @param cause the cause of the error. * @param processName the process name. */ @LogMessage(level = ERROR) @Message(id = 8, value = "Failed to send reconnect message to process '%s' input stream") void failedToSendReconnect(@Cause Throwable cause, String processName); /** * Logs an error message indicating the process failed to start. * * @param processName the process name. */ @LogMessage(level = ERROR) @Message(id = 9, value = "Failed to start process '%s'") void failedToStartProcess(@Cause Throwable cause, String processName); /** * Logs an error message indicating a failure to write a message to the connection. * * @param messageType the type of the message that failed to write. * @param t the cause of the error. */ @LogMessage(level = ERROR) @Message(id = 10, value = "Failed to write %s message to connection: %s") void failedToWriteMessage(String messageType, Throwable t); /** * Logs an informational message indicating the process has finished with the exit status code. * * @param processName the process name. * @param exitCode the exit code. */ @LogMessage(level = INFO) @Message(id = 11, value = "Process '%s' finished with an exit status of %d") void processFinished(String processName, int exitCode); /** * Logs a warning message indicating a connection with an invalid version from the address, represented by the * {@code address} parameter, was received. * * @param address the address. */ @LogMessage(level = WARN) @Message(id = 12, value = "Received connection with invalid version from %s") void receivedInvalidVersion(InetAddress address); /** * Logs a warning message indicating an unknown greeting code, represented by the {@code code} parameter, * was received by the address, represented by the {@code address} parameter. * * @param code the unknown code. * @param address the address */ @LogMessage(level = WARN) @Message(id = 13, value = "Received unrecognized greeting code 0x%02x from %s") void receivedUnknownGreetingCode(int code, InetAddress address); /** * Logs a warning message indicating unknown credentials were received by the address, represented by the * {@code address} parameter. * * @param address the address */ @LogMessage(level = WARN) @Message(id = 14, value = "Received connection with unknown credentials from %s") void receivedUnknownCredentials(InetAddress address); /** * Logs a warning message indicating an unknown message with the code, represented by the {@code code} parameter, * was received. * * @param code the unknown code. */ @LogMessage(level = WARN) @Message(id = 15, value = "Received unknown message with code 0x%02x") void receivedUnknownMessageCode(int code); /** * Logs an informational message indicating the process controller shutdown is complete. */ @LogMessage(level = INFO) @Message(id = 16, value = "All processes finished; exiting") void shutdownComplete(); /** * Logs an informational message indicating the process controller is shutting down. */ @LogMessage(level = INFO) @Message(id = 17, value = "Shutting down process controller") void shuttingDown(); /** * Logs an informational message indicating the process is starting. * * @param processName the process name. */ @LogMessage(level = INFO) @Message(id = 18, value = "Starting process '%s'") void startingProcess(String processName); /** * Logs an informational message indicating the process is stopping. * * @param processName the process name. */ @LogMessage(level = INFO) @Message(id = 19, value = "Stopping process '%s'") void stoppingProcess(String processName); /** * Logs an error message indicating the stream processing failed for the process. * * @param processName the process name. * @param error the error. */ @LogMessage(level = ERROR) @Message(id = 20, value = "Stream processing failed for process '%s': %s") void streamProcessingFailed(String processName, Throwable error); /** * Logs an informational message that the respawn is waiting until another attempt * is made to restart the process. * * @param seconds the seconds * @param processName the process name */ @LogMessage(level = INFO) @Message(id = 21, value = "Waiting %d seconds until trying to restart process %s.") void waitingToRestart(int seconds, String processName); @LogMessage(level = WARN) @Message(id = 22, value = "Failed to kill process '%s', trying to destroy the process instead.") void failedToKillProcess(String process); @Message(id = Message.NONE, value = "Usage: %s [args...]%nwhere args include:") String argUsage(String executableName); /** * Instructions for the {@link org.jboss.as.process.CommandLineConstants#BACKUP_DC} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Keep a copy of the persistent domain configuration even if this host is not the Domain Controller. If ignore-unused-configuration is unset in host.xml, then the complete domain configuration will be stored, otherwise the configured value of ignore-unused-configuration will be used.") String argBackup(); /** * Instructions for the {@link org.jboss.as.process.CommandLineConstants#CACHED_DC} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "If this host is not the Domain Controller and cannot contact the Domain Controller at boot, a locally cached copy of the domain configuration is used for boot (if available, see --backup.) The Domain Controller is background polled until it becomes available. Note that starting a host with --cached-dc when the Domain Controller is available will cache a copy of the domain configuration even if --backup is not used.") String argCachedDc(); /** * Instructions for the {@link org.jboss.as.process.CommandLineConstants#DOMAIN_CONFIG} command line arguments. * * @return the message. */ @Message(id = Message.NONE, value = "Name of the domain configuration file to use (default is \"domain.xml\") (Same as -c)") String argDomainConfig(); /** * Instructions for the {@link org.jboss.as.process.CommandLineConstants#SHORT_DOMAIN_CONFIG} command line arguments. * * @return the message. */ @Message(id = Message.NONE, value = "Name of the domain configuration file to use (default is \"domain.xml\") (Same as --domain-config)") String argShortDomainConfig(); /** * Instructions for the {@link org.jboss.as.process.CommandLineConstants#READ_ONLY_DOMAIN_CONFIG} command line arguments. * * @return the message. */ @Message(id = Message.NONE, value = "Name of the domain configuration file to use. This differs from '" + CommandLineConstants.DOMAIN_CONFIG + "', '" + CommandLineConstants.SHORT_DOMAIN_CONFIG + "' and '" + CommandLineConstants.OLD_DOMAIN_CONFIG + "' in that the initial file is never overwritten.") String argReadOnlyDomainConfig(); /** * Instructions for the {@link CommandLineConstants#SHORT_HELP} or {@link CommandLineConstants#HELP} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Display this message and exit") String argHelp(); /** * Instructions for the {@link CommandLineConstants#INTERPROCESS_HC_ADDRESS} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Address on which the host controller should listen for communication from the process controller") String argInterProcessHcAddress(); /** * Instructions for the {@link CommandLineConstants#INTERPROCESS_HC_PORT} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Port on which the host controller should listen for communication from the process controller") String argInterProcessHcPort(); /** * Instructions for the {@link CommandLineConstants#HOST_CONFIG} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Name of the host configuration file to use (default is \"host.xml\")") String argHostConfig(); /** * Instructions for the {@link CommandLineConstants#READ_ONLY_HOST_CONFIG} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Name of the host configuration file to use. This differs from '" + CommandLineConstants.HOST_CONFIG + "' in that the initial file is never overwritten.") String argReadOnlyHostConfig(); /** * Instructions for the {@link CommandLineConstants#PROCESS_CONTROLLER_BIND_ADDR} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Address on which the process controller listens for communication from processes it controls") String argPcAddress(); /** * Instructions for the {@link CommandLineConstants#PROCESS_CONTROLLER_BIND_PORT} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Port on which the process controller listens for communication from processes it controls") String argPcPort(); /** * Instructions for the {@link CommandLineConstants#SHORT_PROPERTIES} or {@link CommandLineConstants#PROPERTIES} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Load system properties from the given url") String argProperties(); /** * Instructions for the {@link CommandLineConstants#SYS_PROP} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Set a system property") String argSystem(); /** * Instructions for the {@link CommandLineConstants#SHORT_VERSION}, {@link CommandLineConstants#OLD_SHORT_VERSION} or {@link CommandLineConstants#VERSION} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Print version and exit") String argVersion(); /** * Instructions for the {@link CommandLineConstants#PUBLIC_BIND_ADDRESS} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Set system property jboss.bind.address to the given value") String argPublicBindAddress(); /** * Instructions for the {@code -b<interface></interface>} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Set system property jboss.bind.address.<interface> to the given value") String argInterfaceBindAddress(); /** * Instructions for the {@link CommandLineConstants#DEFAULT_MULTICAST_ADDRESS} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Set system property jboss.default.multicast.address to the given value") String argDefaultMulticastAddress(); /** * Instructions for the {@link CommandLineConstants#ADMIN_ONLY} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Set the host controller's running type to ADMIN_ONLY causing it to open administrative interfaces and accept management requests but not start servers or, if this host controller is the master for the domain, accept incoming connections from slave host controllers.") String argAdminOnly(); /** * Instructions for the {@link CommandLineConstants#MASTER_ADDRESS} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Set system property jboss.domain.master.address to the given value. In a default slave Host Controller config, this is used to configure the address of the master Host Controller.") String argMasterAddress(); /** * Instructions for the {@link CommandLineConstants#MASTER_PORT} command line argument. * * @return the message. */ @Message(id = Message.NONE, value = "Set system property jboss.domain.master.port to the given value. In a default slave Host Controller config, this is used to configure the port used for native management communication by the master Host Controller.") String argMasterPort(); /** * Instructions for the {@link CommandLineConstants#SECMGR} command line argument. * * @return the message */ @Message(id = Message.NONE, value = "Runs the server with a security manager installed.") String argSecMgr(); /** * Error message indicating no value was provided for a command line argument. * * @param argument the name of the argument * * @return the message. */ @Message(id = 23, value = "No value was provided for argument %s") String noArgValue(String argument); // /** // * Creates an exception indicating the Java executable could not be found. // * // * @param binDir the directory the executable file should be located. // * // * @return an {@link IllegalStateException} for the error. // */ // @Message(id = 24, value = "Could not find java executable under %s.") // IllegalStateException cannotFindJavaExe(String binDir); /** * Creates an exception indicating the authentication key must be 16 bytes long. * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 25, value = "Authentication key must be 24 bytes long") IllegalArgumentException invalidAuthKeyLen(); // /** // * Creates an exception indicating the command must have at least one entry. // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 26, value = "cmd must have at least one entry") // IllegalArgumentException invalidCommandLen(); // /** // * Creates an exception indicating the Java home directory does not exist. // * // * @param dir the directory to Java home. // * // * @return an {@link IllegalStateException} for the error. // */ // @Message(id = 27, value = "Java home '%s' does not exist.") // IllegalStateException invalidJavaHome(String dir); // /** // * Creates an exception indicating the Java home bin directory does not exist. // * // * @param binDir the bin directory. // * @param javaHomeDir the Java home directory. // * // * @return an {@link IllegalStateException} for the error. // */ // @Message(id = 28, value = "Java home's bin '%s' does not exist. The home directory was determined to be %s.") // IllegalStateException invalidJavaHomeBin(String binDir, String javaHomeDir); /** * Creates an exception indicating the parameter has an invalid length. * * @param parameterName the parameter name. * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 29, value = "%s length is invalid") IllegalArgumentException invalidLength(String parameterName); /** * Creates an exception indicating the option, represented by the {@code option} parameter, is invalid. * * @param option the invalid option. * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 30, value = "Invalid option: %s") IllegalArgumentException invalidOption(String option); /** * Creates an exception indicating a command contains a {@code null} component. * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 31, value = "Command contains a null component") IllegalArgumentException nullCommandComponent(); // id = 32; redundant parameter null check message /** * Logs an error message indicating a failure to accept the connection. * * @param cause the cause of the error. */ @LogMessage(level = ERROR) @Message(id = 33, value = "Failed to accept a connection") void failedToAcceptConnection(@Cause Throwable cause); /** * Logs an error message indicating a failure to close the resource. * * @param cause the cause of the error. * @param resource the resource. */ @LogMessage(level = ERROR) @Message(id = 34, value = "Failed to close resource %s") void failedToCloseResource(@Cause Throwable cause, Object resource); /** * Logs an error message indicating a failure to close the server socket. * * @param cause the cause of the error. * @param socket the server socket. */ @LogMessage(level = ERROR) @Message(id = 35, value = "Failed to close the server socket %s") void failedToCloseServerSocket(@Cause Throwable cause, ServerSocket socket); /** * Logs an error message indicating a failure to close the socket. * * @param cause the cause of the error. */ @LogMessage(level = ERROR) @Message(id = 36, value = "Failed to close a socket") void failedToCloseSocket(@Cause Throwable cause); //@LogMessage(level = ERROR) //@Message(id = 37, value = "Failed to finish the marshaller %s") //void failedToFinishMarshaller(@Cause Throwable cause, Marshaller marshaller); //@LogMessage(level = ERROR) //@Message(id = 38, value = "Failed to finish the unmarshaller %s") //void failedToFinishUnmarshaller(@Cause Throwable cause, Unmarshaller unmarshaller); /** * Logs an error message indicating a failure to handle the incoming connection. * * @param cause the cause of the error. */ @LogMessage(level = ERROR) @Message(id = 39, value = "Failed to handle incoming connection") void failedToHandleIncomingConnection(@Cause Throwable cause); /** * Logs an error messaged indicating a failure to handle the socket failure condition. * * @param cause the cause of the error. */ @LogMessage(level = ERROR) @Message(id = 40, value = "Failed to handle socket failure condition") void failedToHandleSocketFailure(@Cause Throwable cause); /** * Logs an error messaged indicating a failure to handle the socket finished condition. * * @param cause the cause of the error. */ @LogMessage(level = ERROR) @Message(id = 41, value = "Failed to handle socket finished condition") void failedToHandleSocketFinished(@Cause Throwable cause); /** * Logs an error messaged indicating a failure to handle the socket shut down condition. * * @param cause the cause of the error. */ @LogMessage(level = ERROR) @Message(id = 42, value = "Failed to handle socket shut down condition") void failedToHandleSocketShutdown(@Cause Throwable cause); /** * Logs an error message indicating a failure to read a message. * * @param cause the cause of the error. */ @LogMessage(level = ERROR) @Message(id = 43, value = "Failed to read a message") void failedToReadMessage(@Cause Throwable cause); /** * Logs a warning message indicating the leakage of the message outout stream. */ @LogMessage(level = WARN) @Message(id = 44, value = "Leaked a message output stream; cleaning") void leakedMessageOutputStream(); /** * Creates an exception indicating a failure to create the server thread. * * @return an {@link java.io.IOException} for the error. */ @Message(id = 45, value = "Failed to create server thread") IOException failedToCreateServerThread(); /** * Creates an exception indicating a failure to read the object. * * @param cause the cause of the error. * * @return an {@link java.io.IOException} for the error. */ @Message(id = 46, value = "Failed to read object") IOException failedToReadObject(@Cause Throwable cause); /** * Creates an exception indicating an invalid byte. * * @return an {@link java.io.UTFDataFormatException} for the error. */ @Message(id = 47, value = "Invalid byte") UTFDataFormatException invalidByte(); /** * Creates an exception indicating an invalid byte. * * @param c the character. * @param i the raw integer. * * @return an {@link java.io.UTFDataFormatException} for the error. */ @Message(id = 48, value = "Invalid byte:%s(%d)") UTFDataFormatException invalidByte(char c, int i); /** * Creates an exception indicating an invalid byte token was found. * * @param expected the expected value. * @param actual the actual value. * * @return an {@link java.io.IOException} for the error. */ @Message(id = 49, value = "Invalid byte token. Expecting '%s' received '%s'") IOException invalidByteToken(int expected, byte actual); /** * Creates an exception indicating an invalid command byte was read. * * @param commandByte the command byte read. * * @return an {@link java.io.IOException} for the error. */ @Message(id = 50, value = "Invalid command byte read: %s") IOException invalidCommandByte(int commandByte); // @Message(id = 61, value = "Invalid signature [%s]") // IOException invalidSignature(String signature); /** * Creates an exception indicating an invalid start chunk was found. * * @param chunk the start chunk. * * @return an {@code IOException} for the error. */ @Message(id = 51, value = "Invalid start chunk start [%s]") IOException invalidStartChunk(int chunk); // @Message(id = 53, value = "Invalid type: %s") // IOException invalidType(String type); // @Message(id = 54, value = "Type is neither %s or %s: %s") // IllegalArgumentException invalidType(String validType1, String validType2, byte providedType); // @Message(id = 55, value = "Only '%s' is a valid url") // IllegalArgumentException invalidUrl(String url); /** * Creates an exception indicating the number of bytes read. * * @param bytesRead the number of bytes read. * * @return an {@link java.io.EOFException} for the error. */ @Message(id = 56, value = "Read %d bytes.") EOFException readBytes(int bytesRead); // /** // * Creates an exception indicating there was no request handler found with the id in the operation handler. // * // * @param id the id of the request handler. // * @param operationHandler the operation handler the id was not found in. // * // * @return an {@link java.io.IOException} for the error. // */ // @Message(id = 57, value = "No request handler found with id %s in operation handler %s") // IOException requestHandlerIdNotFound(byte id, ManagementOperationHandler operationHandler); /** * Creates an exception indicating the stream is closed. * * @return an {@link java.io.IOException} for the error. */ @Message(id = 58, value = "Stream closed") IOException streamClosed(); /** * Creates an exception indicating the thread creation was refused. * * @return an {@link IllegalStateException} for the error. */ @Message(id = 59, value = "Thread creation was refused") IllegalStateException threadCreationRefused(); /** * Creates an exception indicating an unexpected end of stream was detected. * * @return an {@link java.io.EOFException} for the error. */ @Message(id = 60, value = "Unexpected end of stream") EOFException unexpectedEndOfStream(); /** * Creates an exception indicating the write channel is closed. * * @return an {@link java.io.IOException} for the error. */ @Message(id = 61, value = "Write channel closed") IOException writeChannelClosed(); /** * Creates an exception indicating the writes have already been shutdown. * * @return an {@link java.io.IOException} for the error. */ @Message(id = 62, value = "Writes are already shut down") IOException writesAlreadyShutdown(); @LogMessage(level = INFO) @Message(id = 63, value = "Process '%s' did not complete normal stop within %d ms; attempting to kill process using OS calls") void attemptingToKillProcess(String process, long timeout); @LogMessage(level = INFO) @Message(id = 64, value = "Cannot locate process '%s' -- could not find the 'jps' command") void jpsCommandNotFound(String process); @LogMessage(level = INFO) @Message(id = 65, value = "No process identifiable as '%s' could be found") void processNotFound(String process); @LogMessage(level = INFO) @Message(id = 66, value = "Multiple processes identifiable as '%s' found; OS level kill cannot be safely performed") void multipleProcessesFound(String process); @LogMessage(level = INFO) @Message(id = 67, value = "Process '%s' did not complete normal stop within %d ms; attempting to destroy process " + "using java.lang.Process.destroyForcibly()") void destroyingProcess(String process, long timeout); }
/** * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng) * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.stylefeng.guns.modular.system.warpper; import cn.stylefeng.guns.core.common.constant.factory.ConstantFactory; import cn.stylefeng.roses.core.base.warpper.BaseControllerWrapper; import cn.stylefeng.roses.kernel.model.page.PageResult; import com.baomidou.mybatisplus.plugins.Page; import java.util.List; import java.util.Map; /** * 字典列表的包装 * * @author fengshuonan * @date 2017年4月25日 18:10:31 */ public class LedInfoWarpper extends BaseControllerWrapper { public LedInfoWarpper(Map<String, Object> single) { super(single); } public LedInfoWarpper(List<Map<String, Object>> multi) { super(multi); } public LedInfoWarpper(Page<Map<String, Object>> page) { super(page); } public LedInfoWarpper(PageResult<Map<String, Object>> pageResult) { super(pageResult); } @Override protected void wrapTheMap(Map<String, Object> map) { map.put("type", ConstantFactory.me().getDictsByName("ledinfo", (Integer) map.get("type"))); map.put("state", ConstantFactory.me().getDictsByName("led管理", (Integer) map.get("state"))); } }
package com.webworkz.playground.pipeline; public abstract class Event { private final EventType type; public Event(EventType type) { this.type = type; } public EventType getType() { return type; } }
package sk.henrichg.phoneprofilesplus; import android.annotation.SuppressLint; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Build; import android.provider.Settings; import android.telephony.SubscriptionInfo; import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; import android.text.Editable; import android.text.TextWatcher; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.PopupMenu; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.TooltipCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.preference.PreferenceDialogFragmentCompat; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; @SuppressWarnings("WeakerAccess") public class MobileCellsPreferenceFragmentX extends PreferenceDialogFragmentCompat { private Context prefContext; private MobileCellsPreferenceX preference; int phoneCount = 1; private AlertDialog mRenameDialog; private AlertDialog mSelectorDialog; private AlertDialog mSortDialog; private TextView cellFilter; private TextView cellName; private TextView connectedCellSIM1; private TextView connectedCellSIM2; private TextView connectedCellDefault; private MobileCellsPreferenceAdapterX listAdapter; private MobileCellNamesDialogX mMobileCellsFilterDialog; private MobileCellNamesDialogX mMobileCellNamesDialog; private AppCompatImageButton addCellButtonSIM1; private AppCompatImageButton addCellButtonSIM2; private AppCompatImageButton addCellButtonDefault; private RelativeLayout locationSystemSettingsRelLa; private TextView locationEnabledStatusTextView; private AppCompatImageButton locationSystemSettingsButton; private Button rescanButton; private RefreshListViewAsyncTask rescanAsyncTask; private RefreshListViewBroadcastReceiver refreshListViewBroadcastReceiver; @SuppressLint("InflateParams") @Override protected View onCreateDialogView(Context context) { prefContext = context; preference = (MobileCellsPreferenceX) getPreference(); preference.fragment = this; final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager != null) { phoneCount = telephonyManager.getPhoneCount(); } LayoutInflater inflater = LayoutInflater.from(context); return inflater.inflate(R.layout.dialog_mobile_cells_preference, null, false); } @Override protected void onBindDialogView(View view) { super.onBindDialogView(view); //Log.e("MobileCellsPreferenceFragmentX.onBindDialogView", "xxx"); refreshListViewBroadcastReceiver = new MobileCellsPreferenceFragmentX.RefreshListViewBroadcastReceiver(/*preference*/); LocalBroadcastManager.getInstance(prefContext).registerReceiver(refreshListViewBroadcastReceiver, new IntentFilter(PPApplication.PACKAGE_NAME + ".MobileCellsPreference_refreshListView")); PPApplication.forceStartMobileCellsScanner(prefContext); MobileCellsPreferenceX.forceStart = true; cellFilter = view.findViewById(R.id.mobile_cells_pref_dlg_cells_filter_name); if ((preference.cellFilter == null) || preference.cellFilter.isEmpty()) { if (preference.value.isEmpty()) cellFilter.setText(R.string.mobile_cell_names_dialog_item_show_all); else cellFilter.setText(R.string.mobile_cell_names_dialog_item_show_selected); } else cellFilter.setText(preference.cellFilter); cellFilter.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { refreshListView(false, Integer.MAX_VALUE); } }); cellName = view.findViewById(R.id.mobile_cells_pref_dlg_cells_name); connectedCellSIM1 = view.findViewById(R.id.mobile_cells_pref_dlg_connectedCell_sim1); connectedCellSIM2 = view.findViewById(R.id.mobile_cells_pref_dlg_connectedCell_sim2); connectedCellDefault = view.findViewById(R.id.mobile_cells_pref_dlg_connectedCell_simDefault); ListView cellsListView = view.findViewById(R.id.mobile_cells_pref_dlg_listview); listAdapter = new MobileCellsPreferenceAdapterX(prefContext, preference); cellsListView.setAdapter(listAdapter); //refreshListView(false); /* cellsListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { cellName.setText(cellsList.get(position).name); } }); */ mMobileCellsFilterDialog = new MobileCellNamesDialogX((Activity)prefContext, preference, true); cellFilter.setOnClickListener(view1 -> { if (getActivity() != null) if (!getActivity().isFinishing()) mMobileCellsFilterDialog.show(); }); mMobileCellNamesDialog = new MobileCellNamesDialogX((Activity)prefContext, preference, false); cellName.setOnClickListener(view12 -> { if (getActivity() != null) if (!getActivity().isFinishing()) mMobileCellNamesDialog.show(); }); final AppCompatImageButton editIcon = view.findViewById(R.id.mobile_cells_pref_dlg_rename); TooltipCompat.setTooltipText(editIcon, getString(R.string.mobile_cells_pref_dlg_rename_cell_button_tooltip)); editIcon.setOnClickListener(v -> { if (getActivity() != null) if (!getActivity().isFinishing()) { mRenameDialog = new AlertDialog.Builder(prefContext) .setTitle(R.string.mobile_cells_pref_dlg_cell_rename_title) .setCancelable(true) .setNegativeButton(android.R.string.cancel, null) //.setSingleChoiceItems(R.array.mobileCellsRenameArray, 0, new DialogInterface.OnClickListener() { .setItems(R.array.mobileCellsRenameArray, (dialog, which) -> { final DatabaseHandler db = DatabaseHandler.getInstance(prefContext); switch (which) { case 0: case 1: db.renameMobileCellsList(preference.filteredCellsList, cellName.getText().toString(), which == 0, preference.value); break; case 2: db.renameMobileCellsList(preference.filteredCellsList, cellName.getText().toString(), false, null); break; } refreshListView(false, Integer.MAX_VALUE); //dialog.dismiss(); }) .create(); // mRenameDialog.setOnShowListener(new DialogInterface.OnShowListener() { // @Override // public void onShow(DialogInterface dialog) { // Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE); // if (positive != null) positive.setAllCaps(false); // Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE); // if (negative != null) negative.setAllCaps(false); // } // }); mRenameDialog.show(); } }); AppCompatImageButton changeSelectionIcon = view.findViewById(R.id.mobile_cells_pref_dlg_changeSelection); TooltipCompat.setTooltipText(changeSelectionIcon, getString(R.string.mobile_cells_pref_dlg_select_button_tooltip)); changeSelectionIcon.setOnClickListener(view13 -> { if (getActivity() != null) if (!getActivity().isFinishing()) { mSelectorDialog = new AlertDialog.Builder(prefContext) .setTitle(R.string.pref_dlg_change_selection_title) .setCancelable(true) .setNegativeButton(android.R.string.cancel, null) //.setSingleChoiceItems(R.array.mobileCellsChangeSelectionArray, 0, new DialogInterface.OnClickListener() { .setItems(R.array.mobileCellsChangeSelectionArray, (dialog, which) -> { switch (which) { case 0: preference.value = ""; break; case 1: for (MobileCellsData cell : preference.filteredCellsList) { if (cell.name.equals(cellName.getText().toString())) preference.addCellId(cell.cellId); } break; case 2: preference.value = ""; for (MobileCellsData cell : preference.filteredCellsList) { preference.addCellId(cell.cellId); } break; default: } refreshListView(false, Integer.MAX_VALUE); //dialog.dismiss(); }) .create(); // mSelectorDialog.setOnShowListener(new DialogInterface.OnShowListener() { // @Override // public void onShow(DialogInterface dialog) { // Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE); // if (positive != null) positive.setAllCaps(false); // Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE); // if (negative != null) negative.setAllCaps(false); // } // }); mSelectorDialog.show(); } }); final AppCompatImageButton sortIcon = view.findViewById(R.id.mobile_cells_pref_dlg_sort); TooltipCompat.setTooltipText(sortIcon, getString(R.string.mobile_cells_pref_dlg_button_tooltip)); sortIcon.setOnClickListener(v -> { if (getActivity() != null) if (!getActivity().isFinishing()) { mSortDialog = new AlertDialog.Builder(prefContext) .setTitle(R.string.mobile_cells_pref_dlg_cell_sort_title) .setCancelable(true) .setNegativeButton(android.R.string.cancel, null) .setSingleChoiceItems(R.array.mobileCellsSortArray, preference.sortCellsBy, (dialog, which) -> { preference.sortCellsBy = which; //PPApplication.logE("MobileCellsPreferenceFragmentX.sortIcon.onClickListener", "sortCellsBy="+preference.sortCellsBy); refreshListView(false, Integer.MAX_VALUE); dialog.dismiss(); }) .create(); // mSortDialog.setOnShowListener(new DialogInterface.OnShowListener() { // @Override // public void onShow(DialogInterface dialog) { // Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE); // if (positive != null) positive.setAllCaps(false); // Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE); // if (negative != null) negative.setAllCaps(false); // } // }); mSortDialog.show(); } }); final AppCompatImageButton helpIcon = view.findViewById(R.id.mobile_cells_pref_dlg_helpIcon); TooltipCompat.setTooltipText(helpIcon, getString(R.string.help_button_tooltip)); helpIcon.setOnClickListener(v -> DialogHelpPopupWindowX.showPopup(helpIcon, R.string.menu_help, (Activity)prefContext, /*getDialog(),*/ R.string.mobile_cells_pref_dlg_help)); rescanButton = view.findViewById(R.id.mobile_cells_pref_dlg_rescanButton); if (PPApplication.HAS_FEATURE_TELEPHONY) { TelephonyManager telephonyManager = (TelephonyManager) prefContext.getSystemService(Context.TELEPHONY_SERVICE); boolean simIsReady = false; if (telephonyManager != null) { if (Build.VERSION.SDK_INT < 26) { if (telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY) // sim card is ready simIsReady = true; } else { if (Permissions.checkPhone(prefContext.getApplicationContext())) { SubscriptionManager mSubscriptionManager = (SubscriptionManager) prefContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE); //PPApplication.logE("MobileCellsPreferenceFragmentX.onBindDialogView", "mSubscriptionManager=" + mSubscriptionManager); //SubscriptionManager.from(context); if (mSubscriptionManager != null) { List<SubscriptionInfo> subscriptionList = null; try { // Loop through the subscription list i.e. SIM list. subscriptionList = mSubscriptionManager.getActiveSubscriptionInfoList(); } catch (SecurityException e) { PPApplication.recordException(e); //PPApplication.logE("MobileCellsPreferenceFragmentX.onBindDialogView", Log.getStackTraceString(e)); } //PPApplication.logE("MobileCellsPreferenceFragmentX.onBindDialogView", "subscriptionList=" + subscriptionList); if (subscriptionList != null) { //PPApplication.logE("MobileCellsPreferenceFragmentX.onBindDialogView", "subscriptionList.size()=" + subscriptionList.size()); for (int i = 0; i < subscriptionList.size();/*mSubscriptionManager.getActiveSubscriptionInfoCountMax();*/ i++) { // Get the active subscription ID for a given SIM card. SubscriptionInfo subscriptionInfo = subscriptionList.get(i); //PPApplication.logE("MobileCellsPreferenceFragmentX.onBindDialogView", "subscriptionInfo=" + subscriptionInfo); if (subscriptionInfo != null) { int slotIndex = subscriptionInfo.getSimSlotIndex(); //PPApplication.logE("MobileCellsPreferenceFragmentX.onBindDialogView", "slotIndex=" + slotIndex); //PPApplication.logE("MobileCellsPreferenceFragmentX.onBindDialogView", "telephonyManager.getSimState(slotIndex)=" + telephonyManager.getSimState(slotIndex)); if (telephonyManager.getSimState(slotIndex) == TelephonyManager.SIM_STATE_READY) { // sim card is ready //PPApplication.logE("MobileCellsPreferenceFragmentX.onBindDialogView", "sim card is ready"); simIsReady = true; break; } } } } } } } } if (simIsReady) { rescanButton.setOnClickListener(v -> { if (Permissions.grantMobileCellsDialogPermissions(prefContext)) refreshListView(true, Integer.MAX_VALUE); }); } else rescanButton.setEnabled(false); } else rescanButton.setEnabled(false); if ((Build.VERSION.SDK_INT >= 26) && (phoneCount > 1)) { addCellButtonSIM1 = view.findViewById(R.id.mobile_cells_pref_dlg_addCellButton_sim1); TooltipCompat.setTooltipText(addCellButtonSIM1, getString(R.string.mobile_cells_pref_dlg_add_button_tooltip)); addCellButtonSIM1.setOnClickListener(v -> { if (preference.registeredCellDataSIM1 != null) { preference.addCellId(preference.registeredCellDataSIM1.cellId); refreshListView(false, preference.registeredCellDataSIM1.cellId); } }); addCellButtonSIM2 = view.findViewById(R.id.mobile_cells_pref_dlg_addCellButton_sim2); TooltipCompat.setTooltipText(addCellButtonSIM2, getString(R.string.mobile_cells_pref_dlg_add_button_tooltip)); addCellButtonSIM2.setOnClickListener(v -> { if (preference.registeredCellDataSIM2 != null) { preference.addCellId(preference.registeredCellDataSIM2.cellId); refreshListView(false, preference.registeredCellDataSIM2.cellId); } }); } else { addCellButtonDefault = view.findViewById(R.id.mobile_cells_pref_dlg_addCellButton_simDefault); TooltipCompat.setTooltipText(addCellButtonDefault, getString(R.string.mobile_cells_pref_dlg_add_button_tooltip)); addCellButtonDefault.setOnClickListener(v -> { if (preference.registeredCellDataDefault != null) { preference.addCellId(preference.registeredCellDataDefault.cellId); refreshListView(false, preference.registeredCellDataDefault.cellId); } }); } boolean sim1Exists; boolean sim2Exists; synchronized (PPApplication.simCardsMutext) { sim1Exists = PPApplication.simCardsMutext.simCardsDetected; sim2Exists = sim1Exists; sim1Exists = sim1Exists && PPApplication.simCardsMutext.sim1Exists; sim2Exists = sim2Exists && PPApplication.simCardsMutext.sim2Exists; } RelativeLayout connectedCellRelLa; //noinspection IfStatementWithIdenticalBranches if ((Build.VERSION.SDK_INT >= 26) && (phoneCount > 1)) { if (!sim1Exists) { connectedCellRelLa = view.findViewById(R.id.mobile_cells_pref_dlg_reLa1_sim1); connectedCellRelLa.setVisibility(View.GONE); } if (!sim2Exists) { connectedCellRelLa = view.findViewById(R.id.mobile_cells_pref_dlg_reLa1_sim2); connectedCellRelLa.setVisibility(View.GONE); } connectedCellRelLa = view.findViewById(R.id.mobile_cells_pref_dlg_reLa1_simDefault); connectedCellRelLa.setVisibility(View.GONE); } else { connectedCellRelLa = view.findViewById(R.id.mobile_cells_pref_dlg_reLa1_sim1); if (connectedCellRelLa != null) connectedCellRelLa.setVisibility(View.GONE); connectedCellRelLa = view.findViewById(R.id.mobile_cells_pref_dlg_reLa1_sim2); if (connectedCellRelLa != null) connectedCellRelLa.setVisibility(View.GONE); } locationSystemSettingsRelLa = view.findViewById(R.id.mobile_cells_pref_dlg_locationSystemSettingsRelLa); locationEnabledStatusTextView = view.findViewById(R.id.mobile_cells_pref_dlg_locationEnableStatus); locationSystemSettingsButton = view.findViewById(R.id.mobile_cells_pref_dlg_locationSystemSettingsButton); TooltipCompat.setTooltipText(locationSystemSettingsButton, getString(R.string.location_settings_button_tooltip)); setLocationEnableStatus(); refreshListView(false, Integer.MAX_VALUE); } @Override public void onDialogClosed(boolean positiveResult) { //Log.e("MobileCellsPreferenceFragmentX.onDialogClosed", "xxx"); if (positiveResult) { preference.persistValue(); } else { preference.resetSummary(); } if ((mRenameDialog != null) && mRenameDialog.isShowing()) mRenameDialog.dismiss(); if ((mSelectorDialog != null) && mSelectorDialog.isShowing()) mSelectorDialog.dismiss(); if ((mSortDialog != null) && mSortDialog.isShowing()) mSortDialog.dismiss(); if ((rescanAsyncTask != null) && (!rescanAsyncTask.getStatus().equals(AsyncTask.Status.FINISHED))) rescanAsyncTask.cancel(true); if (refreshListViewBroadcastReceiver != null) { LocalBroadcastManager.getInstance(prefContext).unregisterReceiver(refreshListViewBroadcastReceiver); refreshListViewBroadcastReceiver = null; } MobileCellsPreferenceX.forceStart = false; PPApplication.restartMobileCellsScanner(prefContext); preference.fragment = null; } void setLocationEnableStatus() { if (Build.VERSION.SDK_INT >= 28) { String statusText; if (!PhoneProfilesService.isLocationEnabled(prefContext)) { /*if (Build.VERSION.SDK_INT < 28) statusText = prefContext.getString(R.string.phone_profiles_pref_eventLocationSystemSettings) + ":\n" + prefContext.getString(R.string.phone_profiles_pref_applicationEventScanningLocationSettingsDisabled_summary); else*/ statusText = prefContext.getString(R.string.phone_profiles_pref_eventLocationSystemSettings) + ":\n" + "* " + prefContext.getString(R.string.phone_profiles_pref_applicationEventScanningLocationSettingsDisabled_summary) + "! *"; locationEnabledStatusTextView.setText(statusText); locationSystemSettingsButton.setOnClickListener(v -> { if (getActivity() != null) { boolean ok = false; if (GlobalGUIRoutines.activityActionExists(Settings.ACTION_LOCATION_SOURCE_SETTINGS, prefContext.getApplicationContext())) { try { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); //intent.addCategory(Intent.CATEGORY_DEFAULT); //noinspection deprecation getActivity().startActivityForResult(intent, EventsPrefsFragment.RESULT_MOBILE_CELLS_LOCATION_SYSTEM_SETTINGS); ok = true; } catch (Exception e) { PPApplication.recordException(e); } } if (!ok) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(prefContext); dialogBuilder.setMessage(R.string.setting_screen_not_found_alert); //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); dialogBuilder.setPositiveButton(android.R.string.ok, null); AlertDialog dialog = dialogBuilder.create(); // dialog.setOnShowListener(new DialogInterface.OnShowListener() { // @Override // public void onShow(DialogInterface dialog) { // Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE); // if (positive != null) positive.setAllCaps(false); // Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE); // if (negative != null) negative.setAllCaps(false); // } // }); if (getActivity() != null) if (!getActivity().isFinishing()) dialog.show(); } } }); locationSystemSettingsRelLa.setVisibility(View.VISIBLE); //locationEnabledStatusTextView.setVisibility(View.VISIBLE); //locationSystemSettingsButton.setVisibility(View.VISIBLE); rescanButton.setVisibility(View.GONE); } else { locationSystemSettingsRelLa.setVisibility(View.GONE); //locationEnabledStatusTextView.setVisibility(View.GONE); //locationSystemSettingsButton.setVisibility(View.GONE); rescanButton.setVisibility(View.VISIBLE); } } else { locationSystemSettingsRelLa.setVisibility(View.GONE); //locationEnabledStatusTextView.setVisibility(View.GONE); //locationSystemSettingsButton.setVisibility(View.GONE); rescanButton.setVisibility(View.VISIBLE); } } @SuppressLint("StaticFieldLeak") public void refreshListView(final boolean forRescan, final int renameCellId) { rescanAsyncTask = new RefreshListViewAsyncTask(forRescan, renameCellId, preference, this, prefContext); rescanAsyncTask.execute(); } private static class SortByNameList implements Comparator<MobileCellsData> { public int compare(MobileCellsData lhs, MobileCellsData rhs) { if (PPApplication.collator != null) { String _lhs = ""; if (lhs._new) _lhs = _lhs + "0000"; else _lhs = _lhs + "0001"; if (lhs.name.isEmpty()) _lhs = _lhs + "0002"; else _lhs = _lhs + "0003" + lhs.name; _lhs = _lhs + "-" + lhs.cellId; String _rhs = ""; if (rhs._new) _rhs = _rhs + "0000"; else _rhs = _rhs + "0001"; if (rhs.name.isEmpty()) _rhs = _rhs + "0002"; else _rhs = _rhs + "0003" + rhs.name; _rhs = _rhs + "-" + rhs.cellId; return PPApplication.collator.compare(_lhs, _rhs); } else return 0; } } private static class SortByConnectionList implements Comparator<MobileCellsData> { public int compare(MobileCellsData lhs, MobileCellsData rhs) { if (PPApplication.collator != null) { String _lhs;// = ""; /*if (lhs._new) _lhs = _lhs + "0000"; else _lhs = _lhs + "0001"; if (lhs.name.isEmpty()) _lhs = _lhs + "0002"; else _lhs = _lhs + "0003" + lhs.name; _lhs = _lhs + "-" + lhs.cellId;*/ _lhs = String.valueOf(lhs.lastConnectedTime); String _rhs;// = ""; /*if (rhs._new) _rhs = _rhs + "0000"; else _rhs = _rhs + "0001"; if (rhs.name.isEmpty()) _rhs = _rhs + "0002"; else _rhs = _rhs + "0003" + rhs.name; _rhs = _rhs + "-" + rhs.cellId;*/ _rhs = String.valueOf(rhs.lastConnectedTime); return PPApplication.collator.compare(_rhs, _lhs); } else return 0; } } public void showEditMenu(View view) { //Context context = ((AppCompatActivity)getActivity()).getSupportActionBar().getThemedContext(); final Context _context = view.getContext(); PopupMenu popup; //if (android.os.Build.VERSION.SDK_INT >= 19) popup = new PopupMenu(_context, view, Gravity.END); //else // popup = new PopupMenu(context, view); new MenuInflater(_context).inflate(R.menu.mobile_cells_pref_item_edit, popup.getMenu()); final int cellId = (int)view.getTag(); popup.setOnMenuItemClickListener(item -> { int itemId = item.getItemId(); if (itemId == R.id.mobile_cells_pref_item_menu_delete) { if (getActivity() != null) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()); dialogBuilder.setTitle(getString(R.string.profile_context_item_delete)); dialogBuilder.setMessage(getString(R.string.delete_mobile_cell_alert_message)); //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); dialogBuilder.setPositiveButton(R.string.alert_button_yes, (dialog, which) -> { DatabaseHandler db = DatabaseHandler.getInstance(_context); db.deleteMobileCell(cellId); preference.removeCellId(cellId); refreshListView(false, Integer.MAX_VALUE); }); dialogBuilder.setNegativeButton(R.string.alert_button_no, null); AlertDialog dialog = dialogBuilder.create(); // dialog.setOnShowListener(new DialogInterface.OnShowListener() { // @Override // public void onShow(DialogInterface dialog) { // Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE); // if (positive != null) positive.setAllCaps(false); // Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE); // if (negative != null) negative.setAllCaps(false); // } // }); if ((getActivity() != null) && (!getActivity().isFinishing())) dialog.show(); } return true; } if (itemId == R.id.mobile_cells_pref_item_menu_delete_all_selected) { if (getActivity() != null) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()); dialogBuilder.setTitle(getString(R.string.profile_context_item_delete)); dialogBuilder.setMessage(getString(R.string.delete_selected_mobile_cells_alert_message)); //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); dialogBuilder.setPositiveButton(R.string.alert_button_yes, (dialog, which) -> { DatabaseHandler db = DatabaseHandler.getInstance(_context); for (MobileCellsData cell : preference.filteredCellsList) { String[] splits = preference.value.split("\\|"); for (String valueCell : splits) { if (valueCell.equals(Integer.toString(cell.cellId))) { db.deleteMobileCell(cell.cellId); preference.removeCellId(cell.cellId); } } } refreshListView(false, Integer.MAX_VALUE); }); dialogBuilder.setNegativeButton(R.string.alert_button_no, null); AlertDialog dialog = dialogBuilder.create(); // dialog.setOnShowListener(new DialogInterface.OnShowListener() { // @Override // public void onShow(DialogInterface dialog) { // Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE); // if (positive != null) positive.setAllCaps(false); // Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE); // if (negative != null) negative.setAllCaps(false); // } // }); if ((getActivity() != null) && (!getActivity().isFinishing())) dialog.show(); } return true; } else { return false; } }); if (getActivity() != null) if (!getActivity().isFinishing()) popup.show(); } public class RefreshListViewBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { // PPApplication.logE("[IN_BROADCAST] MobileCellsPreferenceFragmentX.RefreshListViewBroadcastReceiver", "xxx"); //if (preference != null) // preference.refreshListView(false, Integer.MAX_VALUE); refreshListView(false, Integer.MAX_VALUE); } } void setCellNameText(String text) { cellName.setText(text); } String getCellNameText() { return cellName.getText().toString(); } void setCellFilterText(String text) { cellFilter.setText(text); } private static class RefreshListViewAsyncTask extends AsyncTask<Void, Integer, Void> { final boolean forRescan; final int renameCellId; private final WeakReference<MobileCellsPreferenceX> preferenceWeakRef; private final WeakReference<MobileCellsPreferenceFragmentX> fragmentWeakRef; private final WeakReference<Context> prefContextWeakRef; String _cellName; List<MobileCellsData> _cellsList = null; List<MobileCellsData> _filteredCellsList = null; String _cellFilterValue; String _value; int _sortCellsBy; MobileCellsData _registeredCellDataSIM1; boolean _registeredCellInTableSIM1; boolean _registeredCellInValueSIM1; MobileCellsData _registeredCellDataSIM2; boolean _registeredCellInTableSIM2; boolean _registeredCellInValueSIM2; MobileCellsData _registeredCellDataDefault; boolean _registeredCellInTableDefault; boolean _registeredCellInValueDefault; boolean sim1Exists; boolean sim2Exists; public RefreshListViewAsyncTask(final boolean forRescan, final int renameCellId, MobileCellsPreferenceX preference, MobileCellsPreferenceFragmentX fragment, Context prefContext) { this.forRescan = forRescan; this.renameCellId = renameCellId; this.preferenceWeakRef = new WeakReference<>(preference); this.fragmentWeakRef = new WeakReference<>(fragment); this.prefContextWeakRef = new WeakReference<>(prefContext); } @Override protected void onPreExecute() { super.onPreExecute(); MobileCellsPreferenceFragmentX fragment = fragmentWeakRef.get(); if (fragment != null) { synchronized (PPApplication.simCardsMutext) { sim1Exists = PPApplication.simCardsMutext.simCardsDetected; sim2Exists = sim1Exists; sim1Exists = sim1Exists && PPApplication.simCardsMutext.sim1Exists; sim2Exists = sim2Exists && PPApplication.simCardsMutext.sim2Exists; } _cellName = fragment.cellName.getText().toString(); _cellsList = new ArrayList<>(); _filteredCellsList = new ArrayList<>(); _cellFilterValue = fragment.cellFilter.getText().toString(); _value = fragment.preference.value; _sortCellsBy = fragment.preference.sortCellsBy; if ((Build.VERSION.SDK_INT >= 26) && (fragment.phoneCount > 1)) { if (sim1Exists) { if (fragment.preference.registeredCellDataSIM1 != null) { _registeredCellDataSIM1 = new MobileCellsData(fragment.preference.registeredCellDataSIM1.cellId, fragment.preference.registeredCellDataSIM1.name, fragment.preference.registeredCellDataSIM1.connected, fragment.preference.registeredCellDataSIM1._new, fragment.preference.registeredCellDataSIM1.lastConnectedTime, fragment.preference.registeredCellDataSIM1.lastRunningEvents, fragment.preference.registeredCellDataSIM1.lastPausedEvents, fragment.preference.registeredCellDataSIM1.doNotDetect); } _registeredCellInTableSIM1 = fragment.preference.registeredCellInTableSIM1; _registeredCellInValueSIM1 = fragment.preference.registeredCellInValueSIM1; } if (sim2Exists) { if (fragment.preference.registeredCellDataSIM2 != null) { _registeredCellDataSIM2 = new MobileCellsData(fragment.preference.registeredCellDataSIM2.cellId, fragment.preference.registeredCellDataSIM2.name, fragment.preference.registeredCellDataSIM2.connected, fragment.preference.registeredCellDataSIM2._new, fragment.preference.registeredCellDataSIM2.lastConnectedTime, fragment.preference.registeredCellDataSIM2.lastRunningEvents, fragment.preference.registeredCellDataSIM2.lastPausedEvents, fragment.preference.registeredCellDataSIM2.doNotDetect); } _registeredCellInTableSIM2 = fragment.preference.registeredCellInTableSIM2; _registeredCellInValueSIM2 = fragment.preference.registeredCellInValueSIM2; } } else { if (fragment.preference.registeredCellDataDefault != null) { _registeredCellDataDefault = new MobileCellsData(fragment.preference.registeredCellDataDefault.cellId, fragment.preference.registeredCellDataDefault.name, fragment.preference.registeredCellDataDefault.connected, fragment.preference.registeredCellDataDefault._new, fragment.preference.registeredCellDataDefault.lastConnectedTime, fragment.preference.registeredCellDataDefault.lastRunningEvents, fragment.preference.registeredCellDataDefault.lastPausedEvents, fragment.preference.registeredCellDataDefault.doNotDetect); } _registeredCellInTableDefault = fragment.preference.registeredCellInTableDefault; _registeredCellInValueDefault = fragment.preference.registeredCellInValueDefault; } //dataRelativeLayout.setVisibility(View.GONE); //progressLinearLayout.setVisibility(View.VISIBLE); } } @Override protected Void doInBackground(Void... params) { synchronized (PPApplication.mobileCellsScannerMutex) { MobileCellsPreferenceFragmentX fragment = fragmentWeakRef.get(); MobileCellsPreferenceX preference = preferenceWeakRef.get(); Context prefContext = prefContextWeakRef.get(); if ((fragment != null) && (preference != null) && (prefContext != null)) { // Log.e("MobileCellsPreferenceFragmentX.refreshListView", "in doInBackground"); // Log.e("MobileCellsPreferenceFragmentX.refreshListView", "PPApplication.mobileCellsScanner="+PPApplication.mobileCellsScanner); if (forRescan) { // PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", " **** forRescan"); if ((PhoneProfilesService.getInstance() != null) && PhoneProfilesService.getInstance().isMobileCellsScannerStarted()) { // PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", " **** registerCell"); // Log.e("MobileCellsPreferenceFragmentX.refreshListView", "scanner started"); PhoneProfilesService.getInstance().getMobileCellsScanner().registerCell(); //PPApplication.sleep(200); } } // if (MobileCellsScanner.isValidCellId(MobileCellsScanner.registeredCell)) // PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", " **** registeredCell="+MobileCellsScanner.registeredCell); // else // PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "**** registeredCell=NOT valid"); // add all from table DatabaseHandler db = DatabaseHandler.getInstance(prefContext.getApplicationContext()); db.addMobileCellsToList(_cellsList, 0); _registeredCellDataSIM1 = null; _registeredCellInTableSIM1 = false; _registeredCellInValueSIM1 = false; _registeredCellDataSIM2 = null; _registeredCellInTableSIM2 = false; _registeredCellInValueSIM2 = false; _registeredCellDataDefault = null; _registeredCellInTableDefault = false; _registeredCellInValueDefault = false; if ((PhoneProfilesService.getInstance() != null) && PhoneProfilesService.getInstance().isMobileCellsScannerStarted()) { // add registered cell //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "search registered cell from scanner"); // Log.e("MobileCellsPreferenceFragmentX.refreshListView", "scanner started"); MobileCellsScanner scanner = PhoneProfilesService.getInstance().getMobileCellsScanner(); if ((Build.VERSION.SDK_INT >= 26) && (fragment.phoneCount > 1)) { if (sim1Exists) { int registeredCell = scanner.getRegisteredCell(1); // Log.e("MobileCellsPreferenceFragmentX.refreshListView", "registeredCell from sim 1 ="+registeredCell); long lastConnectedTime = scanner.getLastConnectedTime(1); for (MobileCellsData cell : _cellsList) { if (cell.cellId == registeredCell) { cell.connected = true; _registeredCellDataSIM1 = cell; _registeredCellInTableSIM1 = true; //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add registered cell from scanner - found"); break; } } if (!_registeredCellInTableSIM1 && MobileCellsScanner.isValidCellId(registeredCell)) { //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add registered cell from scanner - not found - add it to list"); synchronized (PPApplication.mobileCellsScannerMutex) { _registeredCellDataSIM1 = new MobileCellsData(registeredCell, _cellName, true, true, lastConnectedTime, MobileCellsScanner.lastRunningEventsNotOutside, MobileCellsScanner.lastPausedEventsOutside, false); _cellsList.add(_registeredCellDataSIM1); } } } if (sim2Exists) { int registeredCell = scanner.getRegisteredCell(2); // Log.e("MobileCellsPreferenceFragmentX.refreshListView", "registeredCell from sim 2 ="+registeredCell); long lastConnectedTime = scanner.getLastConnectedTime(2); for (MobileCellsData cell : _cellsList) { if (cell.cellId == registeredCell) { cell.connected = true; _registeredCellDataSIM2 = cell; _registeredCellInTableSIM2 = true; //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add registered cell from scanner - found"); break; } } if (!_registeredCellInTableSIM2 && MobileCellsScanner.isValidCellId(registeredCell)) { //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add registered cell from scanner - not found - add it to list"); synchronized (PPApplication.mobileCellsScannerMutex) { _registeredCellDataSIM2 = new MobileCellsData(registeredCell, _cellName, true, true, lastConnectedTime, MobileCellsScanner.lastRunningEventsNotOutside, MobileCellsScanner.lastPausedEventsOutside, false); _cellsList.add(_registeredCellDataSIM2); } } } } else { int registeredCell = scanner.getRegisteredCell(0); // Log.e("MobileCellsPreferenceFragmentX.refreshListView", "registeredCell from default="+registeredCell); long lastConnectedTime = scanner.getLastConnectedTime(0); for (MobileCellsData cell : _cellsList) { if (cell.cellId == registeredCell) { cell.connected = true; _registeredCellDataDefault = cell; _registeredCellInTableDefault = true; //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add registered cell from scanner - found"); break; } } if (!_registeredCellInTableDefault && MobileCellsScanner.isValidCellId(registeredCell)) { //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add registered cell from scanner - not found - add it to list"); synchronized (PPApplication.mobileCellsScannerMutex) { _registeredCellDataDefault = new MobileCellsData(registeredCell, _cellName, true, true, lastConnectedTime, MobileCellsScanner.lastRunningEventsNotOutside, MobileCellsScanner.lastPausedEventsOutside, false); _cellsList.add(_registeredCellDataDefault); } } } /*if (!_registeredCellInTable) { PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add registered cell from scanner - NOT added into list"); } else { PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add registered cell from scanner - registeredCellData.cellId="+_registeredCellData.cellId); }*/ } // add all from value /*if (PPApplication.logEnabled()) { PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "search cells from preference value"); PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "_value=" + _value); }*/ String[] splits = _value.split("\\|"); for (String cell : splits) { if (cell.isEmpty()) continue; boolean found = false; for (MobileCellsData mCell : _cellsList) { if (cell.equals(Integer.toString(mCell.cellId))) { found = true; //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add cells from preference value - found"); break; } } if (!found) { try { int iCell = Integer.parseInt(cell); _cellsList.add(new MobileCellsData(iCell, _cellName, false, false, 0, "", "", false)); //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add cells from preference value - not found - add it to list"); } catch (Exception e) { //PPApplication.recordException(e); } } if ((Build.VERSION.SDK_INT >= 26) && (fragment.phoneCount > 1)) { if (sim1Exists) { if (_registeredCellDataSIM1 != null) { //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add cells from preference value - registeredCellData.cellId="+registeredCellData.cellId); //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add cells from preference value - cell="+cell); if (Integer.parseInt(cell) == _registeredCellDataSIM1.cellId) _registeredCellInValueSIM1 = true; } } if (sim2Exists) { if (_registeredCellDataSIM2 != null) { //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add cells from preference value - registeredCellData.cellId="+registeredCellData.cellId); //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add cells from preference value - cell="+cell); if (Integer.parseInt(cell) == _registeredCellDataSIM2.cellId) _registeredCellInValueSIM2 = true; } } } else { if (_registeredCellDataDefault != null) { //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add cells from preference value - registeredCellData.cellId="+registeredCellData.cellId); //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add cells from preference value - cell="+cell); if (Integer.parseInt(cell) == _registeredCellDataDefault.cellId) _registeredCellInValueDefault = true; } } } /*if (PPApplication.logEnabled()) { if (!_registeredCellInValue) { PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add cells from preference value - registered cell is NOT in value"); } else { PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add cells from preference value - registered cell is in value"); } }*/ // save all from value + registeredCell to table db.saveMobileCellsList(_cellsList, true, false); // rename cell added by "plus" icon if (MobileCellsScanner.isValidCellId(renameCellId)) { String val = String.valueOf(renameCellId); db.renameMobileCellsList(_cellsList, _cellName, false, val); } if (_sortCellsBy == 0) //noinspection Java8ListSort Collections.sort(_cellsList, new SortByNameList()); else //noinspection Java8ListSort Collections.sort(_cellsList, new SortByConnectionList()); //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add cells into filtered list"); _filteredCellsList.clear(); splits = _value.split("\\|"); for (MobileCellsData cellData : _cellsList) { if (_cellFilterValue.equals(prefContext.getString(R.string.mobile_cell_names_dialog_item_show_selected))) { for (String cell : splits) { if (cell.equals(Integer.toString(cellData.cellId))) { //PPApplication.logE("MobileCellsPreferenceFragmentX.refreshListView", "add cells into filtered list - added selected cellId="+cellData.cellId); _filteredCellsList.add(cellData); break; } } } else if (_cellFilterValue.equals(prefContext.getString(R.string.mobile_cell_names_dialog_item_show_without_name))) { if (cellData.name.isEmpty()) _filteredCellsList.add(cellData); } else if (_cellFilterValue.equals(prefContext.getString(R.string.mobile_cell_names_dialog_item_show_new))) { if (cellData._new) _filteredCellsList.add(cellData); } else if (_cellFilterValue.equals(prefContext.getString(R.string.mobile_cell_names_dialog_item_show_all))) { _filteredCellsList.add(cellData); } else { if (_cellFilterValue.equals(cellData.name)) _filteredCellsList.add(cellData); } } } return null; } } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); MobileCellsPreferenceFragmentX fragment = fragmentWeakRef.get(); MobileCellsPreferenceX preference = preferenceWeakRef.get(); Context prefContext = prefContextWeakRef.get(); if ((fragment != null) && (preference != null) && (prefContext != null)) { preference.cellsList = new ArrayList<>(_cellsList); preference.filteredCellsList = new ArrayList<>(_filteredCellsList); fragment.listAdapter.notifyDataSetChanged(); if (fragment.cellName.getText().toString().isEmpty()) { boolean found = false; for (MobileCellsData cell : preference.filteredCellsList) { if (preference.isCellSelected(cell.cellId) && (!cell.name.isEmpty())) { // cell name = first selected filtered cell name. (???) fragment.cellName.setText(cell.name); found = true; } } if (!found) { // cell name = event name SharedPreferences sharedPreferences = preference.getSharedPreferences(); fragment.cellName.setText(sharedPreferences.getString(Event.PREF_EVENT_NAME, "")); } } if ((Build.VERSION.SDK_INT >= 26) && (fragment.phoneCount > 1)) { if (sim1Exists) { if (_registeredCellDataSIM1 != null) { preference.registeredCellDataSIM1 = new MobileCellsData(_registeredCellDataSIM1.cellId, _registeredCellDataSIM1.name, _registeredCellDataSIM1.connected, _registeredCellDataSIM1._new, _registeredCellDataSIM1.lastConnectedTime, _registeredCellDataSIM1.lastRunningEvents, _registeredCellDataSIM1.lastPausedEvents, _registeredCellDataSIM1.doNotDetect); } preference.registeredCellInTableSIM1 = _registeredCellInTableSIM1; preference.registeredCellInValueSIM1 = _registeredCellInValueSIM1; } if (sim2Exists) { if (_registeredCellDataSIM2 != null) { preference.registeredCellDataSIM2 = new MobileCellsData(_registeredCellDataSIM2.cellId, _registeredCellDataSIM2.name, _registeredCellDataSIM2.connected, _registeredCellDataSIM2._new, _registeredCellDataSIM2.lastConnectedTime, _registeredCellDataSIM2.lastRunningEvents, _registeredCellDataSIM2.lastPausedEvents, _registeredCellDataSIM2.doNotDetect); } preference.registeredCellInTableSIM2 = _registeredCellInTableSIM2; preference.registeredCellInValueSIM2 = _registeredCellInValueSIM2; } } else { if (_registeredCellDataDefault != null) { preference.registeredCellDataDefault = new MobileCellsData(_registeredCellDataDefault.cellId, _registeredCellDataDefault.name, _registeredCellDataDefault.connected, _registeredCellDataDefault._new, _registeredCellDataDefault.lastConnectedTime, _registeredCellDataDefault.lastRunningEvents, _registeredCellDataDefault.lastPausedEvents, _registeredCellDataDefault.doNotDetect); } preference.registeredCellInTableDefault = _registeredCellInTableDefault; preference.registeredCellInValueDefault = _registeredCellInValueDefault; } if ((Build.VERSION.SDK_INT >= 26) && (fragment.phoneCount > 1)) { if (sim1Exists) { String connectedCellName = prefContext.getString(R.string.mobile_cells_pref_dlg_connected_cell_sim1) + " "; if (preference.registeredCellDataSIM1 != null) { if (!preference.registeredCellDataSIM1.name.isEmpty()) connectedCellName = connectedCellName + preference.registeredCellDataSIM1.name + ", "; String cellFlags = ""; if (preference.registeredCellDataSIM1._new) cellFlags = cellFlags + "N"; //if (registeredCellData.connected) // cellFlags = cellFlags + "C"; if (!cellFlags.isEmpty()) connectedCellName = connectedCellName + "(" + cellFlags + ") "; connectedCellName = connectedCellName + preference.registeredCellDataSIM1.cellId; } fragment.connectedCellSIM1.setText(connectedCellName); GlobalGUIRoutines.setImageButtonEnabled((preference.registeredCellDataSIM1 != null) && !(preference.registeredCellInTableSIM1 && preference.registeredCellInValueSIM1), fragment.addCellButtonSIM1, prefContext); } if (sim2Exists) { String connectedCellName = prefContext.getString(R.string.mobile_cells_pref_dlg_connected_cell_sim2) + " "; if (preference.registeredCellDataSIM2 != null) { if (!preference.registeredCellDataSIM2.name.isEmpty()) connectedCellName = connectedCellName + preference.registeredCellDataSIM2.name + ", "; String cellFlags = ""; if (preference.registeredCellDataSIM2._new) cellFlags = cellFlags + "N"; //if (registeredCellData.connected) // cellFlags = cellFlags + "C"; if (!cellFlags.isEmpty()) connectedCellName = connectedCellName + "(" + cellFlags + ") "; connectedCellName = connectedCellName + preference.registeredCellDataSIM2.cellId; } fragment.connectedCellSIM2.setText(connectedCellName); GlobalGUIRoutines.setImageButtonEnabled((preference.registeredCellDataSIM2 != null) && !(preference.registeredCellInTableSIM2 && preference.registeredCellInValueSIM2), fragment.addCellButtonSIM2, prefContext); } } else { String connectedCellName = prefContext.getString(R.string.mobile_cells_pref_dlg_connected_cell) + " "; if (preference.registeredCellDataDefault != null) { if (!preference.registeredCellDataDefault.name.isEmpty()) connectedCellName = connectedCellName + preference.registeredCellDataDefault.name + ", "; String cellFlags = ""; if (preference.registeredCellDataDefault._new) cellFlags = cellFlags + "N"; //if (registeredCellData.connected) // cellFlags = cellFlags + "C"; if (!cellFlags.isEmpty()) connectedCellName = connectedCellName + "(" + cellFlags + ") "; connectedCellName = connectedCellName + preference.registeredCellDataDefault.cellId; } fragment.connectedCellDefault.setText(connectedCellName); GlobalGUIRoutines.setImageButtonEnabled((preference.registeredCellDataDefault != null) && !(preference.registeredCellInTableDefault && preference.registeredCellInValueDefault), fragment.addCellButtonDefault, prefContext); } } } } }
/** * Copyright (c) 2016-2019 SWAN开源 All rights reserved. * * http://www.gaoxiaoit.com/ * * 版权所有,侵权必究! */ package io.renren; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AdminApplication { public static void main(String[] args) { SpringApplication.run(AdminApplication.class, args); } }
package cn.modernpoem.date; import java.util.regex.Matcher; /** * @author zhy */ public interface DateFormatter { /** * Format the date to yyyyMMdd/yyyyMM/yyyy * * @param lastLine the last line of contents * @return date string, or null */ String format(String lastLine); /** * Format 2 digit number * * @param monthOrDate month or date less than 10 * @return 2 digit number */ static String addZeroOf(String monthOrDate) { if (monthOrDate.length() == 1) { return '0' + monthOrDate; } else { return monthOrDate; } } char[] HAN_ZI0 = "〇一二三四五六七八九".toCharArray(); char[] HAN_ZI1 = "零壹贰叁肆伍陆柒捌玖".toCharArray(); /** * Translate han_zi to number * * @param hanZi han_zi * @return number, or input char */ static String toNumber(int hanZi) { for (int i = 0; i < HAN_ZI0.length; i++) { if (hanZi == HAN_ZI0[i] || hanZi == HAN_ZI1[i]) { return String.valueOf((char) ('0' + i)); } } if (hanZi == 'o' || hanZi == 'O') { return "0"; } return String.valueOf((char) hanZi); } }
/* * Copyright 2015 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp.instrumentation; import com.google.javascript.jscomp.AbstractCompiler; import com.google.javascript.jscomp.CompilerOptions.InstrumentOption; import com.google.javascript.jscomp.CompilerPass; import com.google.javascript.rhino.Node; /** GWT compatible no-op replacement for {@code CoverageInstrumentationPass} */ public class CoverageInstrumentationPass implements CompilerPass { /** Coverage Reach */ public enum CoverageReach { ALL, CONDITIONAL } public CoverageInstrumentationPass(AbstractCompiler compiler, CoverageReach reach) { } public CoverageInstrumentationPass( AbstractCompiler compiler, CoverageReach reach, InstrumentOption notUsed, String productionInstrumentationArrayName) {} @Override public void process(Node externs, Node root) { } }
/* * MIT License * * Copyright (c) 2022 MASES s.r.l. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.windows.forms; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; // Import section // PACKAGE_IMPORT_SECTION /** * The base .NET class managing System.Windows.Forms.TextDataFormat, System.Windows.Forms, Version=6.0.2.0, Culture=neutral, PublicKeyToken=b77a5c561934e089. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Forms.TextDataFormat" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Forms.TextDataFormat</a> */ public class TextDataFormat extends NetObject { /** * Fully assembly qualified name: System.Windows.Forms, Version=6.0.2.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 */ public static final String assemblyFullName = "System.Windows.Forms, Version=6.0.2.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; /** * Assembly name: System.Windows.Forms */ public static final String assemblyShortName = "System.Windows.Forms"; /** * Qualified class name: System.Windows.Forms.TextDataFormat */ public static final String className = "System.Windows.Forms.TextDataFormat"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumReflected = createEnum(); JCEnum classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } static JCEnum createEnum() { try { String enumToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating Enum %s", enumToCreate); JCEnum enumCreated = bridge.GetEnum(enumToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created Enum: %s", (enumCreated != null) ? enumCreated.toString() : "Returned null value"); return enumCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public TextDataFormat(java.lang.Object instance) { super(instance); if (instance instanceof JCObject) { try { String enumName = NetEnum.GetName(classType, (JCObject)instance); classInstance = enumReflected.fromValue(enumName); } catch (Throwable t) { JCOReflector.writeLog(t); classInstance = enumReflected; } } else if (instance instanceof JCEnum) { classInstance = (JCEnum)instance; } } public TextDataFormat() { super(); // add reference to assemblyName.dll file try { addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } catch (Throwable jcne) { JCOReflector.writeLog(jcne); } } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public JCType getJCOType() { return classType; } final static TextDataFormat getFrom(JCEnum object, String value) { try { return new TextDataFormat(object.fromValue(value)); } catch (JCException e) { return new TextDataFormat(object); } } // Enum fields section public static TextDataFormat Text = getFrom(enumReflected, "Text"); public static TextDataFormat UnicodeText = getFrom(enumReflected, "UnicodeText"); public static TextDataFormat Rtf = getFrom(enumReflected, "Rtf"); public static TextDataFormat Html = getFrom(enumReflected, "Html"); public static TextDataFormat CommaSeparatedValue = getFrom(enumReflected, "CommaSeparatedValue"); // Flags management section }