code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
/******************************************************************************* * Copyright (C) 2014 Philipp B. Costa * * 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 br.ufc.mdcc.mpos.net; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import org.apache.log4j.Logger; import br.ufc.mdcc.mpos.net.util.Service; /** * This is a general server implementation. * * @author Philipp B. Costa */ public abstract class AbstractServer extends Thread { protected Logger logger; private Service service; protected String ip; protected String startMessage; public AbstractServer(String ip, Service service, Class<?> cls) { super(service.getName()); this.logger = Logger.getLogger(cls); this.service = service; this.ip = ip; } public Service getService() { return service; } protected void close(OutputStream os) { try { if (os != null) { os.close(); } } catch (IOException e) { logger.info("IOException was thrown during close Stream"); } } protected void close(Socket socket) { try { if (socket != null) { socket.close(); } } catch (IOException e) { logger.info("IOException was thrown during close Socket"); } } protected void close(InputStream is) { try { if (is != null) { is.close(); } } catch (IOException e) { logger.info("IOException was thrown during close Stream"); } } }
ufc-great/mpos
plataform/MpOS Plataform/src/br/ufc/mdcc/mpos/net/AbstractServer.java
Java
apache-2.0
2,028
package com.ratingfund.app.util; import java.io.Closeable; import java.io.IOException; public class IOCloseUtil { public static void close(Closeable ... io){ for(Closeable temp : io){ if(null!=temp){ try { temp.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
wangjiafu5d/RatingFund
src/com/ratingfund/app/util/IOCloseUtil.java
Java
apache-2.0
338
/* * Copyright (C) 2012 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. * All Rights Reserved. */ package gov.nasa.worldwind.geom; /** * @author tag * @version $Id: BarycentricPlanarShape.java 1171 2013-02-11 21:45:02Z dcollins $ */ public interface BarycentricPlanarShape { double[] getBarycentricCoords(Vec4 p); Vec4 getPoint(double[] w); @SuppressWarnings({"UnnecessaryLocalVariable"}) double[] getBilinearCoords(double alpha, double beta); }
aleo72/ww-ceem-radar
src/main/java/gov/nasa/worldwind/geom/BarycentricPlanarShape.java
Java
apache-2.0
542
package commons; import org.makagiga.commons.Flags; import org.makagiga.test.AbstractTest; import org.makagiga.test.Test; import org.makagiga.test.TestField; import org.makagiga.test.TestMethod; import org.makagiga.test.Tester; @Test(className = Flags.class) public final class TestFlags extends AbstractTest { // private private final long FLAG_A = 1 << 0; private final long FLAG_B = 1 << 1; // public @Test( fields = @TestField(name = "NONE"), methods = { @TestMethod(name = "hashCode"), @TestMethod(name = "intValue"), @TestMethod(name = "isClear", parameters = "long"), @TestMethod(name = "isSet", parameters = "long"), @TestMethod(name = "longValue"), @TestMethod(name = "valueOf", parameters = "long") } ) public void test_constructor() { Flags f; f = Flags.valueOf(0); assert f.hashCode() == f.intValue(); assert f.intValue() == 0; assert f.isClear(FLAG_A); assert f.isClear(FLAG_B); assert f.longValue() == 0L; Tester.testSerializable(f); f = Flags.valueOf(FLAG_A); assert f.hashCode() == f.intValue(); assert f.intValue() == FLAG_A; assert f.isSet(FLAG_A); assert f.isClear(FLAG_B); assert f.longValue() == FLAG_A; Tester.testSerializable(f); f = Flags.valueOf(FLAG_B); assert f.hashCode() == f.intValue(); assert f.intValue() == FLAG_B; assert f.isSet(FLAG_B); assert f.isClear(FLAG_A); assert f.longValue() == FLAG_B; Tester.testSerializable(f); f = Flags.valueOf(Long.MAX_VALUE); assert f.hashCode() == Long.hashCode(Long.MAX_VALUE); assert f.intValue() == (int)Long.MAX_VALUE; assert f.isSet(FLAG_A); assert f.isSet(FLAG_B); assert f.longValue() == Long.MAX_VALUE; Tester.testSerializable(f); // cache Flags f0 = Flags.valueOf(0); assert f0 == Flags.NONE; assert f0.intValue() == 0; Flags f1 = Flags.valueOf(1 << 0); assert f1.intValue() == 1 << 0; assert Flags.valueOf(1 << 0) == f1; Flags f2 = Flags.valueOf(1 << 1); assert f2.intValue() == 1 << 1; assert Flags.valueOf(1 << 1) == f2; } @Test( methods = @TestMethod(name = "equals", parameters = "Object") ) public void test_equals() { Flags f1 = Flags.valueOf(Long.MAX_VALUE); Flags f2 = Flags.valueOf(Long.MAX_VALUE); Flags f3 = Flags.valueOf(Long.MAX_VALUE); assert f1 != f2; assert f2 != f3; Tester.testEquals(f1, f2, f3); Flags a = Flags.valueOf(FLAG_A); assert !a.equals(f1); assert !f1.equals(a); } }
stuffer2325/Makagiga
test/src/commons/TestFlags.java
Java
apache-2.0
2,441
/** * Copyright 2014 John Lawson * * TECSResultHandler.java is part of JCluster. 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 uk.co.jwlawson.jcluster; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.jwlawson.jcluster.data.MatrixInfo; /** * Callable which handles results from a CompletionService. * * <p> * Implementations should handle each result as it is computed and provide a final MatrixInfo object * once all results have been considered. * * @author John Lawson * */ public abstract class TECSResultHandler implements Callable<MatrixInfo> { private final Logger log = LoggerFactory.getLogger(getClass()); /** CompletionService which gives the futures once completed. */ private TrackingExecutorCompletionService<MatrixInfo> mService; /** True if the completion service is running and has tasks being submitted. */ private final AtomicBoolean mRunning; /** Initial MatrixInfo object containing the original matrix and any info known about it. */ private final MatrixInfo mInitial; /** Lock to check whether the hanlder is waiting for a mTask. */ private final ReentrantLock mLock; /** Reference to thread which is handling results. */ private final AtomicReference<Thread> mHandlingThread; /** Task creating the results. */ @Nullable private MatrixTask<?> mTask; /** * Create a new instance with the specified initial MatrixInfo object. * * @param initial Initial matrix */ public TECSResultHandler(MatrixInfo initial) { mInitial = initial; mRunning = new AtomicBoolean(true); mHandlingThread = new AtomicReference<Thread>(); mLock = new ReentrantLock(); } /** * Set the CompletionService to take results from. * * @param mService CompletionService */ public void setCompletionService(TrackingExecutorCompletionService<MatrixInfo> mService) { this.mService = mService; } /** * Set the main mTask which is being run and which is relying on the results from this. * * @param mTask Task which is waiting for the results from this */ public void setTask(MatrixTask<?> task) { this.mTask = task; } /** * Request that the overlying mTask stops if it has been set. * <p> * This should be used if the results from the calculations carried out so far has determined the * final information required, so no further calculations are required. */ protected void requestStop() { if (mTask != null) { mTask.requestStop(); } } /** * Inform the result handler that all tasks have been submitted to the CompletionService, so once * the service has no further results to provide then the results handler should return its final * result. */ public final void allTasksSubmitted() { log.debug("All tasks submitted"); mRunning.set(false); if (mLock.isLocked()) { log.debug("Interrupting thread {} from thread {} as it is waiting for mTask", mHandlingThread .get().getName(), Thread.currentThread().getName()); mHandlingThread.get().interrupt(); } } @Override public final MatrixInfo call() throws Exception { mHandlingThread.set(Thread.currentThread()); while (mService.hasResult() || mRunning.get()) { Future<MatrixInfo> future = null; mLock.lock(); try { future = mService.poll(1, TimeUnit.SECONDS); } catch (InterruptedException e) { log.debug("Polling for result was interrupted in thread {}", mHandlingThread.get() .getName()); continue; } finally { mLock.unlock(); } if (future == null) { log.debug("TECS has no results. Poll fell through. hasResult: {}, Running:{}", mService.hasResult(), mRunning.get()); continue; } MatrixInfo result = future.get(); handleResult(result); } return getFinal(); } /** * Handle the computed result. * * @param result New result */ protected abstract void handleResult(MatrixInfo result); /** * Get the final result to return once all results have been handled. * * @return Final MatrixInfo result */ protected abstract MatrixInfo getFinal(); /** * Get the original MatrixInfo object. Used by subclasses to combine the information from the * results with the original info. * * @return Initial MatrixInfo object */ protected final MatrixInfo getInitial() { return mInitial; } }
jwlawson/JCluster
jCluster-core/src/main/java/uk/co/jwlawson/jcluster/TECSResultHandler.java
Java
apache-2.0
5,100
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.skywalking.apm.plugin.vertx3.define; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.matcher.ElementMatcher; import org.apache.skywalking.apm.agent.core.plugin.interceptor.ConstructorInterceptPoint; import org.apache.skywalking.apm.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint; import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.ClassInstanceMethodsEnhancePluginDefine; import org.apache.skywalking.apm.agent.core.plugin.match.ClassMatch; import org.apache.skywalking.apm.agent.core.plugin.match.NameMatch; import static net.bytebuddy.matcher.ElementMatchers.any; /** * {@link HttpServerRequestWrapperConstructorInstrumentation} enhance the constructor in * <code>io.vertx.ext.web.impl.HttpServerRequestWrapper</code> class by * <code>HttpServerRequestWrapperConstructorInterceptor</code> class. */ public class HttpServerRequestWrapperConstructorInstrumentation extends ClassInstanceMethodsEnhancePluginDefine { private static final String ENHANCE_CLASS = "io.vertx.ext.web.impl.HttpServerRequestWrapper"; private static final String INTERCEPT_CLASS = "org.apache.skywalking.apm.plugin.vertx3.HttpServerRequestWrapperConstructorInterceptor"; @Override public ConstructorInterceptPoint[] getConstructorsInterceptPoints() { return new ConstructorInterceptPoint[] { new ConstructorInterceptPoint() { @Override public ElementMatcher<MethodDescription> getConstructorMatcher() { return any(); } @Override public String getConstructorInterceptor() { return INTERCEPT_CLASS; } } }; } @Override public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() { return new InstanceMethodsInterceptPoint[0]; } @Override protected ClassMatch enhanceClass() { return NameMatch.byName(ENHANCE_CLASS); } }
wu-sheng/sky-walking
apm-sniffer/apm-sdk-plugin/vertx-plugins/vertx-core-3.x-plugin/src/main/java/org/apache/skywalking/apm/plugin/vertx3/define/HttpServerRequestWrapperConstructorInstrumentation.java
Java
apache-2.0
2,884
package org.visallo.web.routes.vertex; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.Singleton; import org.visallo.webster.ParameterizedHandler; import org.visallo.webster.annotations.Handle; import org.visallo.webster.annotations.Required; import org.apache.commons.io.IOUtils; import org.vertexium.*; import org.vertexium.mutation.ElementMutation; import org.vertexium.property.StreamingPropertyValue; import org.visallo.core.exception.VisalloResourceNotFoundException; import org.visallo.core.model.ontology.Concept; import org.visallo.core.model.ontology.OntologyRepository; import org.visallo.core.model.properties.VisalloProperties; import org.visallo.core.model.workQueue.Priority; import org.visallo.core.model.workQueue.WorkQueueRepository; import org.visallo.core.model.workspace.Workspace; import org.visallo.core.model.workspace.WorkspaceRepository; import org.visallo.core.security.VisibilityTranslator; import org.visallo.core.user.User; import org.visallo.core.util.*; import org.visallo.web.clientapi.model.ClientApiVertex; import org.visallo.web.clientapi.model.VisibilityJson; import org.visallo.web.parameterProviders.ActiveWorkspaceId; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Part; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; import static org.vertexium.util.IterableUtils.toList; import static org.visallo.core.model.ontology.OntologyRepository.PUBLIC; @Singleton public class VertexUploadImage implements ParameterizedHandler { private static final VisalloLogger LOGGER = VisalloLoggerFactory.getLogger(VertexUploadImage.class); private static final String SOURCE_UPLOAD = "User Upload"; private static final String PROCESS = VertexUploadImage.class.getName(); private static final String MULTI_VALUE_KEY = VertexUploadImage.class.getName(); private final Graph graph; private final OntologyRepository ontologyRepository; private final WorkQueueRepository workQueueRepository; private final VisibilityTranslator visibilityTranslator; private final WorkspaceRepository workspaceRepository; private final String clockwiseRotationIri; private final String yAxisFlippedIri; private final String conceptIri; private final String entityHasImageIri; @Inject public VertexUploadImage( final Graph graph, final OntologyRepository ontologyRepository, final WorkQueueRepository workQueueRepository, final VisibilityTranslator visibilityTranslator, final WorkspaceRepository workspaceRepository ) { this.graph = graph; this.ontologyRepository = ontologyRepository; this.workQueueRepository = workQueueRepository; this.visibilityTranslator = visibilityTranslator; this.workspaceRepository = workspaceRepository; this.conceptIri = ontologyRepository.getRequiredConceptIRIByIntent("entityImage", PUBLIC); this.entityHasImageIri = ontologyRepository.getRequiredRelationshipIRIByIntent("entityHasImage", PUBLIC); this.yAxisFlippedIri = ontologyRepository.getRequiredPropertyIRIByIntent("media.yAxisFlipped", PUBLIC); this.clockwiseRotationIri = ontologyRepository.getRequiredPropertyIRIByIntent("media.clockwiseRotation", PUBLIC); } @Handle public ClientApiVertex handle( HttpServletRequest request, @Required(name = "graphVertexId") String graphVertexId, @ActiveWorkspaceId String workspaceId, User user, Authorizations authorizations ) throws Exception { final List<Part> files = Lists.newArrayList(request.getParts()); Concept concept = ontologyRepository.getConceptByIRI(conceptIri, workspaceId); checkNotNull(concept, "Could not find image concept: " + conceptIri); if (files.size() != 1) { throw new RuntimeException("Wrong number of uploaded files. Expected 1 got " + files.size()); } final Part file = files.get(0); Workspace workspace = this.workspaceRepository.findById(workspaceId, user); Vertex entityVertex = graph.getVertex(graphVertexId, authorizations); if (entityVertex == null) { throw new VisalloResourceNotFoundException(String.format("Could not find associated entity vertex for id: %s", graphVertexId)); } ElementMutation<Vertex> entityVertexMutation = entityVertex.prepareMutation(); VisibilityJson visibilityJson = getVisalloVisibility(entityVertex, workspaceId); Visibility visibility = visibilityTranslator.toVisibility(visibilityJson).getVisibility(); Metadata metadata = new Metadata(); VisalloProperties.VISIBILITY_JSON_METADATA.setMetadata(metadata, visibilityJson, visibilityTranslator.getDefaultVisibility()); VisalloProperties.MODIFIED_DATE_METADATA.setMetadata(metadata, new Date(), visibilityTranslator.getDefaultVisibility()); VisalloProperties.MODIFIED_BY_METADATA.setMetadata(metadata, user.getUserId(), visibilityTranslator.getDefaultVisibility()); String title = imageTitle(entityVertex, workspaceId); ElementBuilder<Vertex> artifactVertexBuilder = convertToArtifact(file, title, visibilityJson, metadata, user, visibility); Vertex artifactVertex = artifactVertexBuilder.save(authorizations); this.graph.flush(); entityVertexMutation.setProperty(VisalloProperties.ENTITY_IMAGE_VERTEX_ID.getPropertyName(), artifactVertex.getId(), metadata, visibility); entityVertex = entityVertexMutation.save(authorizations); graph.flush(); List<Edge> existingEdges = toList(entityVertex.getEdges(artifactVertex, Direction.BOTH, entityHasImageIri, authorizations)); if (existingEdges.size() == 0) { EdgeBuilder edgeBuilder = graph.prepareEdge(entityVertex, artifactVertex, entityHasImageIri, visibility); Visibility defaultVisibility = visibilityTranslator.getDefaultVisibility(); VisalloProperties.VISIBILITY_JSON.setProperty(edgeBuilder, visibilityJson, defaultVisibility); VisalloProperties.MODIFIED_DATE.setProperty(edgeBuilder, new Date(), defaultVisibility); VisalloProperties.MODIFIED_BY.setProperty(edgeBuilder, user.getUserId(), defaultVisibility); edgeBuilder.save(authorizations); } this.workspaceRepository.updateEntityOnWorkspace(workspace, artifactVertex.getId(), user); this.workspaceRepository.updateEntityOnWorkspace(workspace, entityVertex.getId(), user); graph.flush(); workQueueRepository.pushElement(artifactVertex, Priority.HIGH); workQueueRepository.pushGraphPropertyQueue( artifactVertex, null, VisalloProperties.RAW.getPropertyName(), workspaceId, visibilityJson.getSource(), Priority.HIGH ); workQueueRepository.pushElementImageQueue( entityVertex, null, VisalloProperties.ENTITY_IMAGE_VERTEX_ID.getPropertyName(), Priority.HIGH ); return (ClientApiVertex) ClientApiConverter.toClientApi(entityVertex, workspaceId, authorizations); } private String imageTitle(Vertex entityVertex, String workspaceId) { Property titleProperty = VisalloProperties.TITLE.getFirstProperty(entityVertex); Object title; if (titleProperty == null) { String conceptTypeProperty = VisalloProperties.CONCEPT_TYPE.getPropertyName(); String vertexConceptType = (String) entityVertex.getProperty(conceptTypeProperty).getValue(); Concept concept = ontologyRepository.getConceptByIRI(vertexConceptType, workspaceId); title = concept.getDisplayName(); } else { title = titleProperty.getValue(); } return String.format("Image of %s", title.toString()); } private VisibilityJson getVisalloVisibility(Vertex entityVertex, String workspaceId) { VisibilityJson visibilityJson = VisalloProperties.VISIBILITY_JSON.getPropertyValue(entityVertex); if (visibilityJson == null) { visibilityJson = new VisibilityJson(); } String visibilitySource = visibilityJson.getSource(); if (visibilitySource == null) { visibilitySource = ""; } return VisibilityJson.updateVisibilitySourceAndAddWorkspaceId(visibilityJson, visibilitySource, workspaceId); } protected ElementBuilder<Vertex> convertToArtifact( final Part file, String title, VisibilityJson visibilityJson, Metadata metadata, User user, Visibility visibility ) throws IOException { Visibility defaultVisibility = visibilityTranslator.getDefaultVisibility(); final InputStream fileInputStream = file.getInputStream(); final byte[] rawContent = IOUtils.toByteArray(fileInputStream); LOGGER.debug("Uploaded file raw content byte length: %d", rawContent.length); final String fileName = file.getName(); final String fileRowKey = RowKeyHelper.buildSHA256KeyString(rawContent); LOGGER.debug("Generated row key: %s", fileRowKey); StreamingPropertyValue rawValue = StreamingPropertyValue.create(new ByteArrayInputStream(rawContent), byte[].class); rawValue.searchIndex(false); rawValue.store(true); ElementBuilder<Vertex> vertexBuilder = graph.prepareVertex(visibility); // Note that VisalloProperties.MIME_TYPE is expected to be set by a GraphPropertyWorker. VisalloProperties.CONCEPT_TYPE.setProperty(vertexBuilder, conceptIri, defaultVisibility); VisalloProperties.VISIBILITY_JSON.setProperty(vertexBuilder, visibilityJson, defaultVisibility); VisalloProperties.MODIFIED_BY.setProperty(vertexBuilder, user.getUserId(), defaultVisibility); VisalloProperties.MODIFIED_DATE.setProperty(vertexBuilder, new Date(), defaultVisibility); VisalloProperties.TITLE.addPropertyValue(vertexBuilder, MULTI_VALUE_KEY, title, metadata, visibility); VisalloProperties.FILE_NAME.addPropertyValue(vertexBuilder, MULTI_VALUE_KEY, fileName, metadata, visibility); VisalloProperties.RAW.setProperty(vertexBuilder, rawValue, metadata, visibility); VisalloProperties.SOURCE.addPropertyValue(vertexBuilder, MULTI_VALUE_KEY, SOURCE_UPLOAD, metadata, visibility); VisalloProperties.PROCESS.addPropertyValue(vertexBuilder, MULTI_VALUE_KEY, PROCESS, metadata, visibility); ImageTransform imageTransform = ImageTransformExtractor.getImageTransform(rawContent); vertexBuilder.setProperty(yAxisFlippedIri, imageTransform.isYAxisFlipNeeded(), metadata, visibility); vertexBuilder.setProperty(clockwiseRotationIri, imageTransform.getCWRotationNeeded(), metadata, visibility); return vertexBuilder; } }
visallo/visallo
web/web-base/src/main/java/org/visallo/web/routes/vertex/VertexUploadImage.java
Java
apache-2.0
11,209
package batfish.logicblox; import java.util.Collections; import java.util.Map; import java.util.TreeMap; public class Facts { private static final Map<String, String> _CONTROL_PLANE_FACT_COLUMN_HEADERS = new TreeMap<String, String> (); private static final Map<String, String> _TRAFFIC_FACT_COLUMN_HEADERS = new TreeMap<String, String>(); public static final Map<String, String> CONTROL_PLANE_FACT_COLUMN_HEADERS = Collections.unmodifiableMap(_CONTROL_PLANE_FACT_COLUMN_HEADERS); public static final Map<String, String> TRAFFIC_FACT_COLUMN_HEADERS = Collections.unmodifiableMap(_TRAFFIC_FACT_COLUMN_HEADERS); static { _TRAFFIC_FACT_COLUMN_HEADERS.put("SetFlowOriginate", "NODE|SRCIP|DSTIP|SRCPORT|DSTPORT|IPPROTOCOL"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetFakeInterface", "NODE|INTERFACE"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetFlowSinkInterface", "NODE|INTERFACE"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("GuessTopology", "DUMMY"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SamePhysicalSegment", "NODE1|INTERFACE1|NODE2|INTERFACE2"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetSwitchportAccess", "SWITCH|INTERFACE|VLAN"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetSwitchportTrunkAllows", "SWITCH|INTERFACE|VLANSTART|VLANEND"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetSwitchportTrunkEncapsulation", "SWITCH|INTERFACE|ENCAPSULATION"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetSwitchportTrunkNative", "SWITCH|INTERFACE|VLAN"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetVlanInterface", "NODE|INTERFACE|VLAN"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetInterfaceFilterIn", "NODE|INTERFACE|FILTER"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetInterfaceFilterOut", "NODE|INTERFACE|FILTER"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetInterfaceRoutingPolicy", "NODE|INTERFACE|POLICY"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetNetwork", "STARTIP|START|END|PREFIXLENGTH"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetIpAccessListDenyLine", "LIST|LINE"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetIpAccessListLine", "LIST|LINE|PROTOCOL|SRCIPSTART|SRCIPEND|DSTIPSTART|DSTIPEND"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetIpAccessListLine_dstPortRange", "LIST|LINE|DSTPORTSTART|DSTPORTEND"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetIpAccessListLine_srcPortRange", "LIST|LINE|SRCPORTSTART|SRCPORTEND"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetActiveInt", "NODE|INTERFACE"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetIpInt", "NODE|INTERFACE|IP|PREFIXLENGTH"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetLinkLoadLimitIn", "NODE|INTERFACE|LIMIT"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetLinkLoadLimitOut", "NODE|INTERFACE|LIMIT"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetGeneratedRoute_flat", "NODE|NETWORKSTART|NETWORKEND|PREFIXLENGTH|ADMIN"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetGeneratedRoutePolicy_flat", "NODE|NETWORKSTART|NETWORKEND|PREFIXLENGTH|MAP"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetStaticRoute_flat", "NODE|NETWORKSTART|NETWORKEND|PREFIXLENGTH|NEXTHOPIP|ADMIN|TAG"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetStaticIntRoute_flat", "NODE|NETWORKSTART|NETWORKEND|PREFIXLENGTH|NEXTHOPIP|NEXTHOPINT|ADMIN|TAG"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetOspfGeneratedRoute_flat", "NODE|NETWORKSTART|NETWORKEND|PREFIXLENGTH"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetOspfGeneratedRoutePolicy_flat", "NODE|NETWORKSTART|NETWORKEND|PREFIXLENGTH|MAP"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetOspfInterface", "NODE|INTERFACE|AREA"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetOspfInterfaceCost", "NODE|INTERFACE|COST"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetOspfOutboundPolicyMap", "NODE|MAP"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetOspfRouterId", "NODE|IP"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetCommunityListLine", "LIST|LINE|COMMUNITY"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetCommunityListLinePermit", "LIST|LINE"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetRouteFilterLine", "LIST|LINE|NETWORKSTART|NETWORKEND|MINPREFIX|MAXPREFIX"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetRouteFilterPermitLine", "LIST|LINE"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseAddCommunity", "MAP|CLAUSE|COMMUNITY"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseDeleteCommunity", "MAP|CLAUSE|LIST"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseDeny", "MAP|CLAUSE"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseMatchAcl", "MAP|CLAUSE|ACL"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseMatchCommunityList", "MAP|CLAUSE|LIST"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseMatchNeighbor", "MAP|CLAUSE|NEIGHBORIP"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseMatchProtocol", "MAP|CLAUSE|PROTOCOL"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseMatchRouteFilter", "MAP|CLAUSE|LIST"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseMatchTag", "MAP|CLAUSE|TAG"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClausePermit", "MAP|CLAUSE"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseSetCommunity", "MAP|CLAUSE|COMMUNITY"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseSetLocalPreference", "MAP|CLAUSE|LOCALPREF"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseSetMetric", "MAP|CLAUSE|METRIC"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseSetNextHopIp", "MAP|CLAUSE|NEXTHOPIP"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapClauseSetOriginType", "MAP|CLAUSE|ORIGINTYPE"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetPolicyMapOspfExternalRouteType", "MAP|PROTOCOL"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetBgpDefaultLocalPref", "NODE|NEIGHBORIP|LOCALPREF"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetBgpExportPolicy", "NODE|NEIGHBORIP|MAP"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetBgpGeneratedRoute_flat", "NODE|NETWORKSTART|NETWORKEND|PREFIXLENGTH"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetBgpGeneratedRoutePolicy_flat", "NODE|NETWORKSTART|NETWORKEND|PREFIXLENGTH|MAP"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetBgpImportPolicy", "NODE|NEIGHBORIP|MAP"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetBgpNeighborDefaultMetric", "NODE|NEIGHBORIP|METRIC"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetBgpNeighborGeneratedRoute_flat", "NODE|NEIGHBORIP|NETWORKSTART|NETWORKEND|PREFIXLENGTH"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetBgpNeighborGeneratedRoutePolicy_flat", "NODE|NEIGHBORIP|NETWORKSTART|NETWORKEND|PREFIXLENGTH|MAP"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetBgpNeighborIp", "NODE|NEIGHBORIP"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetBgpNeighborSendCommunity", "NODE|NEIGHBORIP"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetBgpOriginationPolicy", "NODE|NEIGHBORIP|MAP"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetLocalAs", "NODE|NEIGHBORIP|LOCALAS"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetRemoteAs", "NODE|NEIGHBORIP|REMOTEAS"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetRouteReflectorClient", "NODE|NEIGHBORIP|CLUSTERID"); _CONTROL_PLANE_FACT_COLUMN_HEADERS.put("SetNodeVendor", "NODE|VENDOR"); } private Facts() { } }
andrenmaia/batfish
projects/batfish/src/batfish/logicblox/Facts.java
Java
apache-2.0
7,535
package cz.zcu.fav.remotestimulatorcontrol.model.configuration.erp; import android.util.JsonWriter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.List; import cz.zcu.fav.remotestimulatorcontrol.io.JSONHandler; import static cz.zcu.fav.remotestimulatorcontrol.model.configuration.erp.Tags.TAG_BRIGHTNESS; import static cz.zcu.fav.remotestimulatorcontrol.model.configuration.erp.Tags.TAG_DISTRIBUTION_DELAY; import static cz.zcu.fav.remotestimulatorcontrol.model.configuration.erp.Tags.TAG_DISTRIBUTION_VALUE; import static cz.zcu.fav.remotestimulatorcontrol.model.configuration.erp.Tags.TAG_EDGE; import static cz.zcu.fav.remotestimulatorcontrol.model.configuration.erp.Tags.TAG_MEDIA_OUTPUT_NAME; import static cz.zcu.fav.remotestimulatorcontrol.model.configuration.erp.Tags.TAG_OUT; import static cz.zcu.fav.remotestimulatorcontrol.model.configuration.erp.Tags.TAG_OUTPUTS; import static cz.zcu.fav.remotestimulatorcontrol.model.configuration.erp.Tags.TAG_PULS_DOWN; import static cz.zcu.fav.remotestimulatorcontrol.model.configuration.erp.Tags.TAG_PULS_UP; import static cz.zcu.fav.remotestimulatorcontrol.model.configuration.erp.Tags.TAG_RANDOM; import static cz.zcu.fav.remotestimulatorcontrol.model.configuration.erp.Tags.TAG_WAIT; /** * Třída představující IO handler pro čtení a zápis JSON dat */ class JSONHandlerERP extends JSONHandler { // region Variables // Pracovní konfigurace private final ConfigurationERP mConfiguration; // endregion // region Constructors /** * Vytvoří nový IO handler se zaměřením na JSON hodnoty * * @param configuration {@link ConfigurationERP} */ JSONHandlerERP(ConfigurationERP configuration) { super(configuration); this.mConfiguration = configuration; } // endregion // region Private methods /** * Načte všechny výstupy * * @param outputs JSON pole * @throws JSONException Pokud něco nevyjde */ private void readOutputs(JSONArray outputs) throws JSONException { List<ConfigurationERP.Output> outputList = mConfiguration.outputList; outputList.clear(); int count = mConfiguration.getOutputCount(); for (int i = 0; i < count; i++) { JSONObject outputObject = outputs.getJSONObject(i); outputList.add(readOutput(outputObject, i)); } } /** * Načte jeden výstup * * @param outputObject JSON objekt * @param id Jednoznačný identifikátor výstupu * @return {@link ConfigurationERP.Output} * @throws JSONException Pokud něco nevyjde */ private ConfigurationERP.Output readOutput(JSONObject outputObject, int id) throws JSONException { int pulsUp = outputObject.getInt(TAG_PULS_UP); int pulsDown = outputObject.getInt(TAG_PULS_DOWN); int distValue = outputObject.getInt(TAG_DISTRIBUTION_VALUE); int distDelay = outputObject.getInt(TAG_DISTRIBUTION_DELAY); int brightness = outputObject.getInt(TAG_BRIGHTNESS); String mediaName = ""; if (outputObject.has(TAG_MEDIA_OUTPUT_NAME)) { mediaName = outputObject.getString(TAG_MEDIA_OUTPUT_NAME); } ConfigurationERP.Output output = new ConfigurationERP.Output(mConfiguration, id, pulsUp, pulsDown, distValue, distDelay, brightness); output.setMediaName(mediaName); return output; } /** * Zapíše všechny výstupy * * @param writer Reference na JSON writer * @throws IOException Pokud něco nevyjde */ private void writeOutputs(JsonWriter writer) throws IOException { writer.name(TAG_OUTPUTS); writer.beginArray(); for (ConfigurationERP.Output output : mConfiguration.outputList) { writeOutput(writer, output); } writer.endArray(); } /** * Zapíše jeden výstup * * @param writer Reference na JSON writer * @param output Reference na výstup, který se má zapsat * @throws IOException Pokud něco nevyjde */ private void writeOutput(JsonWriter writer, ConfigurationERP.Output output) throws IOException { writer.beginObject(); writer.name(TAG_PULS_UP).value(output.getPulsUp()); writer.name(TAG_PULS_DOWN).value(output.getPulsDown()); writer.name(TAG_DISTRIBUTION_VALUE).value(output.getDistributionValue()); writer.name(TAG_DISTRIBUTION_DELAY).value(output.getDistributionDelay()); writer.name(TAG_BRIGHTNESS).value(output.getBrightness()); if (output.getMedia() != null) { writer.name(TAG_MEDIA_OUTPUT_NAME).value(output.getMedia().getName()); } writer.endObject(); } // endregion //region Public methods /** * {@inheritDoc} */ @Override public void read(InputStream inputStream) throws IOException { StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) builder.append(line); reader.close(); String src = builder.toString(); try { JSONObject jsonConfiguration = new JSONObject(src); readSelf(jsonConfiguration); mConfiguration.setOut(jsonConfiguration.getInt(TAG_OUT)); mConfiguration.setWait(jsonConfiguration.getInt(TAG_WAIT)); mConfiguration.setEdge(ConfigurationERP.Edge.valueOf(jsonConfiguration.getInt(TAG_EDGE))); mConfiguration.setRandom(ConfigurationERP.Random.valueOf(jsonConfiguration.getInt(TAG_RANDOM))); JSONArray outputArray = jsonConfiguration.getJSONArray(TAG_OUTPUTS); readOutputs(outputArray); } catch (JSONException e) { e.printStackTrace(); } } /** * {@inheritDoc} */ @Override public void write(OutputStream outputStream) throws IOException { JsonWriter writer = new JsonWriter(new OutputStreamWriter(outputStream)); writer.setIndent(" "); writer.beginObject(); super.writeSelf(writer); writer.name(TAG_OUT).value(mConfiguration.getOut()); writer.name(TAG_WAIT).value(mConfiguration.getWait()); writer.name(TAG_EDGE).value(mConfiguration.getEdge().ordinal()); writer.name(TAG_RANDOM).value(mConfiguration.getRandom().ordinal()); writeOutputs(writer); writer.endObject(); writer.close(); } // endregion }
stechy1/Remote-stimulator-control
app/src/main/java/cz/zcu/fav/remotestimulatorcontrol/model/configuration/erp/JSONHandlerERP.java
Java
apache-2.0
6,819
/* * Copyright 2013-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.client.v3.applications; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.immutables.value.Value; /** * The Resource response payload for the List Application Features operation */ @JsonDeserialize @Value.Immutable abstract class _ApplicationFeatureResource extends ApplicationFeature { }
cloudfoundry/cf-java-client
cloudfoundry-client/src/main/java/org/cloudfoundry/client/v3/applications/_ApplicationFeatureResource.java
Java
apache-2.0
968
package inject.property.entity; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "propertiesfiles") public class Configuration { @XmlElement(name = "file", required = true, nillable = false) private List<String> files = new ArrayList<>(); public void addFile(String fileName) { files.add(fileName); } public void addFiles(String[] filesList) { files.addAll(Arrays.asList(filesList)); } public List<String> getFiles() { return files; } }
djallalserradji/inject.property
src/main/java/inject/property/entity/Configuration.java
Java
apache-2.0
631
/* * Copyright 2016 LINE Corporation * * LINE Corporation 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.armeria.client.circuitbreaker; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.junit.Test; import com.google.common.base.Ticker; import com.google.common.testing.FakeTicker; public class SlidingWindowCounterTest { private static final FakeTicker ticker = new FakeTicker(); @Test public void testInitialState() { SlidingWindowCounter counter = new SlidingWindowCounter(ticker, Duration.ofSeconds(10), Duration.ofSeconds(1)); assertThat(counter.count()).isEqualTo(new EventCount(0, 0)); } @Test public void testOnSuccess() { SlidingWindowCounter counter = new SlidingWindowCounter(ticker, Duration.ofSeconds(10), Duration.ofSeconds(1)); assertThat(counter.onSuccess()).isEmpty(); ticker.advance(1, TimeUnit.SECONDS); assertThat(counter.onFailure()).contains(new EventCount(1, 0)); assertThat(counter.count()).isEqualTo(new EventCount(1, 0)); } @Test public void testOnFailure() { SlidingWindowCounter counter = new SlidingWindowCounter(ticker, Duration.ofSeconds(10), Duration.ofSeconds(1)); assertThat(counter.onFailure()).isEmpty(); ticker.advance(1, TimeUnit.SECONDS); assertThat(counter.onFailure()).contains(new EventCount(0, 1)); assertThat(counter.count()).isEqualTo(new EventCount(0, 1)); } @Test public void testTrim() { SlidingWindowCounter counter = new SlidingWindowCounter(ticker, Duration.ofSeconds(10), Duration.ofSeconds(1)); assertThat(counter.onSuccess()).isEmpty(); assertThat(counter.onFailure()).isEmpty(); ticker.advance(1, TimeUnit.SECONDS); assertThat(counter.onFailure()).contains(new EventCount(1, 1)); assertThat(counter.count()).isEqualTo(new EventCount(1, 1)); ticker.advance(11, TimeUnit.SECONDS); assertThat(counter.onFailure()).contains(new EventCount(0, 0)); assertThat(counter.count()).isEqualTo(new EventCount(0, 0)); } @Test public void testConcurrentAccess() throws InterruptedException { SlidingWindowCounter counter = new SlidingWindowCounter(Ticker.systemTicker(), Duration.ofMinutes(5), Duration.ofMillis(1)); int worker = 6; int batch = 100000; AtomicLong success = new AtomicLong(); AtomicLong failure = new AtomicLong(); CyclicBarrier barrier = new CyclicBarrier(worker); List<Thread> threads = new ArrayList<>(worker); for (int i = 0; i < worker; i++) { Thread t = new Thread(() -> { try { barrier.await(); long s = 0; long f = 0; for (int j = 0; j < batch; j++) { double r = ThreadLocalRandom.current().nextDouble(); if (r > 0.6) { counter.onSuccess(); s++; } else if (r > 0.2) { counter.onFailure(); f++; } } success.addAndGet(s); failure.addAndGet(f); } catch (Exception e) { e.printStackTrace(); } }); threads.add(t); t.start(); } for (Thread thread : threads) { thread.join(); } await().untilAsserted(() -> assertThat(counter.onFailure()).isPresent()); assertThat(counter.count()).isEqualTo(new EventCount(success.get(), failure.get())); } @Test public void testLateBucket() { SlidingWindowCounter counter = new SlidingWindowCounter(ticker, Duration.ofSeconds(10), Duration.ofSeconds(1)); ticker.advance(-1, TimeUnit.SECONDS); assertThat(counter.onSuccess()).isEmpty(); assertThat(counter.count()).isEqualTo(new EventCount(0, 0)); } }
imasahiro/armeria
core/src/test/java/com/linecorp/armeria/client/circuitbreaker/SlidingWindowCounterTest.java
Java
apache-2.0
5,328
/* * Copyright 2015-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.rules.args; import static org.junit.Assert.assertThat; import com.facebook.buck.rules.DefaultSourcePathResolver; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.rules.TestBuildRuleResolver; import com.facebook.buck.rules.keys.AlterRuleKeys; import com.facebook.buck.rules.keys.RuleKeyBuilder; import com.facebook.buck.rules.keys.TestDefaultRuleKeyFactory; import com.facebook.buck.rules.keys.UncachedRuleKeyBuilder; import com.facebook.buck.testutil.FakeProjectFilesystem; import com.facebook.buck.util.cache.FileHashCache; import com.facebook.buck.util.cache.FileHashCacheMode; import com.facebook.buck.util.cache.impl.DefaultFileHashCache; import com.facebook.buck.util.cache.impl.StackedFileHashCache; import com.google.common.base.Functions; import com.google.common.collect.ImmutableList; import com.google.common.hash.HashCode; import org.hamcrest.Matchers; import org.junit.Test; public class SanitizedArgTest { private RuleKeyBuilder<HashCode> createRuleKeyBuilder() { FakeProjectFilesystem projectFilesystem = new FakeProjectFilesystem(); FileHashCache fileHashCache = new StackedFileHashCache( ImmutableList.of( DefaultFileHashCache.createDefaultFileHashCache( projectFilesystem, FileHashCacheMode.DEFAULT))); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(new TestBuildRuleResolver()); SourcePathResolver resolver = DefaultSourcePathResolver.from(ruleFinder); return new UncachedRuleKeyBuilder( ruleFinder, resolver, fileHashCache, new TestDefaultRuleKeyFactory(fileHashCache, resolver, ruleFinder)); } @Test public void stringify() { SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(new TestBuildRuleResolver())); SanitizedArg arg = SanitizedArg.create(Functions.constant("sanitized"), "unsanitized"); assertThat(Arg.stringifyList(arg, pathResolver), Matchers.contains("unsanitized")); } @Test public void appendToRuleKey() { SanitizedArg arg1 = SanitizedArg.create(Functions.constant("sanitized"), "unsanitized 1"); SanitizedArg arg2 = SanitizedArg.create(Functions.constant("sanitized"), "unsanitized 2"); RuleKeyBuilder<HashCode> builder1 = createRuleKeyBuilder(); RuleKeyBuilder<HashCode> builder2 = createRuleKeyBuilder(); AlterRuleKeys.amendKey(builder1, arg1); AlterRuleKeys.amendKey(builder2, arg2); assertThat(builder1.build(), Matchers.equalTo(builder2.build())); } }
clonetwin26/buck
test/com/facebook/buck/rules/args/SanitizedArgTest.java
Java
apache-2.0
3,236
package com.example.eventhub; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.eventhub.test", appContext.getPackageName()); } }
grazianiborcai/EventHub
eventhub/src/androidTest/java/com/example/eventhub/ExampleInstrumentedTest.java
Java
apache-2.0
749
package org.edx.mobile.util.images; import android.content.Context; import android.support.annotation.NonNull; import org.edx.mobile.R; import org.edx.mobile.http.HttpConnectivityException; import org.edx.mobile.http.HttpResponseStatusException; import org.edx.mobile.logger.Logger; import org.edx.mobile.util.NetworkUtil; public enum ErrorUtils { ; protected static final Logger logger = new Logger(ErrorUtils.class.getName()); @NonNull public static String getErrorMessage(@NonNull Throwable ex, @NonNull Context context) { String errorMessage = null; if (ex instanceof HttpConnectivityException) { if (NetworkUtil.isConnected(context)) { errorMessage = context.getString(R.string.network_connected_error); } else { errorMessage = context.getString(R.string.reset_no_network_message); } } else if (ex instanceof HttpResponseStatusException) { final int status = ((HttpResponseStatusException) ex).getStatusCode(); if (status == 503) { errorMessage = context.getString(R.string.network_service_unavailable); } } if (null == errorMessage) { logger.error(ex, true /* Submit crash report since this is an unknown type of error */); errorMessage = context.getString(R.string.error_unknown); } return errorMessage; } }
FDoubleman/wd-edx-android
VideoLocker/src/main/java/org/edx/mobile/util/images/ErrorUtils.java
Java
apache-2.0
1,440
package org.nick.wwwjdic; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.os.Bundle; import android.text.ClipboardManager; import android.util.Log; import android.widget.Toast; import org.nick.wwwjdic.history.FavoritesAndHistory; import org.nick.wwwjdic.history.HistoryDbHelper; import org.nick.wwwjdic.hkr.HkrCandidates; import org.nick.wwwjdic.model.WwwjdicEntry; public abstract class DetailActivity extends ActionBarActivity { private static final String TAG = DetailActivity.class.getSimpleName(); public static final String EXTRA_IS_FAVORITE = "org.nick.wwwjdic.IS_FAVORITE"; protected HistoryDbHelper db; protected WwwjdicEntry wwwjdicEntry; protected boolean isFavorite; public static final String EXTRA_DETAILS_PARENT = "org.nick.wwwjdic.detailsParent"; public enum Parent { MAIN, DICT_CANDIDATES, KANJI_CANDIDATES, HKR_CANDIDATES, EXAMPLE_CANDIDATES, HISTORY, FAVORITES, } protected DetailActivity() { } @Override public void onCreate(Bundle state) { super.onCreate(state); setVolumeControlStream(AudioManager.STREAM_MUSIC); isFavorite = getIntent().getBooleanExtra(EXTRA_IS_FAVORITE, false); db = HistoryDbHelper.getInstance(this); } protected void copy() { ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); cm.setText(wwwjdicEntry.getHeadword()); String messageTemplate = getResources().getString( R.string.copied_to_clipboard); Toast.makeText(this, String.format(messageTemplate, wwwjdicEntry.getHeadword()), Toast.LENGTH_SHORT).show(); } @Override public Intent getParentActivityIntent () { Log.d(TAG, "getParentActivityIntent"); int parentIdx = getIntent().getIntExtra(DetailActivity.EXTRA_DETAILS_PARENT, 0); DetailActivity.Parent parent = DetailActivity.Parent.values()[parentIdx]; Log.d(TAG, "parent " + parent); switch (parent) { case MAIN: return getHomeIntent(); case DICT_CANDIDATES: return new Intent(this, DictionaryResultList.class); case KANJI_CANDIDATES: return new Intent(this, KanjiResultList.class); case EXAMPLE_CANDIDATES: return new Intent(this, ExamplesResultList.class); case HKR_CANDIDATES: return new Intent(this, HkrCandidates.class); case FAVORITES: { Intent intent = new Intent(this, FavoritesAndHistory.class); intent.putExtra(FavoritesAndHistory.EXTRA_SELECTED_TAB_IDX, FavoritesAndHistory.FAVORITES_TAB_IDX); return intent; } case HISTORY: { Intent intent = new Intent(this, FavoritesAndHistory.class); intent.putExtra(FavoritesAndHistory.EXTRA_SELECTED_TAB_IDX, FavoritesAndHistory.HISTORY_TAB_IDX); return intent; } default: return super.getParentActivityIntent(); } } }
nelenkov/wwwjdic
wwwjdic/src/org/nick/wwwjdic/DetailActivity.java
Java
apache-2.0
3,384
package put.ci.cevo.framework.retrospection; import put.ci.cevo.framework.algorithms.history.EvolutionHistory; import put.ci.cevo.framework.measures.PerformanceMeasure; import put.ci.cevo.framework.retrospection.queries.EvolutionQuery; import put.ci.cevo.framework.state.EvaluatedIndividual; import put.ci.cevo.util.random.ThreadedContext; import put.ci.cevo.util.random.ThreadedContext.Worker; import put.ci.cevo.util.sequence.Sequence; public class EvolutionaryRetrospector implements Retrospector { private final EvolutionHistory history; public EvolutionaryRetrospector(EvolutionHistory history) { this.history = history; } @Override public <V> Sequence<EvaluatedIndividual<V>> inquire(EvolutionQuery<V> query, final PerformanceMeasure<V> measure, ThreadedContext context) { return context.invoke(new Worker<EvaluatedIndividual<V>, EvaluatedIndividual<V>>() { @Override public EvaluatedIndividual<V> process(EvaluatedIndividual<V> subject, ThreadedContext context) { double performance = measure.measure(subject.getIndividual(), context).stats().getMean(); return subject.withObjectiveFitness(performance); } }, query.perform(history).toList()); } }
pliskowski/ECJ-2015
cevo-framework/src/main/java/put/ci/cevo/framework/retrospection/EvolutionaryRetrospector.java
Java
apache-2.0
1,192
package org.aml.java2raml; import java.io.IOException; import java.io.InputStreamReader; import org.aml.typesystem.IAnnotationModel; import org.aml.typesystem.java.AllObjectsAreNullable; import org.aml.typesystem.java.IAnnotationFilter; import org.junit.Test; import junit.framework.Assert; import junit.framework.TestCase; public class BasicTest extends TestCase{ @Test public void test0(){ Java2Raml r0=new Java2Raml(); r0.add(Manager.class); compare(r0.flush(), "/t1.raml"); } @Test public void test1(){ Java2Raml r0=new Java2Raml(); r0.add(NestedArray.class); compare(r0.flush(), "/t2.raml"); } @Test public void test2(){ Java2Raml r0=new Java2Raml(); r0.add(XMLSerialized.class); compare(r0.flush(), "/t3.raml"); } @Test public void test3(){ Java2Raml r0=new Java2Raml(); r0.add(XMLSerialized2.class); compare(r0.flush(), "/t4.raml"); } public void test4(){ Java2Raml r0=new Java2Raml(); r0.add(EnumTest.class); compare(r0.flush(), "/t5.raml"); } public void test5(){ Java2Raml r0=new Java2Raml(); r0.getTypeBuilderConfig().setAnnotationsFilter(new IAnnotationFilter() { @Override public boolean preserve(IAnnotationModel mdl) { return true; } }); r0.add(CustomAnnotationTypes.class); compare(r0.flush(), "/t6.raml"); } public void test6(){ Java2Raml r0=new Java2Raml(); r0.getTypeBuilderConfig().setAnnotationsFilter(new IAnnotationFilter() { @Override public boolean preserve(IAnnotationModel mdl) { return true; } }); r0.add(CustomAnnotationTypes2.class); compare(r0.flush(), "/t7.raml"); } public void test7(){ Java2Raml r0=new Java2Raml(); r0.getTypeBuilderConfig().setAnnotationsFilter(new IAnnotationFilter() { @Override public boolean preserve(IAnnotationModel mdl) { return true; } }); r0.add(CustomAnnotationTypes3.class); compare(r0.flush(), "/t8.raml"); } public void test8(){ Java2Raml r0=new Java2Raml(); r0.getTypeBuilderConfig().setAnnotationsFilter(new IAnnotationFilter() { @Override public boolean preserve(IAnnotationModel mdl) { return true; } }); r0.add(NestedAnnotations.class); compare(r0.flush(), "/t9.raml"); } public void test9(){ Java2Raml r0=new Java2Raml(); r0.getTypeBuilderConfig().setAnnotationsFilter(new IAnnotationFilter() { @Override public boolean preserve(IAnnotationModel mdl) { return true; } }); r0.getTypeBuilderConfig().setCheckNullable(new AllObjectsAreNullable()); r0.add(ValidationBean.class); compare(r0.flush(), "/t10.raml"); } public void test10(){ Java2Raml r0=new Java2Raml(); r0.add(XMLTransient.class); compare(r0.flush(), "/t12.raml"); } static String normalizeWhiteSpace(String s){ return s.replace('\r', '\n').replaceAll("\n\n","\n"); } static void compare(String s,String path){ InputStreamReader inputStreamReader = new InputStreamReader(BasicTest.class.getResourceAsStream(path)); StringBuilder bld=new StringBuilder(); while (true){ int c; try { c = inputStreamReader.read(); if (c==-1){ break; } bld.append((char)c); } catch (IOException e) { throw new IllegalStateException(); } } Assert.assertEquals(normalizeWhiteSpace(bld.toString()), normalizeWhiteSpace(s)); } }
OnPositive/aml
org.aml.java2raml/src/test/java/org/aml/java2raml/BasicTest.java
Java
apache-2.0
3,359
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.dialogflow.cx.v3beta1; import static io.grpc.MethodDescriptor.generateFullMethodName; /** * * * <pre> * Service for managing [Changelogs][google.cloud.dialogflow.cx.v3beta1.Changelog]. * </pre> */ @javax.annotation.Generated( value = "by gRPC proto compiler", comments = "Source: google/cloud/dialogflow/cx/v3beta1/changelog.proto") @io.grpc.stub.annotations.GrpcGenerated public final class ChangelogsGrpc { private ChangelogsGrpc() {} public static final String SERVICE_NAME = "google.cloud.dialogflow.cx.v3beta1.Changelogs"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor< com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsRequest, com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsResponse> getListChangelogsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "ListChangelogs", requestType = com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsRequest.class, responseType = com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsRequest, com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsResponse> getListChangelogsMethod() { io.grpc.MethodDescriptor< com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsRequest, com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsResponse> getListChangelogsMethod; if ((getListChangelogsMethod = ChangelogsGrpc.getListChangelogsMethod) == null) { synchronized (ChangelogsGrpc.class) { if ((getListChangelogsMethod = ChangelogsGrpc.getListChangelogsMethod) == null) { ChangelogsGrpc.getListChangelogsMethod = getListChangelogsMethod = io.grpc.MethodDescriptor .<com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsRequest, com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsResponse> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListChangelogs")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsResponse .getDefaultInstance())) .setSchemaDescriptor(new ChangelogsMethodDescriptorSupplier("ListChangelogs")) .build(); } } } return getListChangelogsMethod; } private static volatile io.grpc.MethodDescriptor< com.google.cloud.dialogflow.cx.v3beta1.GetChangelogRequest, com.google.cloud.dialogflow.cx.v3beta1.Changelog> getGetChangelogMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetChangelog", requestType = com.google.cloud.dialogflow.cx.v3beta1.GetChangelogRequest.class, responseType = com.google.cloud.dialogflow.cx.v3beta1.Changelog.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.cloud.dialogflow.cx.v3beta1.GetChangelogRequest, com.google.cloud.dialogflow.cx.v3beta1.Changelog> getGetChangelogMethod() { io.grpc.MethodDescriptor< com.google.cloud.dialogflow.cx.v3beta1.GetChangelogRequest, com.google.cloud.dialogflow.cx.v3beta1.Changelog> getGetChangelogMethod; if ((getGetChangelogMethod = ChangelogsGrpc.getGetChangelogMethod) == null) { synchronized (ChangelogsGrpc.class) { if ((getGetChangelogMethod = ChangelogsGrpc.getGetChangelogMethod) == null) { ChangelogsGrpc.getGetChangelogMethod = getGetChangelogMethod = io.grpc.MethodDescriptor .<com.google.cloud.dialogflow.cx.v3beta1.GetChangelogRequest, com.google.cloud.dialogflow.cx.v3beta1.Changelog> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetChangelog")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.dialogflow.cx.v3beta1.GetChangelogRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.dialogflow.cx.v3beta1.Changelog .getDefaultInstance())) .setSchemaDescriptor(new ChangelogsMethodDescriptorSupplier("GetChangelog")) .build(); } } } return getGetChangelogMethod; } /** Creates a new async stub that supports all call types for the service */ public static ChangelogsStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<ChangelogsStub> factory = new io.grpc.stub.AbstractStub.StubFactory<ChangelogsStub>() { @java.lang.Override public ChangelogsStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ChangelogsStub(channel, callOptions); } }; return ChangelogsStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static ChangelogsBlockingStub newBlockingStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<ChangelogsBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<ChangelogsBlockingStub>() { @java.lang.Override public ChangelogsBlockingStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ChangelogsBlockingStub(channel, callOptions); } }; return ChangelogsBlockingStub.newStub(factory, channel); } /** Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static ChangelogsFutureStub newFutureStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<ChangelogsFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<ChangelogsFutureStub>() { @java.lang.Override public ChangelogsFutureStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ChangelogsFutureStub(channel, callOptions); } }; return ChangelogsFutureStub.newStub(factory, channel); } /** * * * <pre> * Service for managing [Changelogs][google.cloud.dialogflow.cx.v3beta1.Changelog]. * </pre> */ public abstract static class ChangelogsImplBase implements io.grpc.BindableService { /** * * * <pre> * Returns the list of Changelogs. * </pre> */ public void listChangelogs( com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getListChangelogsMethod(), responseObserver); } /** * * * <pre> * Retrieves the specified Changelog. * </pre> */ public void getChangelog( com.google.cloud.dialogflow.cx.v3beta1.GetChangelogRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3beta1.Changelog> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getGetChangelogMethod(), responseObserver); } @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getListChangelogsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsRequest, com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsResponse>( this, METHODID_LIST_CHANGELOGS))) .addMethod( getGetChangelogMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.cloud.dialogflow.cx.v3beta1.GetChangelogRequest, com.google.cloud.dialogflow.cx.v3beta1.Changelog>( this, METHODID_GET_CHANGELOG))) .build(); } } /** * * * <pre> * Service for managing [Changelogs][google.cloud.dialogflow.cx.v3beta1.Changelog]. * </pre> */ public static final class ChangelogsStub extends io.grpc.stub.AbstractAsyncStub<ChangelogsStub> { private ChangelogsStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ChangelogsStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ChangelogsStub(channel, callOptions); } /** * * * <pre> * Returns the list of Changelogs. * </pre> */ public void listChangelogs( com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getListChangelogsMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Retrieves the specified Changelog. * </pre> */ public void getChangelog( com.google.cloud.dialogflow.cx.v3beta1.GetChangelogRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3beta1.Changelog> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetChangelogMethod(), getCallOptions()), request, responseObserver); } } /** * * * <pre> * Service for managing [Changelogs][google.cloud.dialogflow.cx.v3beta1.Changelog]. * </pre> */ public static final class ChangelogsBlockingStub extends io.grpc.stub.AbstractBlockingStub<ChangelogsBlockingStub> { private ChangelogsBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ChangelogsBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ChangelogsBlockingStub(channel, callOptions); } /** * * * <pre> * Returns the list of Changelogs. * </pre> */ public com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsResponse listChangelogs( com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getListChangelogsMethod(), getCallOptions(), request); } /** * * * <pre> * Retrieves the specified Changelog. * </pre> */ public com.google.cloud.dialogflow.cx.v3beta1.Changelog getChangelog( com.google.cloud.dialogflow.cx.v3beta1.GetChangelogRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetChangelogMethod(), getCallOptions(), request); } } /** * * * <pre> * Service for managing [Changelogs][google.cloud.dialogflow.cx.v3beta1.Changelog]. * </pre> */ public static final class ChangelogsFutureStub extends io.grpc.stub.AbstractFutureStub<ChangelogsFutureStub> { private ChangelogsFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ChangelogsFutureStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ChangelogsFutureStub(channel, callOptions); } /** * * * <pre> * Returns the list of Changelogs. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsResponse> listChangelogs(com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getListChangelogsMethod(), getCallOptions()), request); } /** * * * <pre> * Retrieves the specified Changelog. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.cloud.dialogflow.cx.v3beta1.Changelog> getChangelog(com.google.cloud.dialogflow.cx.v3beta1.GetChangelogRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetChangelogMethod(), getCallOptions()), request); } } private static final int METHODID_LIST_CHANGELOGS = 0; private static final int METHODID_GET_CHANGELOG = 1; private static final class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final ChangelogsImplBase serviceImpl; private final int methodId; MethodHandlers(ChangelogsImplBase serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_LIST_CHANGELOGS: serviceImpl.listChangelogs( (com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsRequest) request, (io.grpc.stub.StreamObserver< com.google.cloud.dialogflow.cx.v3beta1.ListChangelogsResponse>) responseObserver); break; case METHODID_GET_CHANGELOG: serviceImpl.getChangelog( (com.google.cloud.dialogflow.cx.v3beta1.GetChangelogRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3beta1.Changelog>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } private abstract static class ChangelogsBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { ChangelogsBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return com.google.cloud.dialogflow.cx.v3beta1.ChangelogProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("Changelogs"); } } private static final class ChangelogsFileDescriptorSupplier extends ChangelogsBaseDescriptorSupplier { ChangelogsFileDescriptorSupplier() {} } private static final class ChangelogsMethodDescriptorSupplier extends ChangelogsBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final String methodName; ChangelogsMethodDescriptorSupplier(String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (ChangelogsGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new ChangelogsFileDescriptorSupplier()) .addMethod(getListChangelogsMethod()) .addMethod(getGetChangelogMethod()) .build(); } } } return result; } }
googleapis/java-dialogflow-cx
grpc-google-cloud-dialogflow-cx-v3beta1/src/main/java/com/google/cloud/dialogflow/cx/v3beta1/ChangelogsGrpc.java
Java
apache-2.0
18,410
/** * Copyright (c) Anton Johansson <[email protected]> * * 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.antonjohansson.counterstrike.test; import static org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors; import static org.apache.commons.lang3.reflect.FieldUtils.getFieldsListWithAnnotation; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import org.apache.commons.beanutils.PropertyUtils; import org.junit.Assert; import org.junit.Before; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.stubbing.OngoingStubbing; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpSession; /** * Base skeleton for unit tests. * * @author Anton Johansson */ public abstract class AbstractTest extends Assert { private static final Map<Class<?>, BiFunction<Integer, String, ?>> TEST_DATA_SUPPLIERS = new HashMap<>(); static { TEST_DATA_SUPPLIERS.put(int.class, (id, name) -> id); TEST_DATA_SUPPLIERS.put(Integer.class, (id, name) -> id); TEST_DATA_SUPPLIERS.put(long.class, (id, name) -> id); TEST_DATA_SUPPLIERS.put(Long.class, (id, name) -> id); TEST_DATA_SUPPLIERS.put(short.class, (id, name) -> id); TEST_DATA_SUPPLIERS.put(Short.class, (id, name) -> id); TEST_DATA_SUPPLIERS.put(double.class, (id, name) -> 1.10 * id); TEST_DATA_SUPPLIERS.put(Double.class, (id, name) -> 1.10 * id); TEST_DATA_SUPPLIERS.put(String.class, (id, name) -> name + id); } protected MockHttpServletRequest request; protected MockHttpSession session; @Before public final void setUpInternal() { request = new MockHttpServletRequest(); session = (MockHttpSession) request.getSession(); MockitoAnnotations.initMocks(this); setUp(); initMocks(); } /** * Initializes the unit test. */ protected void setUp() {} /** * Initializes the mocks. */ protected void initMocks() {} /** * Creates a test item. * * @param clazz The class to create test item for. * @param id The ID of the test item. * @return Returns the test item. */ protected static <T> T item(Class<T> clazz, int id) { T instance = newInstance(clazz); PropertyDescriptor[] descriptors = getPropertyDescriptors(instance); for (PropertyDescriptor descriptor : descriptors) { Class<?> type = descriptor.getPropertyType(); BiFunction<Integer, String, ?> function = TEST_DATA_SUPPLIERS.get(type); if (function != null) { String name = descriptor.getName(); setProperty(instance, name, function.apply(id, name)); } } return instance; } /** * Creates a test collection. * * @param clazz The class of the items in the collection. * @return Returns the test collection. */ protected static <T> Collection<T> collection(Class<T> clazz) { return collection(clazz, 1, 2, 3, 4, 5); } /** * Creates a test collection. * * @param clazz The class of the items in the collection. * @param ids The ID's to add. * @return Returns the test collection. */ protected static <T> Collection<T> collection(Class<T> clazz, int... ids) { Collection<T> collection = new ArrayList<>(); for (int id : ids) { collection.add(item(clazz, id)); } return collection; } private static <T> void setProperty(T instance, String name, Object value) { try { PropertyUtils.setProperty(instance, name, value); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new RuntimeException(e); } } private static <T> T newInstance(Class<T> clazz) { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } /** * @see org.mockito.Mockito#when(Object) */ protected <T> OngoingStubbing<T> when(T methodCall) { return Mockito.when(methodCall); } /** * @see org.mockito.Mockito#any() */ protected <T> T any() { return Mockito.any(); } /** * @see org.mockito.Mockito#equals(Object) */ protected <T> T eq(T value) { return Mockito.eq(value); } /** * @see org.mockito.Mockito#mock(Class) */ protected <T> T mock(Class<T> classToMock) { return Mockito.mock(classToMock); } /** * @see org.mockito.Mockito#inOrder(Object...) */ protected InOrder inOrder() { return Mockito.inOrder(getAllMocks()); } /** * @see org.mockito.Mockito#verifyNoMoreInteractions(Object...) */ protected void verifyNoMoreInteractions() { Mockito.verifyNoMoreInteractions(getAllMocks()); } private Object[] getAllMocks() { try { Collection<Object> mocks = new ArrayList<>(); List<Field> fields = getFieldsListWithAnnotation(getClass(), Mock.class); for (Field field : fields) { boolean accessible = field.isAccessible(); field.setAccessible(true); Object mock = field.get(this); field.setAccessible(accessible); mocks.add(mock); } return mocks.toArray(); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } } }
anton-johansson/counter-strike-overview
src/test/java/com/antonjohansson/counterstrike/test/AbstractTest.java
Java
apache-2.0
5,870
package act; /*- * #%L * ACT Framework * %% * Copyright (C) 2014 - 2017 ActFramework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.carrotsearch.junitbenchmarks.BenchmarkRule; import org.junit.Ignore; import org.junit.Rule; import org.junit.rules.TestRule; @Ignore public class BenchmarkBase extends ActTestBase { @Rule public TestRule benchmarkRun = new BenchmarkRule(); }
actframework/actframework
src/test/java/act/BenchmarkBase.java
Java
apache-2.0
928
package com.sebarys.gazeWebsite.web.controller; import org.springframework.web.bind.annotation.RestController; @RestController public class ResultsController { }
sebarys/gaze-web
gazeWebsite-web/src/main/java/com/sebarys/gazeWebsite/web/controller/ResultsController.java
Java
apache-2.0
164
/* * 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.flink.streaming.api.graph; import org.apache.flink.annotation.Internal; import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.functions.Function; import org.apache.flink.api.common.operators.ResourceSpec; import org.apache.flink.api.common.operators.util.UserCodeObjectWrapper; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.IllegalConfigurationException; import org.apache.flink.optimizer.plantranslate.JobGraphGenerator; import org.apache.flink.runtime.checkpoint.CheckpointRetentionPolicy; import org.apache.flink.runtime.checkpoint.MasterTriggerRestoreHook; import org.apache.flink.runtime.io.network.partition.ResultPartitionType; import org.apache.flink.runtime.jobgraph.DistributionPattern; import org.apache.flink.runtime.jobgraph.InputFormatVertex; import org.apache.flink.runtime.jobgraph.JobEdge; import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobgraph.JobVertex; import org.apache.flink.runtime.jobgraph.JobVertexID; import org.apache.flink.runtime.jobgraph.OperatorID; import org.apache.flink.runtime.jobgraph.ScheduleMode; import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable; import org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration; import org.apache.flink.runtime.jobgraph.tasks.JobCheckpointingSettings; import org.apache.flink.runtime.jobmanager.scheduler.CoLocationGroup; import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup; import org.apache.flink.runtime.operators.util.TaskConfig; import org.apache.flink.runtime.state.StateBackend; import org.apache.flink.streaming.api.CheckpointingMode; import org.apache.flink.streaming.api.checkpoint.WithMasterCheckpointHook; import org.apache.flink.streaming.api.environment.CheckpointConfig; import org.apache.flink.streaming.api.operators.AbstractUdfStreamOperator; import org.apache.flink.streaming.api.operators.ChainingStrategy; import org.apache.flink.streaming.api.operators.StreamOperator; import org.apache.flink.streaming.runtime.partitioner.ForwardPartitioner; import org.apache.flink.streaming.runtime.partitioner.RescalePartitioner; import org.apache.flink.streaming.runtime.partitioner.StreamPartitioner; import org.apache.flink.streaming.runtime.tasks.StreamIterationHead; import org.apache.flink.streaming.runtime.tasks.StreamIterationTail; import org.apache.flink.util.FlinkRuntimeException; import org.apache.flink.util.SerializedValue; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * The StreamingJobGraphGenerator converts a {@link StreamGraph} into a {@link JobGraph}. */ @Internal public class StreamingJobGraphGenerator { private static final Logger LOG = LoggerFactory.getLogger(StreamingJobGraphGenerator.class); // ------------------------------------------------------------------------ public static JobGraph createJobGraph(StreamGraph streamGraph) { return new StreamingJobGraphGenerator(streamGraph).createJobGraph(); } // ------------------------------------------------------------------------ private final StreamGraph streamGraph; private final Map<Integer, JobVertex> jobVertices; private final JobGraph jobGraph; private final Collection<Integer> builtVertices; private final List<StreamEdge> physicalEdgesInOrder; private final Map<Integer, Map<Integer, StreamConfig>> chainedConfigs; private final Map<Integer, StreamConfig> vertexConfigs; private final Map<Integer, String> chainedNames; private final Map<Integer, ResourceSpec> chainedMinResources; private final Map<Integer, ResourceSpec> chainedPreferredResources; private final StreamGraphHasher defaultStreamGraphHasher; private final List<StreamGraphHasher> legacyStreamGraphHashers; private StreamingJobGraphGenerator(StreamGraph streamGraph) { this.streamGraph = streamGraph; this.defaultStreamGraphHasher = new StreamGraphHasherV2(); this.legacyStreamGraphHashers = Arrays.asList(new StreamGraphUserHashHasher()); this.jobVertices = new HashMap<>(); this.builtVertices = new HashSet<>(); this.chainedConfigs = new HashMap<>(); this.vertexConfigs = new HashMap<>(); this.chainedNames = new HashMap<>(); this.chainedMinResources = new HashMap<>(); this.chainedPreferredResources = new HashMap<>(); this.physicalEdgesInOrder = new ArrayList<>(); jobGraph = new JobGraph(streamGraph.getJobName()); } private JobGraph createJobGraph() { // make sure that all vertices start immediately jobGraph.setScheduleMode(ScheduleMode.EAGER); // Generate deterministic hashes for the nodes in order to identify them across // submission iff they didn't change. Map<Integer, byte[]> hashes = defaultStreamGraphHasher.traverseStreamGraphAndGenerateHashes(streamGraph); // Generate legacy version hashes for backwards compatibility List<Map<Integer, byte[]>> legacyHashes = new ArrayList<>(legacyStreamGraphHashers.size()); for (StreamGraphHasher hasher : legacyStreamGraphHashers) { legacyHashes.add(hasher.traverseStreamGraphAndGenerateHashes(streamGraph)); } Map<Integer, List<Tuple2<byte[], byte[]>>> chainedOperatorHashes = new HashMap<>(); setChaining(hashes, legacyHashes, chainedOperatorHashes); setPhysicalEdges(); setSlotSharingAndCoLocation(); configureCheckpointing(); JobGraphGenerator.addUserArtifactEntries(streamGraph.getEnvironment().getCachedFiles(), jobGraph); // set the ExecutionConfig last when it has been finalized try { jobGraph.setExecutionConfig(streamGraph.getExecutionConfig()); } catch (IOException e) { throw new IllegalConfigurationException("Could not serialize the ExecutionConfig." + "This indicates that non-serializable types (like custom serializers) were registered"); } return jobGraph; } private void setPhysicalEdges() { Map<Integer, List<StreamEdge>> physicalInEdgesInOrder = new HashMap<Integer, List<StreamEdge>>(); for (StreamEdge edge : physicalEdgesInOrder) { int target = edge.getTargetId(); List<StreamEdge> inEdges = physicalInEdgesInOrder.get(target); // create if not set if (inEdges == null) { inEdges = new ArrayList<>(); physicalInEdgesInOrder.put(target, inEdges); } inEdges.add(edge); } for (Map.Entry<Integer, List<StreamEdge>> inEdges : physicalInEdgesInOrder.entrySet()) { int vertex = inEdges.getKey(); List<StreamEdge> edgeList = inEdges.getValue(); vertexConfigs.get(vertex).setInPhysicalEdges(edgeList); } } /** * Sets up task chains from the source {@link StreamNode} instances. * * <p>This will recursively create all {@link JobVertex} instances. */ private void setChaining(Map<Integer, byte[]> hashes, List<Map<Integer, byte[]>> legacyHashes, Map<Integer, List<Tuple2<byte[], byte[]>>> chainedOperatorHashes) { for (Integer sourceNodeId : streamGraph.getSourceIDs()) { createChain(sourceNodeId, sourceNodeId, hashes, legacyHashes, 0, chainedOperatorHashes); } } private List<StreamEdge> createChain( Integer startNodeId, Integer currentNodeId, Map<Integer, byte[]> hashes, List<Map<Integer, byte[]>> legacyHashes, int chainIndex, Map<Integer, List<Tuple2<byte[], byte[]>>> chainedOperatorHashes) { if (!builtVertices.contains(startNodeId)) { List<StreamEdge> transitiveOutEdges = new ArrayList<StreamEdge>(); List<StreamEdge> chainableOutputs = new ArrayList<StreamEdge>(); List<StreamEdge> nonChainableOutputs = new ArrayList<StreamEdge>(); for (StreamEdge outEdge : streamGraph.getStreamNode(currentNodeId).getOutEdges()) { if (isChainable(outEdge, streamGraph)) { chainableOutputs.add(outEdge); } else { nonChainableOutputs.add(outEdge); } } for (StreamEdge chainable : chainableOutputs) { transitiveOutEdges.addAll( createChain(startNodeId, chainable.getTargetId(), hashes, legacyHashes, chainIndex + 1, chainedOperatorHashes)); } for (StreamEdge nonChainable : nonChainableOutputs) { transitiveOutEdges.add(nonChainable); createChain(nonChainable.getTargetId(), nonChainable.getTargetId(), hashes, legacyHashes, 0, chainedOperatorHashes); } List<Tuple2<byte[], byte[]>> operatorHashes = chainedOperatorHashes.computeIfAbsent(startNodeId, k -> new ArrayList<>()); byte[] primaryHashBytes = hashes.get(currentNodeId); for (Map<Integer, byte[]> legacyHash : legacyHashes) { operatorHashes.add(new Tuple2<>(primaryHashBytes, legacyHash.get(currentNodeId))); } chainedNames.put(currentNodeId, createChainedName(currentNodeId, chainableOutputs)); chainedMinResources.put(currentNodeId, createChainedMinResources(currentNodeId, chainableOutputs)); chainedPreferredResources.put(currentNodeId, createChainedPreferredResources(currentNodeId, chainableOutputs)); StreamConfig config = currentNodeId.equals(startNodeId) ? createJobVertex(startNodeId, hashes, legacyHashes, chainedOperatorHashes) : new StreamConfig(new Configuration()); setVertexConfig(currentNodeId, config, chainableOutputs, nonChainableOutputs); if (currentNodeId.equals(startNodeId)) { config.setChainStart(); config.setChainIndex(0); config.setOperatorName(streamGraph.getStreamNode(currentNodeId).getOperatorName()); config.setOutEdgesInOrder(transitiveOutEdges); config.setOutEdges(streamGraph.getStreamNode(currentNodeId).getOutEdges()); for (StreamEdge edge : transitiveOutEdges) { connect(startNodeId, edge); } config.setTransitiveChainedTaskConfigs(chainedConfigs.get(startNodeId)); } else { Map<Integer, StreamConfig> chainedConfs = chainedConfigs.get(startNodeId); if (chainedConfs == null) { chainedConfigs.put(startNodeId, new HashMap<Integer, StreamConfig>()); } config.setChainIndex(chainIndex); StreamNode node = streamGraph.getStreamNode(currentNodeId); config.setOperatorName(node.getOperatorName()); chainedConfigs.get(startNodeId).put(currentNodeId, config); } config.setOperatorID(new OperatorID(primaryHashBytes)); if (chainableOutputs.isEmpty()) { config.setChainEnd(); } return transitiveOutEdges; } else { return new ArrayList<>(); } } private String createChainedName(Integer vertexID, List<StreamEdge> chainedOutputs) { String operatorName = streamGraph.getStreamNode(vertexID).getOperatorName(); if (chainedOutputs.size() > 1) { List<String> outputChainedNames = new ArrayList<>(); for (StreamEdge chainable : chainedOutputs) { outputChainedNames.add(chainedNames.get(chainable.getTargetId())); } return operatorName + " -> (" + StringUtils.join(outputChainedNames, ", ") + ")"; } else if (chainedOutputs.size() == 1) { return operatorName + " -> " + chainedNames.get(chainedOutputs.get(0).getTargetId()); } else { return operatorName; } } private ResourceSpec createChainedMinResources(Integer vertexID, List<StreamEdge> chainedOutputs) { ResourceSpec minResources = streamGraph.getStreamNode(vertexID).getMinResources(); for (StreamEdge chainable : chainedOutputs) { minResources = minResources.merge(chainedMinResources.get(chainable.getTargetId())); } return minResources; } private ResourceSpec createChainedPreferredResources(Integer vertexID, List<StreamEdge> chainedOutputs) { ResourceSpec preferredResources = streamGraph.getStreamNode(vertexID).getPreferredResources(); for (StreamEdge chainable : chainedOutputs) { preferredResources = preferredResources.merge(chainedPreferredResources.get(chainable.getTargetId())); } return preferredResources; } private StreamConfig createJobVertex( Integer streamNodeId, Map<Integer, byte[]> hashes, List<Map<Integer, byte[]>> legacyHashes, Map<Integer, List<Tuple2<byte[], byte[]>>> chainedOperatorHashes) { JobVertex jobVertex; StreamNode streamNode = streamGraph.getStreamNode(streamNodeId); byte[] hash = hashes.get(streamNodeId); if (hash == null) { throw new IllegalStateException("Cannot find node hash. " + "Did you generate them before calling this method?"); } JobVertexID jobVertexId = new JobVertexID(hash); List<JobVertexID> legacyJobVertexIds = new ArrayList<>(legacyHashes.size()); for (Map<Integer, byte[]> legacyHash : legacyHashes) { hash = legacyHash.get(streamNodeId); if (null != hash) { legacyJobVertexIds.add(new JobVertexID(hash)); } } List<Tuple2<byte[], byte[]>> chainedOperators = chainedOperatorHashes.get(streamNodeId); List<OperatorID> chainedOperatorVertexIds = new ArrayList<>(); List<OperatorID> userDefinedChainedOperatorVertexIds = new ArrayList<>(); if (chainedOperators != null) { for (Tuple2<byte[], byte[]> chainedOperator : chainedOperators) { chainedOperatorVertexIds.add(new OperatorID(chainedOperator.f0)); userDefinedChainedOperatorVertexIds.add(chainedOperator.f1 != null ? new OperatorID(chainedOperator.f1) : null); } } if (streamNode.getInputFormat() != null) { jobVertex = new InputFormatVertex( chainedNames.get(streamNodeId), jobVertexId, legacyJobVertexIds, chainedOperatorVertexIds, userDefinedChainedOperatorVertexIds); TaskConfig taskConfig = new TaskConfig(jobVertex.getConfiguration()); taskConfig.setStubWrapper(new UserCodeObjectWrapper<Object>(streamNode.getInputFormat())); } else { jobVertex = new JobVertex( chainedNames.get(streamNodeId), jobVertexId, legacyJobVertexIds, chainedOperatorVertexIds, userDefinedChainedOperatorVertexIds); } jobVertex.setResources(chainedMinResources.get(streamNodeId), chainedPreferredResources.get(streamNodeId)); jobVertex.setInvokableClass(streamNode.getJobVertexClass()); int parallelism = streamNode.getParallelism(); if (parallelism > 0) { jobVertex.setParallelism(parallelism); } else { parallelism = jobVertex.getParallelism(); } jobVertex.setMaxParallelism(streamNode.getMaxParallelism()); if (LOG.isDebugEnabled()) { LOG.debug("Parallelism set: {} for {}", parallelism, streamNodeId); } jobVertices.put(streamNodeId, jobVertex); builtVertices.add(streamNodeId); jobGraph.addVertex(jobVertex); return new StreamConfig(jobVertex.getConfiguration()); } @SuppressWarnings("unchecked") private void setVertexConfig(Integer vertexID, StreamConfig config, List<StreamEdge> chainableOutputs, List<StreamEdge> nonChainableOutputs) { StreamNode vertex = streamGraph.getStreamNode(vertexID); config.setVertexID(vertexID); config.setBufferTimeout(vertex.getBufferTimeout()); config.setTypeSerializerIn1(vertex.getTypeSerializerIn1()); config.setTypeSerializerIn2(vertex.getTypeSerializerIn2()); config.setTypeSerializerOut(vertex.getTypeSerializerOut()); // iterate edges, find sideOutput edges create and save serializers for each outputTag type for (StreamEdge edge : chainableOutputs) { if (edge.getOutputTag() != null) { config.setTypeSerializerSideOut( edge.getOutputTag(), edge.getOutputTag().getTypeInfo().createSerializer(streamGraph.getExecutionConfig()) ); } } for (StreamEdge edge : nonChainableOutputs) { if (edge.getOutputTag() != null) { config.setTypeSerializerSideOut( edge.getOutputTag(), edge.getOutputTag().getTypeInfo().createSerializer(streamGraph.getExecutionConfig()) ); } } config.setStreamOperator(vertex.getOperator()); config.setOutputSelectors(vertex.getOutputSelectors()); config.setNumberOfOutputs(nonChainableOutputs.size()); config.setNonChainedOutputs(nonChainableOutputs); config.setChainedOutputs(chainableOutputs); config.setTimeCharacteristic(streamGraph.getEnvironment().getStreamTimeCharacteristic()); final CheckpointConfig ceckpointCfg = streamGraph.getCheckpointConfig(); config.setStateBackend(streamGraph.getStateBackend()); config.setCheckpointingEnabled(ceckpointCfg.isCheckpointingEnabled()); if (ceckpointCfg.isCheckpointingEnabled()) { config.setCheckpointMode(ceckpointCfg.getCheckpointingMode()); } else { // the "at-least-once" input handler is slightly cheaper (in the absence of checkpoints), // so we use that one if checkpointing is not enabled config.setCheckpointMode(CheckpointingMode.AT_LEAST_ONCE); } config.setStatePartitioner(0, vertex.getStatePartitioner1()); config.setStatePartitioner(1, vertex.getStatePartitioner2()); config.setStateKeySerializer(vertex.getStateKeySerializer()); Class<? extends AbstractInvokable> vertexClass = vertex.getJobVertexClass(); if (vertexClass.equals(StreamIterationHead.class) || vertexClass.equals(StreamIterationTail.class)) { config.setIterationId(streamGraph.getBrokerID(vertexID)); config.setIterationWaitTime(streamGraph.getLoopTimeout(vertexID)); } List<StreamEdge> allOutputs = new ArrayList<StreamEdge>(chainableOutputs); allOutputs.addAll(nonChainableOutputs); vertexConfigs.put(vertexID, config); } private void connect(Integer headOfChain, StreamEdge edge) { physicalEdgesInOrder.add(edge); Integer downStreamvertexID = edge.getTargetId(); JobVertex headVertex = jobVertices.get(headOfChain); JobVertex downStreamVertex = jobVertices.get(downStreamvertexID); StreamConfig downStreamConfig = new StreamConfig(downStreamVertex.getConfiguration()); downStreamConfig.setNumberOfInputs(downStreamConfig.getNumberOfInputs() + 1); StreamPartitioner<?> partitioner = edge.getPartitioner(); JobEdge jobEdge; if (partitioner instanceof ForwardPartitioner || partitioner instanceof RescalePartitioner) { jobEdge = downStreamVertex.connectNewDataSetAsInput( headVertex, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED_BOUNDED); } else { jobEdge = downStreamVertex.connectNewDataSetAsInput( headVertex, DistributionPattern.ALL_TO_ALL, ResultPartitionType.PIPELINED_BOUNDED); } // set strategy name so that web interface can show it. jobEdge.setShipStrategyName(partitioner.toString()); if (LOG.isDebugEnabled()) { LOG.debug("CONNECTED: {} - {} -> {}", partitioner.getClass().getSimpleName(), headOfChain, downStreamvertexID); } } public static boolean isChainable(StreamEdge edge, StreamGraph streamGraph) { StreamNode upStreamVertex = edge.getSourceVertex(); StreamNode downStreamVertex = edge.getTargetVertex(); StreamOperator<?> headOperator = upStreamVertex.getOperator(); StreamOperator<?> outOperator = downStreamVertex.getOperator(); return downStreamVertex.getInEdges().size() == 1 && outOperator != null && headOperator != null && upStreamVertex.isSameSlotSharingGroup(downStreamVertex) && outOperator.getChainingStrategy() == ChainingStrategy.ALWAYS && (headOperator.getChainingStrategy() == ChainingStrategy.HEAD || headOperator.getChainingStrategy() == ChainingStrategy.ALWAYS) && (edge.getPartitioner() instanceof ForwardPartitioner) && upStreamVertex.getParallelism() == downStreamVertex.getParallelism() && streamGraph.isChainingEnabled(); } private void setSlotSharingAndCoLocation() { final HashMap<String, SlotSharingGroup> slotSharingGroups = new HashMap<>(); final HashMap<String, Tuple2<SlotSharingGroup, CoLocationGroup>> coLocationGroups = new HashMap<>(); for (Entry<Integer, JobVertex> entry : jobVertices.entrySet()) { final StreamNode node = streamGraph.getStreamNode(entry.getKey()); final JobVertex vertex = entry.getValue(); // configure slot sharing group final String slotSharingGroupKey = node.getSlotSharingGroup(); final SlotSharingGroup sharingGroup; if (slotSharingGroupKey != null) { sharingGroup = slotSharingGroups.computeIfAbsent( slotSharingGroupKey, (k) -> new SlotSharingGroup()); vertex.setSlotSharingGroup(sharingGroup); } else { sharingGroup = null; } // configure co-location constraint final String coLocationGroupKey = node.getCoLocationGroup(); if (coLocationGroupKey != null) { if (sharingGroup == null) { throw new IllegalStateException("Cannot use a co-location constraint without a slot sharing group"); } Tuple2<SlotSharingGroup, CoLocationGroup> constraint = coLocationGroups.computeIfAbsent( coLocationGroupKey, (k) -> new Tuple2<>(sharingGroup, new CoLocationGroup())); if (constraint.f0 != sharingGroup) { throw new IllegalStateException("Cannot co-locate operators from different slot sharing groups"); } vertex.updateCoLocationGroup(constraint.f1); } } for (Tuple2<StreamNode, StreamNode> pair : streamGraph.getIterationSourceSinkPairs()) { CoLocationGroup ccg = new CoLocationGroup(); JobVertex source = jobVertices.get(pair.f0.getId()); JobVertex sink = jobVertices.get(pair.f1.getId()); ccg.addVertex(source); ccg.addVertex(sink); source.updateCoLocationGroup(ccg); sink.updateCoLocationGroup(ccg); } } private void configureCheckpointing() { CheckpointConfig cfg = streamGraph.getCheckpointConfig(); long interval = cfg.getCheckpointInterval(); if (interval > 0) { ExecutionConfig executionConfig = streamGraph.getExecutionConfig(); // propagate the expected behaviour for checkpoint errors to task. executionConfig.setFailTaskOnCheckpointError(cfg.isFailOnCheckpointingErrors()); } else { // interval of max value means disable periodic checkpoint interval = Long.MAX_VALUE; } // --- configure the participating vertices --- // collect the vertices that receive "trigger checkpoint" messages. // currently, these are all the sources List<JobVertexID> triggerVertices = new ArrayList<>(); // collect the vertices that need to acknowledge the checkpoint // currently, these are all vertices List<JobVertexID> ackVertices = new ArrayList<>(jobVertices.size()); // collect the vertices that receive "commit checkpoint" messages // currently, these are all vertices List<JobVertexID> commitVertices = new ArrayList<>(jobVertices.size()); for (JobVertex vertex : jobVertices.values()) { if (vertex.isInputVertex()) { triggerVertices.add(vertex.getID()); } commitVertices.add(vertex.getID()); ackVertices.add(vertex.getID()); } // --- configure options --- CheckpointRetentionPolicy retentionAfterTermination; if (cfg.isExternalizedCheckpointsEnabled()) { CheckpointConfig.ExternalizedCheckpointCleanup cleanup = cfg.getExternalizedCheckpointCleanup(); // Sanity check if (cleanup == null) { throw new IllegalStateException("Externalized checkpoints enabled, but no cleanup mode configured."); } retentionAfterTermination = cleanup.deleteOnCancellation() ? CheckpointRetentionPolicy.RETAIN_ON_FAILURE : CheckpointRetentionPolicy.RETAIN_ON_CANCELLATION; } else { retentionAfterTermination = CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION; } CheckpointingMode mode = cfg.getCheckpointingMode(); boolean isExactlyOnce; if (mode == CheckpointingMode.EXACTLY_ONCE) { isExactlyOnce = true; } else if (mode == CheckpointingMode.AT_LEAST_ONCE) { isExactlyOnce = false; } else { throw new IllegalStateException("Unexpected checkpointing mode. " + "Did not expect there to be another checkpointing mode besides " + "exactly-once or at-least-once."); } // --- configure the master-side checkpoint hooks --- final ArrayList<MasterTriggerRestoreHook.Factory> hooks = new ArrayList<>(); for (StreamNode node : streamGraph.getStreamNodes()) { StreamOperator<?> op = node.getOperator(); if (op instanceof AbstractUdfStreamOperator) { Function f = ((AbstractUdfStreamOperator<?, ?>) op).getUserFunction(); if (f instanceof WithMasterCheckpointHook) { hooks.add(new FunctionMasterCheckpointHookFactory((WithMasterCheckpointHook<?>) f)); } } } // because the hooks can have user-defined code, they need to be stored as // eagerly serialized values final SerializedValue<MasterTriggerRestoreHook.Factory[]> serializedHooks; if (hooks.isEmpty()) { serializedHooks = null; } else { try { MasterTriggerRestoreHook.Factory[] asArray = hooks.toArray(new MasterTriggerRestoreHook.Factory[hooks.size()]); serializedHooks = new SerializedValue<>(asArray); } catch (IOException e) { throw new FlinkRuntimeException("Trigger/restore hook is not serializable", e); } } // because the state backend can have user-defined code, it needs to be stored as // eagerly serialized value final SerializedValue<StateBackend> serializedStateBackend; if (streamGraph.getStateBackend() == null) { serializedStateBackend = null; } else { try { serializedStateBackend = new SerializedValue<StateBackend>(streamGraph.getStateBackend()); } catch (IOException e) { throw new FlinkRuntimeException("State backend is not serializable", e); } } // --- done, put it all together --- JobCheckpointingSettings settings = new JobCheckpointingSettings( triggerVertices, ackVertices, commitVertices, new CheckpointCoordinatorConfiguration( interval, cfg.getCheckpointTimeout(), cfg.getMinPauseBetweenCheckpoints(), cfg.getMaxConcurrentCheckpoints(), retentionAfterTermination, isExactlyOnce), serializedStateBackend, serializedHooks); jobGraph.setSnapshotSettings(settings); } }
zhangminglei/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/graph/StreamingJobGraphGenerator.java
Java
apache-2.0
26,465
package org.hl7.fhir.instance.model.valuesets; /* Copyright (c) 2011+, HL7, Inc. 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 HL7 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Sat, Aug 22, 2015 23:00-0400 for FHIR v0.5.0 import org.hl7.fhir.instance.model.EnumFactory; public class V3LocalRemoteControlStateEnumFactory implements EnumFactory<V3LocalRemoteControlState> { public V3LocalRemoteControlState fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) return null; if ("L".equals(codeString)) return V3LocalRemoteControlState.L; if ("R".equals(codeString)) return V3LocalRemoteControlState.R; throw new IllegalArgumentException("Unknown V3LocalRemoteControlState code '"+codeString+"'"); } public String toCode(V3LocalRemoteControlState code) { if (code == V3LocalRemoteControlState.L) return "L"; if (code == V3LocalRemoteControlState.R) return "R"; return "?"; } }
Nodstuff/hapi-fhir
hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/instance/model/valuesets/V3LocalRemoteControlStateEnumFactory.java
Java
apache-2.0
2,503
package com.coolweather.android; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.coolweather.android.gson.Forecast; import com.coolweather.android.gson.Weather; //import com.coolweather.android.service.AutoUpdateService; import com.coolweather.android.service.AutoUpdateService; import com.coolweather.android.util.HttpUtil; import com.coolweather.android.util.Utility; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by Administrator on 2017/7/2. */ public class WeatherActivity extends AppCompatActivity { public DrawerLayout drawerLayout; public SwipeRefreshLayout swipeRefresh; private ScrollView weatherLayout; private Button navButton; private TextView titleCity; private TextView titleUpdateTime; private TextView degreeText; private TextView weatherInfoText; private LinearLayout forecastLayout; private TextView aqiText; private TextView pm25Text; private TextView comfortText; private TextView carWashText; private TextView sportText; private ImageView bingPicImg; private String mWeatherId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= 21) { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); getWindow().setStatusBarColor(Color.TRANSPARENT); } setContentView(R.layout.activity_weather); // 初始化各控件 bingPicImg = (ImageView) findViewById(R.id.bing_pic_img); weatherLayout = (ScrollView) findViewById(R.id.weather_layout); titleCity = (TextView) findViewById(R.id.title_city); titleUpdateTime = (TextView) findViewById(R.id.title_update_time); degreeText = (TextView) findViewById(R.id.degree_text); weatherInfoText = (TextView) findViewById(R.id.weather_info_text); forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout); aqiText = (TextView) findViewById(R.id.aqi_text); pm25Text = (TextView) findViewById(R.id.pm25_text); comfortText = (TextView) findViewById(R.id.comfort_text); carWashText = (TextView) findViewById(R.id.car_wash_text); sportText = (TextView) findViewById(R.id.sport_text); swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh); swipeRefresh.setColorSchemeResources(R.color.colorPrimary); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); navButton = (Button) findViewById(R.id.nav_button); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String weatherString = prefs.getString("weather", null); if (weatherString != null) { // 有缓存时直接解析天气数据 Weather weather = Utility.handleWeatherResponse(weatherString); mWeatherId = weather.basic.weatherId; showWeatherInfo(weather); } else { // 无缓存时去服务器查询天气 mWeatherId = getIntent().getStringExtra("weather_id"); weatherLayout.setVisibility(View.INVISIBLE); requestWeather(mWeatherId); } swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { requestWeather(mWeatherId); } }); navButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawerLayout.openDrawer(GravityCompat.START); } }); String bingPic = prefs.getString("bing_pic", null); if (bingPic != null) { Glide.with(this).load(bingPic).into(bingPicImg); } else { loadBingPic(); } } /** * 根据天气id请求城市天气信息。 */ public void requestWeather(final String weatherId) { String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=bc0418b57b2d4918819d3974ac1285d9"; HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { final String responseText = response.body().string(); final Weather weather = Utility.handleWeatherResponse(responseText); runOnUiThread(new Runnable() { @Override public void run() { if (weather != null && "ok".equals(weather.status)) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit(); editor.putString("weather", responseText); editor.apply(); mWeatherId = weather.basic.weatherId; showWeatherInfo(weather); } else { Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show(); } swipeRefresh.setRefreshing(false); } }); } @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show(); swipeRefresh.setRefreshing(false); } }); } }); loadBingPic(); } /** * 加载必应每日一图 */ private void loadBingPic() { String requestBingPic = "http://guolin.tech/api/bing_pic"; HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { final String bingPic = response.body().string(); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit(); editor.putString("bing_pic", bingPic); editor.apply(); runOnUiThread(new Runnable() { @Override public void run() { Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg); } }); } @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } }); } /** * 处理并展示Weather实体类中的数据。 */ private void showWeatherInfo(Weather weather) { String cityName = weather.basic.cityName; String updateTime = weather.basic.update.updateTime.split(" ")[1]; String degree = weather.now.temperature + "℃"; String weatherInfo = weather.now.more.info; titleCity.setText(cityName); titleUpdateTime.setText(updateTime); degreeText.setText(degree); weatherInfoText.setText(weatherInfo); forecastLayout.removeAllViews(); for (Forecast forecast : weather.forecastList) { View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false); TextView dateText = (TextView) view.findViewById(R.id.date_text); TextView infoText = (TextView) view.findViewById(R.id.info_text); TextView maxText = (TextView) view.findViewById(R.id.max_text); TextView minText = (TextView) view.findViewById(R.id.min_text); dateText.setText(forecast.date); infoText.setText(forecast.more.info); maxText.setText(forecast.temperature.max); minText.setText(forecast.temperature.min); forecastLayout.addView(view); } if (weather.aqi != null) { aqiText.setText(weather.aqi.city.aqi); pm25Text.setText(weather.aqi.city.pm25); } String comfort = "舒适度:" + weather.suggestion.comfort.info; String carWash = "洗车指数:" + weather.suggestion.carWash.info; String sport = "运行建议:" + weather.suggestion.sport.info; comfortText.setText(comfort); carWashText.setText(carWash); sportText.setText(sport); weatherLayout.setVisibility(View.VISIBLE); Intent intent = new Intent(this, AutoUpdateService.class); startService(intent); } }
longlongqi/smartweather
app/src/main/java/com/coolweather/android/WeatherActivity.java
Java
apache-2.0
9,587
/* * Copyright 2014-2015 Quantiply Corporation. 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.quantiply.samza.serde; import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient; import org.apache.avro.Schema; import org.apache.samza.serializers.Serde; import io.confluent.kafka.serializers.KafkaAvroDecoder; import io.confluent.kafka.serializers.KafkaAvroEncoder; import kafka.utils.VerifiableProperties; public class AvroSerde implements Serde<Object> { private final KafkaAvroEncoder encoder; private final KafkaAvroDecoder decoder; public AvroSerde(VerifiableProperties encoderProps, VerifiableProperties decoderProps) { encoder = new KafkaAvroEncoder(encoderProps); decoder = new KafkaAvroDecoder(decoderProps); } /** * For unit testing */ public AvroSerde(SchemaRegistryClient srClient, VerifiableProperties decoderProps) { encoder = new KafkaAvroEncoder(srClient); decoder = new KafkaAvroDecoder(srClient, decoderProps); } @Override public Object fromBytes(byte[] bytes) { return decoder.fromBytes(bytes); } public Object fromBytes(byte[] bytes, Schema readerSchema) { return decoder.fromBytes(bytes, readerSchema); } @Override public byte[] toBytes(Object msg) { return encoder.toBytes(msg); } }
Quantiply/rico
avro/src/main/java/com/quantiply/samza/serde/AvroSerde.java
Java
apache-2.0
1,883
package com.nvim.cache.biz; import java.util.List; import java.util.Queue; import android.content.Context; import com.nvim.cache.CacheModel; import com.nvim.cache.ContactCacheImpl; import com.nvim.cache.MessageCacheImpl; import com.nvim.db.ContactModel; import com.nvim.db.UserModel; import com.nvim.entity.MessageInfo; import com.nvim.entity.User; import com.nvim.lib.utils.IMUIHelper; import com.nvim.lib.utils.IMUIHelper.SessionInfo; import com.nvim.log.Logger; public class CacheHub { private static CacheHub instance; public static CacheHub getInstance() { if (null == instance) { instance = new CacheHub(); } return instance; } private SessionInfo sessionInfo; private Logger logger = Logger.getLogger(CacheHub.class); /** * @author shuchen */ private CacheHub() { } /** * 清除所有缓存 */ public void clear() { CacheModel.getInstance().clear(); } public void setSessionInfo(IMUIHelper.SessionInfo sessionIfo) { this.sessionInfo = sessionIfo; logger.d("chat#setSessionInfo sessionInfo:%s", sessionIfo); } public SessionInfo getSessionInfo() { return sessionInfo; } /* * 设置用户信息 * * @param user 用户信息 */ public void setUser(User user, Context context) { CacheModel.getInstance().setUser(user); if (null != context) { new UserModel(context).add(user); } } /* * 获得用户信息 * * @param userId 用户ID */ public User getUser(String userId, Context context) { User user = CacheModel.getInstance().getUser(userId); if (null == user && null != context) { user = new UserModel(context).query(userId); CacheModel.getInstance().setUser(user); } return user; } /* * 设置当前登入用户 * * @param user 用户信息 */ public void setLoginUser(User user) { CacheModel.setLoginUser(user); return; } /* * 获得当前登入用户 */ public User getLoginUser() { return CacheModel.getLoginUser(); } /* * 获得当前登入用户Id */ public String getLoginUserId() { return CacheModel.getLoginUserId(); } /* * 设置当前聊天对象ID * * @param userId 聊天对象用户ID */ public void setChatUserId(String userId) { CacheModel.getInstance().setChatUserId(userId); return; } /* * 获得当前聊天对象用户ID */ public String getChatUserId() { return CacheModel.getInstance().getChatUserId(); } /* * 设置当前聊天对象 * * @param user 用户信息 */ public void setChatUser(User user) { CacheModel.getInstance().setChatUser(user); return; } /* * 清空当前聊天对象并设置前一回聊天对象 * * @param user 用户信息 */ public void clearChatUser() { CacheModel.getInstance().clearChatUser(); return; } /* * 获得当前聊天对象 */ public User getChatUser() { return CacheModel.getInstance().getChatUser(); // 参数判空放在下一层 } /* * 获得前一回聊天对象 */ // public User getLastChatUser() { // return CacheModel.getInstance().getLastChatUser(); // 参数判空放在下一层 // } /* * 清空前一回聊天对象 */ // public void clearLastChatUser() { // CacheModel.getInstance().clearLastChatUser(); // return; // 参数判空放在下一层 // } /* * 获得与好友聊天的最后一条信息 * * @param userId 用户ID */ public MessageInfo getLastMessage(String friendUserId) { return CacheModel.getInstance().getLastMessage(friendUserId); } /* * 推送一条新消息到DB并更新最后一条消息 */ public int obtainMsgId() { return CacheModel.getInstance().obtainMsgId(); } /* * 推送一条新消息到DB并更新最后一条消息 */ public boolean pushMsg(MessageInfo msgInfo) { return CacheModel.getInstance().push(msgInfo); } /** * 从数据库拉取信息两个用户之间部分信息(由偏移量和信息条数决定) * * @param userId * 用户ID * @param friendUserId * 好友ID * @param msgId * 起始ID * @param offset * 距离起始ID的偏移量 * @param size * 拉取的消息条数 * @return MessageInfo */ public List<MessageInfo> pullMsg(String userId, String friendUserId, int msgId, int offset, int size) { return CacheModel.getInstance().pullMsg(userId, friendUserId, msgId, offset, size); } public List<String> getFriendIdList(String ownerId, Context context) { List<String> idList = CacheModel.getInstance().getFriendIdList(); if (idList.size() < 1 && null != context) { idList = new ContactModel(context).queryFriendsIdList(ownerId); CacheModel.getInstance().setFriendIdList(idList); } return idList; } public boolean setLoadedFriendId(String friendId) { return CacheModel.getInstance().setLoadedFriendId(friendId); } public boolean isLoadedFriendId(String friendId) { return CacheModel.getInstance().isLoadedFriendId(friendId); } /* * 清空某个用户未读消息计数 * * @param userId 用户ID */ public int clearUnreadCount(String userId) { return MessageCacheImpl.getInstance().clearUnreadCount(userId); } /* * 获得用户未读消息计数 * * @param userId 用户ID */ public int getUnreadCount(String userId) { return MessageCacheImpl.getInstance().getUnreadCount(userId); } /* * 获得用户未读消息计数 * * @param userId 用户ID */ public int getUnreadCount() { return MessageCacheImpl.getUnreadCount(); } /* * 添加一条最近联系人 * * @param userId 最近联系人 * * @return void */ public void addFriendId(String userId) { ContactCacheImpl.getInstance().addFriendId(userId); } public void addFriendList(Queue<String> list) { ContactCacheImpl.getInstance().addFriendList(list); } /* * 根据消息ID更新DB中消息的加载状态 */ public Boolean updateMsgStatus(String msgId, int state) { // return CacheModel.getInstance().updateMsgStatus(msgId, state); return false; } /* * 更新两个用户之间的所有消息的加载状态 */ public Boolean updateMsgStatus(String userId, String friendUserId, int state) { return CacheModel.getInstance().updateMsgStatus(userId, friendUserId, state); } /* * 根据消息ID更新DB中消息的是否已读或展现状态 */ public Boolean updateMsgReadStatus(int msgId, int state) { return CacheModel.getInstance().updateMsgReadStatus(msgId, state); } /* * 更新消息ID,主要针对图文混排的消息 */ public Boolean updateMsgParentId(int msgId, int msgParentId) { return CacheModel.getInstance().updateMsgParentId(msgId, msgParentId); } /* * 更新两个用户之间的所有消息是否已读或展现状态 */ public Boolean updateMsgReadStatus(String userId, String friendUserId, int state) { return CacheModel.getInstance().updateMsgReadStatus(userId, friendUserId, state); } /** * 更改图片存储路径 * * @param entityId * @param friendUserId * @return Boolean */ public Boolean updateMsgImageSavePath(String MsgId, String newPath) { return CacheModel.getInstance().updateMsgImageSavePath(MsgId, newPath); } /* * 初次打开时检查DB中消息是否达到上限,若达到则删除最老的部分信息 * * @return 返回删除消息的时间分隔线 */ public int checkAndDeleteIfNeed() { // 如果需要的话,删除最老的部分历史信息 return CacheModel.getInstance().checkAndDeleteIfNeed(); } }
NvIM/NvIM-Android
src/com/nvim/cache/biz/CacheHub.java
Java
apache-2.0
7,464
/* * Copyright 2014 Matteo Giaccone and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package restelio.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Target; /** * Mark a method to respond to a DELETE HTTP method * @author Matteo Giaccone */ @Documented @Inherited @Target(ElementType.METHOD) public @interface DELETE { String value(); }
mgiaccone/restelio
restelio-core/src/main/java/restelio/annotation/DELETE.java
Java
apache-2.0
991
package com.bplow.deep.base; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.junit.Test; import redis.clients.jedis.Jedis; public class JedisClientTest { @Test public void cashceTest() throws IOException{ InputStream in = this.getClass().getResourceAsStream("/log4j.xml"); String xml = IOUtils.toString(in); for(int i =0 ;i < 100000;i++){ Jedis jedis = new Jedis("192.168.89.80"); jedis.get("foo"+i); } } }
ahwxl/deep
src/test/java/com/bplow/deep/base/JedisClientTest.java
Java
apache-2.0
595
/* * Copyright © 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.enterprise.cloudsearch.sdk.indexing.template; import com.google.api.client.json.GenericJson; import com.google.common.collect.Iterators; import com.google.enterprise.cloudsearch.sdk.CloseableIterableOnce; import com.google.enterprise.cloudsearch.sdk.indexing.IndexingService; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.function.Consumer; /** * Container for a sequence of {@link ApiOperation} objects. * * <p>The {@link Repository} can return this object to perform multiple operations when required by * the connector. This object calls the {@link IndexingService} object for each of its contained * operations. * * <p>For example, if a {@link Repository#getDoc(com.google.api.services.cloudsearch.v1.model.Item)} * method call determines that the requested document has some of its child documents missing from * the data repository. A delete operation for each of these children can be concurrently sent in a * batch operation along with the requested document's update operation. * * <p><strong>This class implements {@code Iterable}, but the {@code iterator} and {@code equals} * methods both exhaust the iterator and should only be used by tests.</strong> */ public class BatchApiOperation implements ApiOperation, Iterable<ApiOperation> { private final CloseableIterableOnce<ApiOperation> operations; BatchApiOperation(Iterator<ApiOperation> operations) { this.operations = new CloseableIterableOnce<>(operations); } @Override public List<GenericJson> execute(IndexingService service) throws IOException, InterruptedException { return execute(service, Optional.empty()); } @Override public List<GenericJson> execute(IndexingService service, Optional<Consumer<ApiOperation>> operationModifier) throws IOException, InterruptedException { List<GenericJson> res = new ArrayList<>(); for (ApiOperation operation : operations) { res.addAll(operation.execute(service, operationModifier)); } return res; } /** * Gets an iterator over the {@code ApiOperation}s. This implementation exhausts the * iterator, and should only be used by tests. * * @return an iterator on the first call * @throws IllegalStateException if this method has been called on this instance before */ @Override public Iterator<ApiOperation> iterator() { return operations.iterator(); } /** * Indicates whether another object is also a {@code BatchApiOperation} and iterates * over the same objects. This implementation exhausts the iterators of both objects, * and should only be used by tests. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BatchApiOperation)) { return false; } BatchApiOperation other = (BatchApiOperation) o; return Iterators.elementsEqual(this.iterator(), other.iterator()); } /** * Gets a hash code for this object. This implementation always returns the same value, * in order to remain consistent with {@link #equals} without exhausting the iterator. * * @return a fixed hash code */ @Override public int hashCode() { return 13; } }
google-cloudsearch/connector-sdk
indexing/src/main/java/com/google/enterprise/cloudsearch/sdk/indexing/template/BatchApiOperation.java
Java
apache-2.0
3,904
package com.stupid.method.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * * @调用顺序 <br> * * 1. {@link #setInflater(LayoutInflater)}<br> * 2. {@link #getLayoutId()}<br> * 3. {@link #onCreate(XAdapter, android.content.Context)}<br> * 4. 如果已实例化该类,会先调用onDestiny();<br> * 5. {@link #getView(Object, int)}<br> * ----------- <br> * 6. {@link #onResetView(Object, int)} <br> * [1,2,3] 只执行一遍<br> * [4,5,6]会重复执行 * * **/ public interface IXViewHolder<T> { int getLayoutId(); /** * @return */ View getView(); /** * @param data * @param position * @param onScrolling * @return */ View getView(T data, int position, boolean onScrolling); /** * @param context */ void onCreate(Context context); /** * @param nextPosition * @param count */ void onDestory(int nextPosition, int count); /** * 当前容器的数据长度 * * @param size */ void setListSize(int size); /** * @param inflater * @param parent * @return */ View setInflater(LayoutInflater inflater, ViewGroup parent); /** * @param itemListener */ void setOnClickItemListener(OnClickItemListener itemListener); /** * @param longClickItemListener */ void setOnLongClickItemListener( OnLongClickItemListener longClickItemListener); }
comcp/android-Stupid-Adapter
StupidAdapter/src/com/stupid/method/adapter/IXViewHolder.java
Java
apache-2.0
1,413
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.catalog; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import static org.apache.camel.catalog.CatalogHelper.after; import static org.apache.camel.catalog.JSonSchemaHelper.getNames; import static org.apache.camel.catalog.JSonSchemaHelper.getPropertyDefaultValue; import static org.apache.camel.catalog.JSonSchemaHelper.getPropertyEnum; import static org.apache.camel.catalog.JSonSchemaHelper.getPropertyKind; import static org.apache.camel.catalog.JSonSchemaHelper.getPropertyNameFromNameWithPrefix; import static org.apache.camel.catalog.JSonSchemaHelper.getPropertyPrefix; import static org.apache.camel.catalog.JSonSchemaHelper.getRow; import static org.apache.camel.catalog.JSonSchemaHelper.isComponentLenientProperties; import static org.apache.camel.catalog.JSonSchemaHelper.isPropertyBoolean; import static org.apache.camel.catalog.JSonSchemaHelper.isPropertyInteger; import static org.apache.camel.catalog.JSonSchemaHelper.isPropertyMultiValue; import static org.apache.camel.catalog.JSonSchemaHelper.isPropertyNumber; import static org.apache.camel.catalog.JSonSchemaHelper.isPropertyObject; import static org.apache.camel.catalog.JSonSchemaHelper.isPropertyRequired; import static org.apache.camel.catalog.JSonSchemaHelper.stripOptionalPrefixFromName; import static org.apache.camel.catalog.URISupport.createQueryString; import static org.apache.camel.catalog.URISupport.isEmpty; import static org.apache.camel.catalog.URISupport.normalizeUri; import static org.apache.camel.catalog.URISupport.stripQuery; /** * Default {@link CamelCatalog}. */ public class DefaultCamelCatalog implements CamelCatalog { private static final String MODELS_CATALOG = "org/apache/camel/catalog/models.properties"; private static final String COMPONENTS_CATALOG = "org/apache/camel/catalog/components.properties"; private static final String DATA_FORMATS_CATALOG = "org/apache/camel/catalog/dataformats.properties"; private static final String LANGUAGE_CATALOG = "org/apache/camel/catalog/languages.properties"; private static final String MODEL_JSON = "org/apache/camel/catalog/models"; private static final String COMPONENTS_JSON = "org/apache/camel/catalog/components"; private static final String DATA_FORMATS_JSON = "org/apache/camel/catalog/dataformats"; private static final String LANGUAGE_JSON = "org/apache/camel/catalog/languages"; private static final String ARCHETYPES_CATALOG = "org/apache/camel/catalog/archetypes/archetype-catalog.xml"; private static final String SCHEMAS_XML = "org/apache/camel/catalog/schemas"; private static final Pattern SYNTAX_PATTERN = Pattern.compile("(\\w+)"); private final VersionHelper version = new VersionHelper(); // 3rd party components/data-formats private final Map<String, String> extraComponents = new HashMap<String, String>(); private final Map<String, String> extraDataFormats = new HashMap<String, String>(); // cache of operation -> result private final Map<String, Object> cache = new HashMap<String, Object>(); private boolean caching; private SuggestionStrategy suggestionStrategy; /** * Creates the {@link CamelCatalog} without caching enabled. */ public DefaultCamelCatalog() { } /** * Creates the {@link CamelCatalog} * * @param caching whether to use cache */ public DefaultCamelCatalog(boolean caching) { this.caching = caching; } @Override public void enableCache() { caching = true; } @Override public void setSuggestionStrategy(SuggestionStrategy suggestionStrategy) { this.suggestionStrategy = suggestionStrategy; } @Override public void addComponent(String name, String className) { extraComponents.put(name, className); // invalidate the cache cache.remove("findComponentNames"); cache.remove("findComponentLabels"); cache.remove("listComponentsAsJson"); } @Override public void addDataFormat(String name, String className) { extraDataFormats.put(name, className); // invalidate the cache cache.remove("findDataFormatNames"); cache.remove("findDataFormatLabels"); cache.remove("listDataFormatsAsJson"); } @Override public String getCatalogVersion() { return version.getVersion(); } @Override @SuppressWarnings("unchecked") public List<String> findComponentNames() { List<String> names = null; if (caching) { names = (List<String>) cache.get("findComponentNames"); } if (names == null) { names = new ArrayList<String>(); InputStream is = DefaultCamelCatalog.class.getClassLoader().getResourceAsStream(COMPONENTS_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } // include third party components for (Map.Entry<String, String> entry : extraComponents.entrySet()) { names.add(entry.getKey()); } // sort the names Collections.sort(names); if (caching) { cache.put("findComponentNames", names); } } return names; } @Override @SuppressWarnings("unchecked") public List<String> findDataFormatNames() { List<String> names = null; if (caching) { names = (List<String>) cache.get("findDataFormatNames"); } if (names == null) { names = new ArrayList<String>(); InputStream is = DefaultCamelCatalog.class.getClassLoader().getResourceAsStream(DATA_FORMATS_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } // include third party data formats for (Map.Entry<String, String> entry : extraDataFormats.entrySet()) { names.add(entry.getKey()); } // sort the names Collections.sort(names); if (caching) { cache.put("findDataFormatNames", names); } } return names; } @Override @SuppressWarnings("unchecked") public List<String> findLanguageNames() { List<String> names = null; if (caching) { names = (List<String>) cache.get("findLanguageNames"); } if (names == null) { names = new ArrayList<String>(); InputStream is = DefaultCamelCatalog.class.getClassLoader().getResourceAsStream(LANGUAGE_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } if (caching) { cache.put("findLanguageNames", names); } } return names; } @Override @SuppressWarnings("unchecked") public List<String> findModelNames() { List<String> names = null; if (caching) { names = (List<String>) cache.get("findModelNames"); } if (names == null) { names = new ArrayList<String>(); InputStream is = DefaultCamelCatalog.class.getClassLoader().getResourceAsStream(MODELS_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } if (caching) { cache.put("findModelNames", names); } } return names; } @Override public List<String> findModelNames(String filter) { // should not cache when filter parameter can by any kind of value List<String> answer = new ArrayList<String>(); List<String> names = findModelNames(); for (String name : names) { String json = modelJSonSchema(name); if (json != null) { List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("model", json, false); for (Map<String, String> row : rows) { if (row.containsKey("label")) { String label = row.get("label"); String[] parts = label.split(","); for (String part : parts) { try { if (part.equalsIgnoreCase(filter) || CatalogHelper.matchWildcard(part, filter) || part.matches(filter)) { answer.add(name); } } catch (PatternSyntaxException e) { // ignore as filter is maybe not a pattern } } } } } } return answer; } @Override public List<String> findComponentNames(String filter) { // should not cache when filter parameter can by any kind of value List<String> answer = new ArrayList<String>(); List<String> names = findComponentNames(); for (String name : names) { String json = componentJSonSchema(name); if (json != null) { List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("component", json, false); for (Map<String, String> row : rows) { if (row.containsKey("label")) { String label = row.get("label"); String[] parts = label.split(","); for (String part : parts) { try { if (part.equalsIgnoreCase(filter) || CatalogHelper.matchWildcard(part, filter) || part.matches(filter)) { answer.add(name); } } catch (PatternSyntaxException e) { // ignore as filter is maybe not a pattern } } } } } } return answer; } @Override public List<String> findDataFormatNames(String filter) { // should not cache when filter parameter can by any kind of value List<String> answer = new ArrayList<String>(); List<String> names = findDataFormatNames(); for (String name : names) { String json = dataFormatJSonSchema(name); if (json != null) { List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("dataformat", json, false); for (Map<String, String> row : rows) { if (row.containsKey("label")) { String label = row.get("label"); String[] parts = label.split(","); for (String part : parts) { try { if (part.equalsIgnoreCase(filter) || CatalogHelper.matchWildcard(part, filter) || part.matches(filter)) { answer.add(name); } } catch (PatternSyntaxException e) { // ignore as filter is maybe not a pattern } } } } } } return answer; } @Override public List<String> findLanguageNames(String filter) { // should not cache when filter parameter can by any kind of value List<String> answer = new ArrayList<String>(); List<String> names = findLanguageNames(); for (String name : names) { String json = languageJSonSchema(name); if (json != null) { List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("language", json, false); for (Map<String, String> row : rows) { if (row.containsKey("label")) { String label = row.get("label"); String[] parts = label.split(","); for (String part : parts) { try { if (part.equalsIgnoreCase(filter) || CatalogHelper.matchWildcard(part, filter) || part.matches(filter)) { answer.add(name); } } catch (PatternSyntaxException e) { // ignore as filter is maybe not a pattern } } } } } } return answer; } @Override public String modelJSonSchema(String name) { String file = MODEL_JSON + "/" + name + ".json"; String answer = null; if (caching) { answer = (String) cache.get("model-" + file); } if (answer == null) { InputStream is = DefaultCamelCatalog.class.getClassLoader().getResourceAsStream(file); if (is != null) { try { answer = CatalogHelper.loadText(is); } catch (IOException e) { // ignore } } if (caching) { cache.put("model-" + file, answer); } } return answer; } @Override public String componentJSonSchema(String name) { String file = COMPONENTS_JSON + "/" + name + ".json"; String answer = null; if (caching) { answer = (String) cache.get("component-" + file); } if (answer == null) { InputStream is = DefaultCamelCatalog.class.getClassLoader().getResourceAsStream(file); if (is != null) { try { answer = CatalogHelper.loadText(is); } catch (IOException e) { // ignore } } else { // its maybe a third party so try load it String className = extraComponents.get(name); if (className != null) { String packageName = className.substring(0, className.lastIndexOf('.')); packageName = packageName.replace('.', '/'); String path = packageName + "/" + name + ".json"; is = DefaultCamelCatalog.class.getClassLoader().getResourceAsStream(path); if (is != null) { try { answer = CatalogHelper.loadText(is); } catch (IOException e) { // ignore } } } } if (caching) { cache.put("component-" + file, answer); } } return answer; } @Override public String dataFormatJSonSchema(String name) { String file = DATA_FORMATS_JSON + "/" + name + ".json"; String answer = null; if (caching) { answer = (String) cache.get("dataformat-" + file); } if (answer == null) { InputStream is = DefaultCamelCatalog.class.getClassLoader().getResourceAsStream(file); if (is != null) { try { answer = CatalogHelper.loadText(is); } catch (IOException e) { // ignore } } else { // its maybe a third party so try load it String className = extraDataFormats.get(name); if (className != null) { String packageName = className.substring(0, className.lastIndexOf('.')); packageName = packageName.replace('.', '/'); String path = packageName + "/" + name + ".json"; is = DefaultCamelCatalog.class.getClassLoader().getResourceAsStream(path); if (is != null) { try { answer = CatalogHelper.loadText(is); } catch (IOException e) { // ignore } } } } if (caching) { cache.put("dataformat-" + file, answer); } } return answer; } @Override public String languageJSonSchema(String name) { String file = LANGUAGE_JSON + "/" + name + ".json"; String answer = null; if (caching) { answer = (String) cache.get("language-" + file); } if (answer == null) { InputStream is = DefaultCamelCatalog.class.getClassLoader().getResourceAsStream(file); if (is != null) { try { answer = CatalogHelper.loadText(is); } catch (IOException e) { // ignore } } if (caching) { cache.put("language-" + file, answer); } } return answer; } @Override @SuppressWarnings("unchecked") public Set<String> findModelLabels() { SortedSet<String> answer = null; if (caching) { answer = (TreeSet<String>) cache.get("findModelLabels"); } if (answer == null) { answer = new TreeSet<String>(); List<String> names = findModelNames(); for (String name : names) { String json = modelJSonSchema(name); if (json != null) { List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("model", json, false); for (Map<String, String> row : rows) { if (row.containsKey("label")) { String label = row.get("label"); String[] parts = label.split(","); for (String part : parts) { answer.add(part); } } } } } if (caching) { cache.put("findModelLabels", answer); } } return answer; } @Override @SuppressWarnings("unchecked") public Set<String> findComponentLabels() { SortedSet<String> answer = null; if (caching) { answer = (TreeSet<String>) cache.get("findComponentLabels"); } if (answer == null) { answer = new TreeSet<String>(); List<String> names = findComponentNames(); for (String name : names) { String json = componentJSonSchema(name); if (json != null) { List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("component", json, false); for (Map<String, String> row : rows) { if (row.containsKey("label")) { String label = row.get("label"); String[] parts = label.split(","); for (String part : parts) { answer.add(part); } } } } } if (caching) { cache.put("findComponentLabels", answer); } } return answer; } @Override @SuppressWarnings("unchecked") public Set<String> findDataFormatLabels() { SortedSet<String> answer = null; if (caching) { answer = (TreeSet<String>) cache.get("findDataFormatLabels"); } if (answer == null) { answer = new TreeSet<String>(); List<String> names = findDataFormatNames(); for (String name : names) { String json = dataFormatJSonSchema(name); if (json != null) { List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("dataformat", json, false); for (Map<String, String> row : rows) { if (row.containsKey("label")) { String label = row.get("label"); String[] parts = label.split(","); for (String part : parts) { answer.add(part); } } } } } if (caching) { cache.put("findDataFormatLabels", answer); } } return answer; } @Override @SuppressWarnings("unchecked") public Set<String> findLanguageLabels() { SortedSet<String> answer = null; if (caching) { answer = (TreeSet<String>) cache.get("findLanguageLabels"); } if (answer == null) { answer = new TreeSet<String>(); List<String> names = findLanguageNames(); for (String name : names) { String json = languageJSonSchema(name); if (json != null) { List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("language", json, false); for (Map<String, String> row : rows) { if (row.containsKey("label")) { String label = row.get("label"); String[] parts = label.split(","); for (String part : parts) { answer.add(part); } } } } } if (caching) { cache.put("findLanguageLabels", answer); } } return answer; } @Override public String archetypeCatalogAsXml() { String file = ARCHETYPES_CATALOG; String answer = null; if (caching) { answer = (String) cache.get(file); } if (answer == null) { InputStream is = DefaultCamelCatalog.class.getClassLoader().getResourceAsStream(file); if (is != null) { try { answer = CatalogHelper.loadText(is); } catch (IOException e) { // ignore } } if (caching) { cache.put(file, answer); } } return answer; } @Override public String springSchemaAsXml() { String file = SCHEMAS_XML + "/camel-spring.xsd"; String answer = null; if (caching) { answer = (String) cache.get(file); } if (answer == null) { InputStream is = DefaultCamelCatalog.class.getClassLoader().getResourceAsStream(file); if (is != null) { try { answer = CatalogHelper.loadText(is); } catch (IOException e) { // ignore } } if (caching) { cache.put(file, answer); } } return answer; } @Override public String blueprintSchemaAsXml() { String file = SCHEMAS_XML + "/camel-blueprint.xsd"; String answer = null; if (caching) { answer = (String) cache.get(file); } if (answer == null) { InputStream is = DefaultCamelCatalog.class.getClassLoader().getResourceAsStream(file); if (is != null) { try { answer = CatalogHelper.loadText(is); } catch (IOException e) { // ignore } } if (caching) { cache.put(file, answer); } } return answer; } @Override public EndpointValidationResult validateEndpointProperties(String uri) { return validateEndpointProperties(uri, false); } @Override public EndpointValidationResult validateEndpointProperties(String uri, boolean ignoreLenientProperties) { EndpointValidationResult result = new EndpointValidationResult(uri); Map<String, String> properties; List<Map<String, String>> rows; boolean lenientProperties; String scheme; try { // parse the uri URI u = normalizeUri(uri); scheme = u.getScheme(); String json = componentJSonSchema(scheme); if (json == null) { result.addUnknownComponent(scheme); return result; } rows = JSonSchemaHelper.parseJsonSchema("component", json, false); // only enable lenient properties if we should not ignore lenientProperties = !ignoreLenientProperties && isComponentLenientProperties(rows); rows = JSonSchemaHelper.parseJsonSchema("properties", json, true); properties = endpointProperties(uri); } catch (URISyntaxException e) { result.addSyntaxError(e.getMessage()); return result; } // the dataformat component refers to a data format so lets add the properties for the selected // data format to the list of rows if ("dataformat".equals(scheme)) { String dfName = properties.get("name"); if (dfName != null) { String dfJson = dataFormatJSonSchema(dfName); List<Map<String, String>> dfRows = JSonSchemaHelper.parseJsonSchema("properties", dfJson, true); if (dfRows != null && !dfRows.isEmpty()) { rows.addAll(dfRows); } } } // validate all the options for (Map.Entry<String, String> property : properties.entrySet()) { String value = property.getValue(); String originalName = property.getKey(); String name = property.getKey(); // the name may be using an optional prefix, so lets strip that because the options // in the schema are listed without the prefix name = stripOptionalPrefixFromName(rows, name); // the name may be using a prefix, so lets see if we can find the real property name String propertyName = getPropertyNameFromNameWithPrefix(rows, name); if (propertyName != null) { name = propertyName; } String prefix = getPropertyPrefix(rows, name); String kind = getPropertyKind(rows, name); boolean placeholder = value.startsWith("{{") || value.startsWith("${") || value.startsWith("$simple{"); boolean lookup = value.startsWith("#") && value.length() > 1; // we cannot evaluate multi values as strict as the others, as we don't know their expected types boolean mulitValue = prefix != null && originalName.startsWith(prefix) && isPropertyMultiValue(rows, name); Map<String, String> row = getRow(rows, name); if (row == null) { // unknown option // only add as error if the component is not lenient properties, or not stub component // as if we are lenient then the option is a dynamic extra option which we cannot validate if (!lenientProperties && !"stub".equals(scheme)) { result.addUnknown(name); if (suggestionStrategy != null) { String[] suggestions = suggestionStrategy.suggestEndpointOptions(getNames(rows), name); if (suggestions != null) { result.addUnknownSuggestions(name, suggestions); } } } } else { // default value String defaultValue = getPropertyDefaultValue(rows, name); if (defaultValue != null) { result.addDefaultValue(name, defaultValue); } // is required but the value is empty boolean required = isPropertyRequired(rows, name); if (required && isEmpty(value)) { result.addRequired(name); } // is enum but the value is not within the enum range // but we can only check if the value is not a placeholder String enums = getPropertyEnum(rows, name); if (!mulitValue && !placeholder && !lookup && enums != null) { String[] choices = enums.split(","); boolean found = false; for (String s : choices) { if (value.equalsIgnoreCase(s)) { found = true; break; } } if (!found) { result.addInvalidEnum(name, value); result.addInvalidEnumChoices(name, choices); } } // is reference lookup of bean (not applicable for @UriPath, or multi-valued) if (!mulitValue && !"path".equals(kind) && isPropertyObject(rows, name)) { // must start with # and be at least 2 characters if (!value.startsWith("#") || value.length() <= 1) { result.addInvalidReference(name, value); } } // is boolean if (!mulitValue && !placeholder && !lookup && isPropertyBoolean(rows, name)) { // value must be a boolean boolean bool = "true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value); if (!bool) { result.addInvalidBoolean(name, value); } } // is integer if (!mulitValue && !placeholder && !lookup && isPropertyInteger(rows, name)) { // value must be an integer boolean valid = validateInteger(value); if (!valid) { result.addInvalidInteger(name, value); } } // is number if (!mulitValue && !placeholder && !lookup && isPropertyNumber(rows, name)) { // value must be an number boolean valid = false; try { valid = !Double.valueOf(value).isNaN() || !Float.valueOf(value).isNaN(); } catch (Exception e) { // ignore } if (!valid) { result.addInvalidNumber(name, value); } } } } // now check if all required values are there, and that a default value does not exists for (Map<String, String> row : rows) { String name = row.get("name"); boolean required = isPropertyRequired(rows, name); if (required) { String value = properties.get(name); if (isEmpty(value)) { value = getPropertyDefaultValue(rows, name); } if (isEmpty(value)) { result.addRequired(name); } } } return result; } private static boolean validateInteger(String value) { boolean valid = false; try { valid = Integer.valueOf(value) != null; } catch (Exception e) { // ignore } if (!valid) { // it may be a time pattern, such as 5s for 5 seconds = 5000 try { TimePatternConverter.toMilliSeconds(value); valid = true; } catch (Exception e) { // ignore } } return valid; } @Override public Map<String, String> endpointProperties(String uri) throws URISyntaxException { // NOTICE: This logic is similar to org.apache.camel.util.EndpointHelper#endpointProperties // as the catalog also offers similar functionality (without having camel-core on classpath) // need to normalize uri first // parse the uri URI u = normalizeUri(uri); String scheme = u.getScheme(); String json = componentJSonSchema(scheme); if (json == null) { throw new IllegalArgumentException("Cannot find endpoint with scheme " + scheme); } // grab the syntax String syntax = null; List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("component", json, false); for (Map<String, String> row : rows) { if (row.containsKey("syntax")) { syntax = row.get("syntax"); break; } } if (syntax == null) { throw new IllegalArgumentException("Endpoint with scheme " + scheme + " has no syntax defined in the json schema"); } // clip the scheme from the syntax syntax = after(syntax, ":"); // clip the scheme from the uri uri = after(uri, ":"); String uriPath = stripQuery(uri); // parse the syntax and find the names of each option Matcher matcher = SYNTAX_PATTERN.matcher(syntax); List<String> word = new ArrayList<String>(); while (matcher.find()) { String s = matcher.group(1); if (!scheme.equals(s)) { word.add(s); } } // parse the syntax and find each token between each option String[] tokens = SYNTAX_PATTERN.split(syntax); // find the position where each option start/end List<String> word2 = new ArrayList<String>(); int prev = 0; for (String token : tokens) { if (token.isEmpty()) { continue; } // special for some tokens where :// can be used also, eg http://foo int idx = -1; int len = 0; if (":".equals(token)) { idx = uriPath.indexOf("://", prev); len = 3; } if (idx == -1) { idx = uriPath.indexOf(token, prev); len = token.length(); } if (idx > 0) { String option = uriPath.substring(prev, idx); word2.add(option); prev = idx + len; } } // special for last or if we did not add anyone if (prev > 0 || word2.isEmpty()) { String option = uriPath.substring(prev); word2.add(option); } rows = JSonSchemaHelper.parseJsonSchema("properties", json, true); boolean defaultValueAdded = false; // now parse the uri to know which part isw what Map<String, String> options = new LinkedHashMap<String, String>(); // word contains the syntax path elements Iterator<String> it = word2.iterator(); for (int i = 0; i < word.size(); i++) { String key = word.get(i); boolean allOptions = word.size() == word2.size(); boolean required = isPropertyRequired(rows, key); String defaultValue = getPropertyDefaultValue(rows, key); // we have all options so no problem if (allOptions) { String value = it.next(); options.put(key, value); } else { // we have a little problem as we do not not have all options if (!required) { String value = defaultValue; if (value != null) { options.put(key, value); defaultValueAdded = true; } } else { String value = it.hasNext() ? it.next() : null; if (value != null) { options.put(key, value); } } } } Map<String, String> answer = new LinkedHashMap<String, String>(); // remove all options which are using default values and are not required for (Map.Entry<String, String> entry : options.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (defaultValueAdded) { boolean required = isPropertyRequired(rows, key); String defaultValue = getPropertyDefaultValue(rows, key); if (!required && defaultValue != null) { if (defaultValue.equals(value)) { continue; } } } // we should keep this in the answer answer.put(key, value); } // now parse the uri parameters Map<String, Object> parameters = URISupport.parseParameters(u); // and covert the values to String so its JMX friendly for (Map.Entry<String, Object> entry : parameters.entrySet()) { String key = entry.getKey(); String value = entry.getValue() != null ? entry.getValue().toString() : ""; answer.put(key, value); } return answer; } @Override public String endpointComponentName(String uri) { if (uri != null) { int idx = uri.indexOf(":"); if (idx > 0) { return uri.substring(0, idx); } } return null; } @Override public String asEndpointUri(String scheme, String json, boolean encode) throws URISyntaxException { return doAsEndpointUri(scheme, json, "&", encode); } @Override public String asEndpointUriXml(String scheme, String json, boolean encode) throws URISyntaxException { return doAsEndpointUri(scheme, json, "&amp;", encode); } private String doAsEndpointUri(String scheme, String json, String ampersand, boolean encode) throws URISyntaxException { List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("properties", json, true); Map<String, String> copy = new HashMap<String, String>(); for (Map<String, String> row : rows) { String name = row.get("name"); String required = row.get("required"); String value = row.get("value"); String defaultValue = row.get("defaultValue"); // only add if either required, or the value is != default value String valueToAdd = null; if ("true".equals(required)) { valueToAdd = value != null ? value : defaultValue; if (valueToAdd == null) { valueToAdd = ""; } } else { // if we have a value and no default then add it if (value != null && defaultValue == null) { valueToAdd = value; } // otherwise only add if the value is != default value if (value != null && defaultValue != null && !value.equals(defaultValue)) { valueToAdd = value; } } if (valueToAdd != null) { copy.put(name, valueToAdd); } } return doAsEndpointUri(scheme, copy, ampersand, encode); } @Override public String asEndpointUri(String scheme, Map<String, String> properties, boolean encode) throws URISyntaxException { return doAsEndpointUri(scheme, properties, "&", encode); } @Override public String asEndpointUriXml(String scheme, Map<String, String> properties, boolean encode) throws URISyntaxException { return doAsEndpointUri(scheme, properties, "&amp;", encode); } private String doAsEndpointUri(String scheme, Map<String, String> properties, String ampersand, boolean encode) throws URISyntaxException { String json = componentJSonSchema(scheme); if (json == null) { throw new IllegalArgumentException("Cannot find endpoint with scheme " + scheme); } // grab the syntax String syntax = null; List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("component", json, false); for (Map<String, String> row : rows) { if (row.containsKey("syntax")) { syntax = row.get("syntax"); break; } } if (syntax == null) { throw new IllegalArgumentException("Endpoint with scheme " + scheme + " has no syntax defined in the json schema"); } // do any properties filtering which can be needed for some special components properties = filterProperties(scheme, properties); rows = JSonSchemaHelper.parseJsonSchema("properties", json, true); // clip the scheme from the syntax syntax = after(syntax, ":"); String originalSyntax = syntax; // build at first according to syntax (use a tree map as we want the uri options sorted) Map<String, String> copy = new TreeMap<String, String>(); for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); String value = entry.getValue() != null ? entry.getValue() : ""; if (syntax != null && syntax.contains(key)) { syntax = syntax.replace(key, value); } else { copy.put(key, value); } } // the tokens between the options in the path String[] tokens = syntax.split("\\w+"); // parse the syntax into each options Matcher matcher = SYNTAX_PATTERN.matcher(originalSyntax); List<String> options = new ArrayList<String>(); while (matcher.find()) { String s = matcher.group(1); options.add(s); } // parse the syntax into each options Matcher matcher2 = SYNTAX_PATTERN.matcher(syntax); List<String> options2 = new ArrayList<String>(); while (matcher2.find()) { String s = matcher2.group(1); options2.add(s); } // build the endpoint StringBuilder sb = new StringBuilder(); sb.append(scheme); sb.append(":"); int range = 0; boolean first = true; boolean hasQuestionmark = false; for (int i = 0; i < options.size(); i++) { String key = options.get(i); String key2 = options2.get(i); String token = null; if (tokens.length > i) { token = tokens[i]; } boolean contains = properties.containsKey(key); if (!contains) { // if the key are similar we have no explicit value and can try to find a default value if the option is required if (isPropertyRequired(rows, key)) { String value = getPropertyDefaultValue(rows, key); if (value != null) { properties.put(key, value); key2 = value; } } } // was the option provided? if (properties.containsKey(key)) { if (!first && token != null) { sb.append(token); } hasQuestionmark |= key.contains("?") || (token != null && token.contains("?")); sb.append(key2); first = false; } range++; } // append any extra options that was in surplus for the last while (range < options2.size()) { String token = null; if (tokens.length > range) { token = tokens[range]; } String key2 = options2.get(range); sb.append(token); sb.append(key2); hasQuestionmark |= key2.contains("?") || (token != null && token.contains("?")); range++; } if (!copy.isEmpty()) { // the last option may already contain a ? char, if so we should use & instead of ? sb.append(hasQuestionmark ? ampersand : '?'); String query = createQueryString(copy, ampersand, encode); sb.append(query); } return sb.toString(); } @Override public SimpleValidationResult validateSimpleExpression(String simple) { return doValidateSimple(simple, false); } @Override public SimpleValidationResult validateSimplePredicate(String simple) { return doValidateSimple(simple, true); } private SimpleValidationResult doValidateSimple(String simple, boolean predicate) { SimpleValidationResult answer = new SimpleValidationResult(simple); Object instance = null; Class clazz = null; try { clazz = DefaultCamelCatalog.class.getClassLoader().loadClass("org.apache.camel.language.simple.SimpleLanguage"); instance = clazz.newInstance(); } catch (Exception e) { // ignore } if (clazz != null && instance != null) { try { if (predicate) { instance.getClass().getMethod("createPredicate", String.class).invoke(instance, simple); } else { instance.getClass().getMethod("createExpression", String.class).invoke(instance, simple); } } catch (InvocationTargetException e) { answer.setError(e.getTargetException().getMessage()); } catch (Exception e) { answer.setError(e.getMessage()); } } return answer; } /** * Special logic for log endpoints to deal when showAll=true */ private Map<String, String> filterProperties(String scheme, Map<String, String> options) { if ("log".equals(scheme)) { Map<String, String> answer = new LinkedHashMap<String, String>(); String showAll = options.get("showAll"); if ("true".equals(showAll)) { // remove all the other showXXX options when showAll=true for (Map.Entry<String, String> entry : options.entrySet()) { String key = entry.getKey(); boolean skip = key.startsWith("show") && !key.equals("showAll"); if (!skip) { answer.put(key, entry.getValue()); } } } return answer; } else { // use as-is return options; } } @Override public String listComponentsAsJson() { String answer = null; if (caching) { answer = (String) cache.get("listComponentsAsJson"); } if (answer == null) { StringBuilder sb = new StringBuilder(); sb.append("["); List<String> names = findComponentNames(); for (int i = 0; i < names.size(); i++) { String scheme = names.get(i); String json = componentJSonSchema(scheme); // skip first line json = CatalogHelper.between(json, "\"component\": {", "\"componentProperties\": {"); json = json != null ? json.trim() : ""; // skip last comma if not the last if (i == names.size() - 1) { json = json.substring(0, json.length() - 1); } sb.append("\n"); sb.append(" {\n"); sb.append(" "); sb.append(json); } sb.append("\n]"); answer = sb.toString(); if (caching) { cache.put("listComponentsAsJson", answer); } } return answer; } @Override public String listDataFormatsAsJson() { String answer = null; if (caching) { answer = (String) cache.get("listDataFormatsAsJson"); } if (answer == null) { StringBuilder sb = new StringBuilder(); sb.append("["); List<String> names = findDataFormatNames(); for (int i = 0; i < names.size(); i++) { String scheme = names.get(i); String json = dataFormatJSonSchema(scheme); // skip first line json = CatalogHelper.between(json, "\"dataformat\": {", "\"properties\": {"); json = json != null ? json.trim() : ""; // skip last comma if not the last if (i == names.size() - 1) { json = json.substring(0, json.length() - 1); } sb.append("\n"); sb.append(" {\n"); sb.append(" "); sb.append(json); } sb.append("\n]"); answer = sb.toString(); if (caching) { cache.put("listDataFormatsAsJson", answer); } } return answer; } @Override public String listLanguagesAsJson() { String answer = null; if (caching) { answer = (String) cache.get("listLanguagesAsJson"); } if (answer == null) { StringBuilder sb = new StringBuilder(); sb.append("["); List<String> names = findLanguageNames(); for (int i = 0; i < names.size(); i++) { String scheme = names.get(i); String json = languageJSonSchema(scheme); // skip first line json = CatalogHelper.between(json, "\"language\": {", "\"properties\": {"); json = json != null ? json.trim() : ""; // skip last comma if not the last if (i == names.size() - 1) { json = json.substring(0, json.length() - 1); } sb.append("\n"); sb.append(" {\n"); sb.append(" "); sb.append(json); } sb.append("\n]"); answer = sb.toString(); if (caching) { cache.put("listLanguagesAsJson", answer); } } return answer; } @Override public String listModelsAsJson() { String answer = null; if (caching) { answer = (String) cache.get("listModelsAsJson"); } if (answer == null) { StringBuilder sb = new StringBuilder(); sb.append("["); List<String> names = findModelNames(); for (int i = 0; i < names.size(); i++) { String scheme = names.get(i); String json = modelJSonSchema(scheme); // skip first line json = CatalogHelper.between(json, "\"model\": {", "\"properties\": {"); json = json != null ? json.trim() : ""; // skip last comma if not the last if (i == names.size() - 1) { json = json.substring(0, json.length() - 1); } sb.append("\n"); sb.append(" {\n"); sb.append(" "); sb.append(json); } sb.append("\n]"); answer = sb.toString(); if (caching) { cache.put("listModelsAsJson", answer); } } return answer; } @Override public String summaryAsJson() { String answer = null; if (caching) { answer = (String) cache.get("summaryAsJson"); } if (answer == null) { int archetypes = 0; try { String xml = archetypeCatalogAsXml(); Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes())); Object val = XPathFactory.newInstance().newXPath().evaluate("count(/archetype-catalog/archetypes/archetype)", dom, XPathConstants.NUMBER); double num = (double) val; archetypes = (int) num; } catch (Exception e) { // ignore } StringBuilder sb = new StringBuilder(); sb.append("{\n"); sb.append(" \"version\": \"").append(getCatalogVersion()).append("\",\n"); sb.append(" \"eips\": ").append(findModelNames().size()).append(",\n"); sb.append(" \"components\": ").append(findComponentNames().size()).append(",\n"); sb.append(" \"dataformats\": ").append(findDataFormatNames().size()).append(",\n"); sb.append(" \"languages\": ").append(findLanguageNames().size()).append(",\n"); sb.append(" \"archetypes\": ").append(archetypes).append("\n"); sb.append("}"); answer = sb.toString(); if (caching) { cache.put("summaryAsJson", answer); } } return answer; } }
askannon/camel
platforms/catalog/src/main/java/org/apache/camel/catalog/DefaultCamelCatalog.java
Java
apache-2.0
55,732
/* * 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.jackrabbit.oak.plugins.index; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.newArrayListWithCapacity; import static com.google.common.collect.Sets.newHashSet; import static org.apache.jackrabbit.oak.api.Type.BOOLEAN; import static org.apache.jackrabbit.oak.commons.PathUtils.concat; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.ASYNC_PROPERTY_NAME; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.ASYNC_REINDEX_VALUE; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_DEFINITIONS_NAME; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_PATH; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.REINDEX_ASYNC_PROPERTY_NAME; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.REINDEX_COUNT; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.REINDEX_PROPERTY_NAME; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.TYPE_PROPERTY_NAME; import static org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.MISSING_NODE; import static org.apache.jackrabbit.oak.spi.commit.CompositeEditor.compose; import static org.apache.jackrabbit.oak.spi.commit.EditorDiff.process; import static org.apache.jackrabbit.oak.spi.commit.VisibleEditor.wrap; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import com.google.common.base.Stopwatch; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.jackrabbit.oak.api.CommitFailedException; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.commons.PathUtils; import org.apache.jackrabbit.oak.spi.commit.CommitInfo; import org.apache.jackrabbit.oak.spi.commit.Editor; import org.apache.jackrabbit.oak.spi.commit.ProgressNotificationEditor; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.jackrabbit.oak.spi.state.NodeStateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class IndexUpdate implements Editor { private static final Logger log = LoggerFactory.getLogger(IndexUpdate.class); /** * <p> * The value of this flag determines the behavior of the IndexUpdate when * dealing with {@code reindex} flags. * </p> * <p> * If {@code false} (default value), the indexer will start reindexing * immediately in the current thread, blocking a commit until this operation * is done. * </p> * <p> * If {@code true}, the indexer will ignore the flag, therefore ignoring any * reindex requests. * </p> * <p> * This is only provided as a support tool (see OAK-3505) so it should be * used with extreme caution! * </p> */ private static final boolean IGNORE_REINDEX_FLAGS = Boolean .getBoolean("oak.indexUpdate.ignoreReindexFlags"); static { if (IGNORE_REINDEX_FLAGS) { log.warn("Reindexing is disabled by configuration. This value is configurable via the 'oak.indexUpdate.ignoreReindexFlags' system property."); } } private final IndexUpdateRootState rootState; private final NodeBuilder builder; /** Parent updater, or {@code null} if this is the root updater. */ private final IndexUpdate parent; /** Name of this node, or {@code null} for the root node. */ private final String name; /** Path of this editor, built lazily in {@link #getPath()}. */ private String path; /** * Editors for indexes that will be normally updated. */ private final List<Editor> editors = newArrayList(); /** * Editors for indexes that need to be re-indexed. */ private final Map<String, Editor> reindex = new HashMap<String, Editor>(); private MissingIndexProviderStrategy missingProvider = new MissingIndexProviderStrategy(); public IndexUpdate( IndexEditorProvider provider, String async, NodeState root, NodeBuilder builder, IndexUpdateCallback updateCallback) { this(provider, async, root, builder, updateCallback, CommitInfo.EMPTY); } public IndexUpdate( IndexEditorProvider provider, String async, NodeState root, NodeBuilder builder, IndexUpdateCallback updateCallback, CommitInfo commitInfo) { this.parent = null; this.name = null; this.path = "/"; this.rootState = new IndexUpdateRootState(provider, async, root, updateCallback, commitInfo); this.builder = checkNotNull(builder); } private IndexUpdate(IndexUpdate parent, String name) { this.parent = checkNotNull(parent); this.name = name; this.rootState = parent.rootState; this.builder = parent.builder.getChildNode(checkNotNull(name)); } @Override public void enter(NodeState before, NodeState after) throws CommitFailedException { collectIndexEditors(builder.getChildNode(INDEX_DEFINITIONS_NAME), before); if (!reindex.isEmpty()) { log.info("Reindexing will be performed for following indexes: {}", reindex.keySet()); rootState.reindexedIndexes.addAll(reindex.keySet()); } // no-op when reindex is empty CommitFailedException exception = process( wrap(wrapProgress(compose(reindex.values()), "Reindexing")), MISSING_NODE, after); if (exception != null) { throw exception; } for (Editor editor : editors) { editor.enter(before, after); } } public boolean isReindexingPerformed(){ return !getReindexStats().isEmpty(); } public List<String> getReindexStats(){ return rootState.getReindexStats(); } private boolean shouldReindex(NodeBuilder definition, NodeState before, String name) { PropertyState ps = definition.getProperty(REINDEX_PROPERTY_NAME); if (ps != null && ps.getValue(BOOLEAN)) { return !IGNORE_REINDEX_FLAGS; } // reindex in the case this is a new node, even though the reindex flag // might be set to 'false' (possible via content import) boolean result = !before.getChildNode(INDEX_DEFINITIONS_NAME).hasChildNode(name); if (result) { log.info("Found a new index node [{}]. Reindexing is requested", name); } return result; } private void collectIndexEditors(NodeBuilder definitions, NodeState before) throws CommitFailedException { for (String name : definitions.getChildNodeNames()) { NodeBuilder definition = definitions.getChildNode(name); if (isIncluded(rootState.async, definition)) { String type = definition.getString(TYPE_PROPERTY_NAME); if (type == null) { // probably not an index def continue; } manageIndexPath(definition, name); boolean shouldReindex = shouldReindex(definition, before, name); String indexPath = getIndexPath(getPath(), name); Editor editor = rootState.provider.getIndexEditor(type, definition, rootState.root, rootState.newCallback(indexPath, shouldReindex)); if (editor == null) { missingProvider.onMissingIndex(type, definition, indexPath); } else if (shouldReindex) { if (definition.getBoolean(REINDEX_ASYNC_PROPERTY_NAME) && definition.getString(ASYNC_PROPERTY_NAME) == null) { // switch index to an async update mode definition.setProperty(ASYNC_PROPERTY_NAME, ASYNC_REINDEX_VALUE); } else { definition.setProperty(REINDEX_PROPERTY_NAME, false); incrementReIndexCount(definition); // as we don't know the index content node name // beforehand, we'll remove all child nodes for (String rm : definition.getChildNodeNames()) { if (NodeStateUtils.isHidden(rm)) { definition.getChildNode(rm).remove(); } } reindex.put(concat(getPath(), INDEX_DEFINITIONS_NAME, name), editor); } } else { editors.add(editor); } } } } static boolean isIncluded(String asyncRef, NodeBuilder definition) { if (definition.hasProperty(ASYNC_PROPERTY_NAME)) { PropertyState p = definition.getProperty(ASYNC_PROPERTY_NAME); List<String> opt = newArrayList(p.getValue(Type.STRINGS)); if (asyncRef == null) { // sync index job, accept synonyms return opt.contains("") || opt.contains("sync"); } else { return opt.contains(asyncRef); } } else { return asyncRef == null; } } private void manageIndexPath(NodeBuilder definition, String name) { String path = definition.getString(INDEX_PATH); if (path == null){ definition.setProperty(INDEX_PATH, PathUtils.concat(getPath(), INDEX_DEFINITIONS_NAME, name)); } } private void incrementReIndexCount(NodeBuilder definition) { long count = 0; if(definition.hasProperty(REINDEX_COUNT)){ count = definition.getProperty(REINDEX_COUNT).getValue(Type.LONG); } definition.setProperty(REINDEX_COUNT, count + 1); } /** * Returns the path of this node, building it lazily when first requested. */ private String getPath() { if (path == null) { path = concat(parent.getPath(), name); } return path; } @Override public void leave(NodeState before, NodeState after) throws CommitFailedException { for (Editor editor : editors) { editor.leave(before, after); } if (parent == null){ if (rootState.isReindexingPerformed()){ log.info(rootState.getReport()); } else if (log.isDebugEnabled() && rootState.somethingIndexed()){ log.debug(rootState.getReport()); } } } @Override public void propertyAdded(PropertyState after) throws CommitFailedException { for (Editor editor : editors) { editor.propertyAdded(after); } } @Override public void propertyChanged(PropertyState before, PropertyState after) throws CommitFailedException { for (Editor editor : editors) { editor.propertyChanged(before, after); } } @Override public void propertyDeleted(PropertyState before) throws CommitFailedException { for (Editor editor : editors) { editor.propertyDeleted(before); } } @Override @Nonnull public Editor childNodeAdded(String name, NodeState after) throws CommitFailedException { List<Editor> children = newArrayListWithCapacity(1 + editors.size()); children.add(new IndexUpdate(this, name)); for (Editor editor : editors) { Editor child = editor.childNodeAdded(name, after); if (child != null) { children.add(child); } } return compose(children); } @Override @Nonnull public Editor childNodeChanged( String name, NodeState before, NodeState after) throws CommitFailedException { List<Editor> children = newArrayListWithCapacity(1 + editors.size()); children.add(new IndexUpdate(this, name)); for (Editor editor : editors) { Editor child = editor.childNodeChanged(name, before, after); if (child != null) { children.add(child); } } return compose(children); } @Override @CheckForNull public Editor childNodeDeleted(String name, NodeState before) throws CommitFailedException { List<Editor> children = newArrayListWithCapacity(editors.size()); for (Editor editor : editors) { Editor child = editor.childNodeDeleted(name, before); if (child != null) { children.add(child); } } return compose(children); } protected Set<String> getReindexedDefinitions() { return reindex.keySet(); } private static String getIndexPath(String path, String indexName) { if (PathUtils.denotesRoot(path)) { return "/" + INDEX_DEFINITIONS_NAME + "/" + indexName; } return path + "/" + INDEX_DEFINITIONS_NAME + "/" + indexName; } private static Editor wrapProgress(Editor editor, String message){ return ProgressNotificationEditor.wrap(editor, log, message); } public static class MissingIndexProviderStrategy { /** * The value of this flag determines the behavior of * {@link #onMissingIndex(String, NodeBuilder, String)}. If * {@code false} (default value), the method will set the * {@code reindex} flag to true and log a warning. if {@code true}, the * method will throw a {@link CommitFailedException} failing the commit. */ private boolean failOnMissingIndexProvider = Boolean .getBoolean("oak.indexUpdate.failOnMissingIndexProvider"); private final Set<String> ignore = newHashSet("disabled"); public void onMissingIndex(String type, NodeBuilder definition, String indexPath) throws CommitFailedException { if (isDisabled(type)) { return; } // trigger reindexing when an indexer becomes available PropertyState ps = definition.getProperty(REINDEX_PROPERTY_NAME); if (ps != null && ps.getValue(BOOLEAN)) { // already true, skip the update return; } if (failOnMissingIndexProvider) { throw new CommitFailedException("IndexUpdate", 1, "Missing index provider detected for type [" + type + "] on index [" + indexPath + "]"); } else { log.warn( "Missing index provider of type [{}], requesting reindex on [{}]", type, indexPath); definition.setProperty(REINDEX_PROPERTY_NAME, true); } } boolean isDisabled(String type) { return ignore.contains(type); } void setFailOnMissingIndexProvider(boolean failOnMissingIndexProvider) { this.failOnMissingIndexProvider = failOnMissingIndexProvider; } } public IndexUpdate withMissingProviderStrategy( MissingIndexProviderStrategy missingProvider) { this.missingProvider = missingProvider; return this; } private static final class IndexUpdateRootState { final IndexEditorProvider provider; final String async; final NodeState root; final CommitInfo commitInfo; /** * Callback for the update events of the indexing job */ final IndexUpdateCallback updateCallback; final Set<String> reindexedIndexes = Sets.newHashSet(); final Map<String, CountingCallback> callbacks = Maps.newHashMap(); private IndexUpdateRootState(IndexEditorProvider provider, String async, NodeState root, IndexUpdateCallback updateCallback, CommitInfo commitInfo) { this.provider = checkNotNull(provider); this.async = async; this.root = checkNotNull(root); this.updateCallback = checkNotNull(updateCallback); this.commitInfo = commitInfo; } public IndexUpdateCallback newCallback(String indexPath, boolean reindex) { CountingCallback cb = new CountingCallback(indexPath, reindex); callbacks.put(cb.indexPath, cb); return cb; } public String getReport() { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println("Indexing report"); for (CountingCallback cb : callbacks.values()) { if (!log.isDebugEnabled() && !cb.reindex) { continue; } if (cb.count > 0) { pw.printf(" - %s%n", cb); } } return sw.toString(); } public List<String> getReindexStats(){ List<String> stats = Lists.newArrayList(); for (CountingCallback cb : callbacks.values()){ if (cb.reindex) { stats.add(cb.toString()); } } return stats; } public boolean somethingIndexed() { for (CountingCallback cb : callbacks.values()) { if (cb.count > 0){ return true; } } return false; } public boolean isReindexingPerformed(){ return !reindexedIndexes.isEmpty(); } private class CountingCallback implements ContextAwareCallback, IndexingContext { final String indexPath; final boolean reindex; final Stopwatch watch = Stopwatch.createStarted(); int count; public CountingCallback(String indexPath, boolean reindex) { this.indexPath = indexPath; this.reindex = reindex; } @Override public void indexUpdate() throws CommitFailedException { count++; if (count % 10000 == 0){ log.info("{} => Indexed {} nodes in {} ...", indexPath, count, watch); watch.reset().start(); } updateCallback.indexUpdate(); } @Override public String toString() { String reindexMarker = reindex ? "*" : ""; return indexPath + reindexMarker + "(" + count + ")"; } //~------------------------------< ContextAwareCallback > @Override public IndexingContext getIndexingContext() { return this; } //~--------------------------------< IndexingContext > @Override public String getIndexPath() { return indexPath; } @Override public CommitInfo getCommitInfo() { return commitInfo; } @Override public boolean isReindexing() { return reindex; } @Override public boolean isAsync() { return async != null; } } } }
kwin/jackrabbit-oak
oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/IndexUpdate.java
Java
apache-2.0
20,680
/* * Copyright (c) 2008-2016 Haulmont. * * 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.haulmont.cuba.gui.app.core.credits; import com.haulmont.cuba.gui.components.AbstractWindow; import com.haulmont.cuba.gui.components.TextArea; import com.haulmont.cuba.gui.theme.ThemeConstants; import javax.inject.Inject; import java.util.Map; public class LicenseWindow extends AbstractWindow { @Inject protected TextArea<String> licenseTextArea; @Inject protected ThemeConstants themeConstants; @Override public void init(Map<String, Object> params) { getDialogOptions() .setWidth(themeConstants.get("cuba.gui.LicenseWindow.width")) .setHeight(themeConstants.get("cuba.gui.LicenseWindow.height")) .setResizable(false); String licenseText = (String) params.get("licenseText"); if (licenseText != null) { licenseTextArea.setValue(licenseText); licenseTextArea.setEditable(false); licenseTextArea.setCursorPosition(0); } } }
cuba-platform/cuba
modules/gui/src/com/haulmont/cuba/gui/app/core/credits/LicenseWindow.java
Java
apache-2.0
1,590
/* * Copyright (C) 2004-2008 Jive Software. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.openfire.plugin; import java.io.File; import java.util.regex.PatternSyntaxException; import org.jivesoftware.openfire.MessageRouter; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.container.Plugin; import org.jivesoftware.openfire.container.PluginManager; import org.jivesoftware.openfire.interceptor.InterceptorManager; import org.jivesoftware.openfire.interceptor.PacketInterceptor; import org.jivesoftware.openfire.interceptor.PacketRejectedException; import org.jivesoftware.openfire.session.Session; import org.jivesoftware.openfire.user.User; import org.jivesoftware.openfire.user.UserManager; import org.jivesoftware.util.EmailService; import org.jivesoftware.util.JiveGlobals; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmpp.packet.JID; import org.xmpp.packet.Message; import org.xmpp.packet.Packet; import org.xmpp.packet.Presence; /** * Content filter plugin. * * @author Conor Hayes */ public class ContentFilterPlugin implements Plugin, PacketInterceptor { private static final Logger Log = LoggerFactory.getLogger(ContentFilterPlugin.class); /** * The expected value is a boolean, if true the user identified by the value * of the property #VIOLATION_NOTIFICATION_CONTACT_PROPERTY will be notified * every time there is a content match, otherwise no notification will be * sent. Then default value is false. */ public static final String VIOLATION_NOTIFICATION_ENABLED_PROPERTY = "plugin.contentFilter.violation.notification.enabled"; /** * The expected value is a user name. The default value is "admin". */ public static final String VIOLATION_NOTIFICATION_CONTACT_PROPERTY = "plugin.contentFilter.violation.notification.contact"; /** * The expected value is a boolean, if true the user identified by the value * of the property #VIOLATION_NOTIFICATION_CONTACT_PROPERTY, will also * receive a copy of the offending packet. The default value is false. */ public static final String VIOLATION_INCLUDE_ORIGNAL_PACKET_ENABLED_PROPERTY = "plugin.contentFilter.violation.notification.include.original.enabled"; /** * The expected value is a boolean, if true the user identified by the value * of the property #VIOLATION_NOTIFICATION_CONTACT_PROPERTY, will receive * notification by IM. The default value is true. */ public static final String VIOLATION_NOTIFICATION_BY_IM_ENABLED_PROPERTY = "plugin.contentFilter.violation.notification.by.im.enabled"; /** * The expected value is a boolean, if true the user identified by the value * of the property #VIOLATION_NOTIFICATION_CONTACT_PROPERTY, will receive * notification by email. The default value is false. */ public static final String VIOLATION_NOTIFICATION_BY_EMAIL_ENABLED_PROPERTY = "plugin.contentFilter.violation.notification.by.email.enabled"; /** * The expected value is a boolean, if true the sender will be notified when * a message is rejected, otherwise the message will be silently * rejected,i.e. the sender will not know that the message was rejected and * the receiver will not get the message. The default value is false. */ public static final String REJECTION_NOTIFICATION_ENABLED_PROPERTY = "plugin.contentFilter.rejection.notification.enabled"; /** * The expected value is a string, containing the desired message for the * sender notification. */ public static final String REJECTION_MSG_PROPERTY = "plugin.contentFilter.rejection.msg"; /** * The expected value is a boolean, if true the value of #PATTERNS_PROPERTY * will be used for pattern matching. */ public static final String PATTERNS_ENABLED_PROPERTY = "plugin.contentFilter.patterns.enabled"; /** * The expected value is a comma separated string of regular expressions. */ public static final String PATTERNS_PROPERTY = "plugin.contentFilter.patterns"; /** * The expected value is a boolean, if true Presence packets will be * filtered */ public static final String FILTER_STATUS_ENABLED_PROPERTY = "plugin.contentFilter.filter.status.enabled"; /** * The expected value is a boolean, if true the value of #MASK_PROPERTY will * be used to mask matching content. */ public static final String MASK_ENABLED_PROPERTY = "plugin.contentFilter.mask.enabled"; /** * The expected value is a string. If this property is set any matching * content will not be rejected but masked with the given value. Setting a * content mask means that property #SENDER_NOTIFICATION_ENABLED_PROPERTY is * ignored. The default value is "**". */ public static final String MASK_PROPERTY = "plugin.contentFilter.mask"; /** * The expected value is a boolean, if false packets whose contents matches one * of the supplied regular expressions will be rejected, otherwise the packet will * be accepted and may be optionally masked. The default value is false. * @see #MASK_ENABLED_PROPERTY */ public static final String ALLOW_ON_MATCH_PROPERTY = "plugin.contentFilter.allow.on.match"; /** * the hook into the inteceptor chain */ private InterceptorManager interceptorManager; /** * used to send violation notifications */ private MessageRouter messageRouter; /** * delegate that does the real work of this plugin */ private ContentFilter contentFilter; /** * flags if sender should be notified of rejections */ private boolean rejectionNotificationEnabled; /** * the rejection msg to send */ private String rejectionMessage; /** * flags if content matches should result in admin notification */ private boolean violationNotificationEnabled; /** * the admin user to send violation notifications to */ private String violationContact; /** * flags if original packet should be included in the message to the * violation contact. */ private boolean violationIncludeOriginalPacketEnabled; /** * flags if violation contact should be notified by IM. */ private boolean violationNotificationByIMEnabled; /** * flags if violation contact should be notified by email. */ private boolean violationNotificationByEmailEnabled; /** * flag if patterns should be used */ private boolean patternsEnabled; /** * the patterns to use */ private String patterns; /** * flag if Presence packets should be filtered. */ private boolean filterStatusEnabled; /** * flag if mask should be used */ private boolean maskEnabled; /** * the mask to use */ private String mask; /** * flag if matching content should be accepted or rejected. */ private boolean allowOnMatch; /** * violation notification messages will be from this JID */ private JID violationNotificationFrom; public ContentFilterPlugin() { contentFilter = new ContentFilter(); interceptorManager = InterceptorManager.getInstance(); violationNotificationFrom = new JID(XMPPServer.getInstance() .getServerInfo().getXMPPDomain()); messageRouter = XMPPServer.getInstance().getMessageRouter(); } /** * Restores the plugin defaults. */ public void reset() { setViolationNotificationEnabled(false); setViolationContact("admin"); setViolationNotificationByIMEnabled(true); setViolationNotificationByEmailEnabled(false); setViolationIncludeOriginalPacketEnabled(false); setRejectionNotificationEnabled(false); setRejectionMessage("Message rejected. This is an automated server response"); setPatternsEnabled(false); setPatterns("fox,dog"); setFilterStatusEnabled(false); setMaskEnabled(false); setMask("***"); setAllowOnMatch(false); } public boolean isAllowOnMatch() { return allowOnMatch; } public void setAllowOnMatch(boolean allow) { allowOnMatch = allow; JiveGlobals.setProperty(ALLOW_ON_MATCH_PROPERTY, allow ? "true" : "false"); changeContentFilterMask(); } public boolean isMaskEnabled() { return maskEnabled; } public void setMaskEnabled(boolean enabled) { maskEnabled = enabled; JiveGlobals.setProperty(MASK_ENABLED_PROPERTY, enabled ? "true" : "false"); changeContentFilterMask(); } public void setMask(String mas) { mask = mas; JiveGlobals.setProperty(MASK_PROPERTY, mas); changeContentFilterMask(); } private void changeContentFilterMask() { if (allowOnMatch && maskEnabled) { contentFilter.setMask(mask); } else { contentFilter.clearMask(); } } public String getMask() { return mask; } public boolean isPatternsEnabled() { return patternsEnabled; } public void setPatternsEnabled(boolean enabled) { patternsEnabled = enabled; JiveGlobals.setProperty(PATTERNS_ENABLED_PROPERTY, enabled ? "true" : "false"); changeContentFilterPatterns(); } public void setPatterns(String patt) { patterns = patt; JiveGlobals.setProperty(PATTERNS_PROPERTY, patt); changeContentFilterPatterns(); } public boolean isFilterStatusEnabled() { return filterStatusEnabled; } public void setFilterStatusEnabled(boolean enabled) { filterStatusEnabled = enabled; JiveGlobals.setProperty(FILTER_STATUS_ENABLED_PROPERTY, enabled ? "true" : "false"); } private void changeContentFilterPatterns() { if (patternsEnabled) { contentFilter.setPatterns(patterns); } else { contentFilter.clearPatterns(); } } public String getPatterns() { return patterns; } public boolean isRejectionNotificationEnabled() { return rejectionNotificationEnabled; } public void setRejectionNotificationEnabled(boolean enabled) { rejectionNotificationEnabled = enabled; JiveGlobals.setProperty(REJECTION_NOTIFICATION_ENABLED_PROPERTY, enabled ? "true" : "false"); } public String getRejectionMessage() { return rejectionMessage; } public void setRejectionMessage(String message) { this.rejectionMessage = message; JiveGlobals.setProperty(REJECTION_MSG_PROPERTY, message); } public boolean isViolationNotificationEnabled() { return violationNotificationEnabled; } public void setViolationNotificationEnabled(boolean enabled) { violationNotificationEnabled = enabled; JiveGlobals.setProperty(VIOLATION_NOTIFICATION_ENABLED_PROPERTY, enabled ? "true" : "false"); } public void setViolationContact(String contact) { violationContact = contact; JiveGlobals.setProperty(VIOLATION_NOTIFICATION_CONTACT_PROPERTY, contact); } public String getViolationContact() { return violationContact; } public boolean isViolationIncludeOriginalPacketEnabled() { return violationIncludeOriginalPacketEnabled; } public void setViolationIncludeOriginalPacketEnabled(boolean enabled) { violationIncludeOriginalPacketEnabled = enabled; JiveGlobals.setProperty( VIOLATION_INCLUDE_ORIGNAL_PACKET_ENABLED_PROPERTY, enabled ? "true" : "false"); } public boolean isViolationNotificationByIMEnabled() { return violationNotificationByIMEnabled; } public void setViolationNotificationByIMEnabled(boolean enabled) { violationNotificationByIMEnabled = enabled; JiveGlobals.setProperty(VIOLATION_NOTIFICATION_BY_IM_ENABLED_PROPERTY, enabled ? "true" : "false"); } public boolean isViolationNotificationByEmailEnabled() { return violationNotificationByEmailEnabled; } public void setViolationNotificationByEmailEnabled(boolean enabled) { violationNotificationByEmailEnabled = enabled; JiveGlobals.setProperty( VIOLATION_NOTIFICATION_BY_EMAIL_ENABLED_PROPERTY, enabled ? "true" : "false"); } public void initializePlugin(PluginManager pManager, File pluginDirectory) { // configure this plugin initFilter(); // register with interceptor manager interceptorManager.addInterceptor(this); } private void initFilter() { // default to false violationNotificationEnabled = JiveGlobals.getBooleanProperty( VIOLATION_NOTIFICATION_ENABLED_PROPERTY, false); // default to "admin" violationContact = JiveGlobals.getProperty( VIOLATION_NOTIFICATION_CONTACT_PROPERTY, "admin"); // default to true violationNotificationByIMEnabled = JiveGlobals.getBooleanProperty( VIOLATION_NOTIFICATION_BY_IM_ENABLED_PROPERTY, true); // default to false violationNotificationByEmailEnabled = JiveGlobals.getBooleanProperty( VIOLATION_NOTIFICATION_BY_EMAIL_ENABLED_PROPERTY, false); // default to false violationIncludeOriginalPacketEnabled = JiveGlobals.getBooleanProperty( VIOLATION_INCLUDE_ORIGNAL_PACKET_ENABLED_PROPERTY, false); // default to false rejectionNotificationEnabled = JiveGlobals.getBooleanProperty( REJECTION_NOTIFICATION_ENABLED_PROPERTY, false); // default to english rejectionMessage = JiveGlobals.getProperty(REJECTION_MSG_PROPERTY, "Message rejected. This is an automated server response"); // default to false patternsEnabled = JiveGlobals.getBooleanProperty( PATTERNS_ENABLED_PROPERTY, false); // default to "fox,dog" patterns = JiveGlobals.getProperty(PATTERNS_PROPERTY, "fox,dog"); try { changeContentFilterPatterns(); } catch (PatternSyntaxException e) { Log.warn("Resetting to default patterns of ContentFilterPlugin", e); // Existing patterns are invalid so reset to default ones setPatterns("fox,dog"); } // default to false filterStatusEnabled = JiveGlobals.getBooleanProperty( FILTER_STATUS_ENABLED_PROPERTY, false); // default to false maskEnabled = JiveGlobals.getBooleanProperty(MASK_ENABLED_PROPERTY, false); // default to "***" mask = JiveGlobals.getProperty(MASK_PROPERTY, "***"); // default to false allowOnMatch = JiveGlobals.getBooleanProperty( ALLOW_ON_MATCH_PROPERTY, false); //v1.2.2 backwards compatibility if (maskEnabled) { allowOnMatch = true; } changeContentFilterMask(); } /** * @see org.jivesoftware.openfire.container.Plugin#destroyPlugin() */ public void destroyPlugin() { // unregister with interceptor manager interceptorManager.removeInterceptor(this); } public void interceptPacket(Packet packet, Session session, boolean read, boolean processed) throws PacketRejectedException { if (isValidTargetPacket(packet, read, processed)) { Packet original = packet; if (Log.isDebugEnabled()) { Log.debug("Content filter: intercepted packet:" + original.toString()); } // make a copy of the original packet only if required, // as it's an expensive operation if (violationNotificationEnabled && violationIncludeOriginalPacketEnabled && maskEnabled) { original = packet.createCopy(); } // filter the packet boolean contentMatched = contentFilter.filter(packet); if (Log.isDebugEnabled()) { Log.debug("Content filter: content matched? " + contentMatched); } // notify admin of violations if (contentMatched && violationNotificationEnabled) { if (Log.isDebugEnabled()) { Log.debug("Content filter: sending violation notification"); Log.debug("Content filter: include original msg? " + this.violationIncludeOriginalPacketEnabled); } sendViolationNotification(original); } // msg will either be rejected silently, rejected with // some notification to sender, or allowed and optionally masked. // allowing a message without masking can be useful if the admin // simply wants to get notified of matches without interrupting // the conversation in the (spy mode!) if (contentMatched) { if (allowOnMatch) { if (Log.isDebugEnabled()) { Log.debug("Content filter: allowed content:" + packet.toString()); } // no further action required } else { // msg must be rejected if (Log.isDebugEnabled()) { Log.debug("Content filter: rejecting packet"); } PacketRejectedException rejected = new PacketRejectedException( "Packet rejected with disallowed content!"); if (rejectionNotificationEnabled) { // let the sender know about the rejection, this is // only possible/useful if the content is not masked rejected.setRejectionMessage(rejectionMessage); } throw rejected; } } } } private boolean isValidTargetPacket(Packet packet, boolean read, boolean processed) { return patternsEnabled && !processed && read && (packet instanceof Message || (filterStatusEnabled && packet instanceof Presence)); } private void sendViolationNotification(Packet originalPacket) { String subject = "Content filter notification! (" + originalPacket.getFrom().getNode() + ")"; String body; if (originalPacket instanceof Message) { Message originalMsg = (Message) originalPacket; body = "Disallowed content detected in message from:" + originalMsg.getFrom() + " to:" + originalMsg.getTo() + ", message was " + (allowOnMatch ? "allowed" + (contentFilter.isMaskingContent() ? " and masked." : " but not masked.") : "rejected.") + (violationIncludeOriginalPacketEnabled ? "\nOriginal subject:" + (originalMsg.getSubject() != null ? originalMsg .getSubject() : "") + "\nOriginal content:" + (originalMsg.getBody() != null ? originalMsg .getBody() : "") : ""); } else { // presence Presence originalPresence = (Presence) originalPacket; body = "Disallowed status detected in presence from:" + originalPresence.getFrom() + ", status was " + (allowOnMatch ? "allowed" + (contentFilter.isMaskingContent() ? " and masked." : " but not masked.") : "rejected.") + (violationIncludeOriginalPacketEnabled ? "\nOriginal status:" + originalPresence.getStatus() : ""); } if (violationNotificationByIMEnabled) { if (Log.isDebugEnabled()) { Log.debug("Content filter: sending IM notification"); } sendViolationNotificationIM(subject, body); } if (violationNotificationByEmailEnabled) { if (Log.isDebugEnabled()) { Log.debug("Content filter: sending email notification"); } sendViolationNotificationEmail(subject, body); } } private void sendViolationNotificationIM(String subject, String body) { Message message = createServerMessage(subject, body); // TODO consider spining off a separate thread here, // in high volume situations, it will result in // in faster response and notification is not required // to be real time. messageRouter.route(message); } private Message createServerMessage(String subject, String body) { Message message = new Message(); message.setTo(violationContact + "@" + violationNotificationFrom.getDomain()); message.setFrom(violationNotificationFrom); message.setSubject(subject); message.setBody(body); return message; } private void sendViolationNotificationEmail(String subject, String body) { try { User user = UserManager.getInstance().getUser(violationContact); //this is automatically put on a another thread for execution. EmailService.getInstance().sendMessage(user.getName(), user.getEmail(), "Openfire", "no_reply@" + violationNotificationFrom.getDomain(), subject, body, null); } catch (Throwable e) { // catch throwable in case email setup is invalid Log.error("Content Filter: Failed to send email, please review Openfire setup", e); } } }
Gugli/Openfire
src/plugins/contentFilter/src/java/org/jivesoftware/openfire/plugin/ContentFilterPlugin.java
Java
apache-2.0
23,052
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1beta1/explanation.proto package com.google.cloud.aiplatform.v1beta1; public interface SimilarityOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.aiplatform.v1beta1.Similarity) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * The Cloud Storage location for the input instances. * </pre> * * <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code> * * @return Whether the gcsSource field is set. */ boolean hasGcsSource(); /** * * * <pre> * The Cloud Storage location for the input instances. * </pre> * * <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code> * * @return The gcsSource. */ com.google.cloud.aiplatform.v1beta1.GcsSource getGcsSource(); /** * * * <pre> * The Cloud Storage location for the input instances. * </pre> * * <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code> */ com.google.cloud.aiplatform.v1beta1.GcsSourceOrBuilder getGcsSourceOrBuilder(); /** * * * <pre> * The configuration for the generated index, the semantics are the same as * [metadata][google.cloud.aiplatform.v1beta1.Index.metadata] and should match NearestNeighborSearchConfig. * </pre> * * <code>.google.protobuf.Value nearest_neighbor_search_config = 2;</code> * * @return Whether the nearestNeighborSearchConfig field is set. */ boolean hasNearestNeighborSearchConfig(); /** * * * <pre> * The configuration for the generated index, the semantics are the same as * [metadata][google.cloud.aiplatform.v1beta1.Index.metadata] and should match NearestNeighborSearchConfig. * </pre> * * <code>.google.protobuf.Value nearest_neighbor_search_config = 2;</code> * * @return The nearestNeighborSearchConfig. */ com.google.protobuf.Value getNearestNeighborSearchConfig(); /** * * * <pre> * The configuration for the generated index, the semantics are the same as * [metadata][google.cloud.aiplatform.v1beta1.Index.metadata] and should match NearestNeighborSearchConfig. * </pre> * * <code>.google.protobuf.Value nearest_neighbor_search_config = 2;</code> */ com.google.protobuf.ValueOrBuilder getNearestNeighborSearchConfigOrBuilder(); }
googleapis/java-aiplatform
proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/SimilarityOrBuilder.java
Java
apache-2.0
3,018
/* * Copyright 2012-2013 Ivan Gadzhega * * 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.ivang.axonix.main.events.facts.level; /** * @author Ivan Gadzhega * @since 0.1 */ public class LevelIndexFact { private int levelIndex; public LevelIndexFact(int levelIndex) { this.levelIndex = levelIndex; } public int getLevelIndex() { return levelIndex; } }
PhannGor/aXonix
sources/Main/src/main/net/ivang/axonix/main/events/facts/level/LevelIndexFact.java
Java
apache-2.0
919
/* * Licensed to Crate under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial * agreement. */ package io.crate.planner.operators; import io.crate.analyze.OrderBy; import io.crate.analyze.relations.AbstractTableRelation; import io.crate.common.collections.Lists2; import io.crate.data.Row; import io.crate.execution.dsl.projection.ColumnIndexWriterProjection; import io.crate.execution.dsl.projection.EvalProjection; import io.crate.execution.dsl.projection.MergeCountProjection; import io.crate.execution.dsl.projection.Projection; import io.crate.execution.dsl.projection.builder.ProjectionBuilder; import io.crate.expression.symbol.SelectSymbol; import io.crate.expression.symbol.Symbol; import io.crate.planner.ExecutionPlan; import io.crate.planner.Merge; import io.crate.planner.PlannerContext; import io.crate.statistics.TableStats; import javax.annotation.Nullable; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; public class Insert implements LogicalPlan { private final ColumnIndexWriterProjection writeToTable; @Nullable private final EvalProjection applyCasts; final LogicalPlan source; public Insert(LogicalPlan source, ColumnIndexWriterProjection writeToTable, @Nullable EvalProjection applyCasts) { this.source = source; this.writeToTable = writeToTable; this.applyCasts = applyCasts; } @Override public ExecutionPlan build(PlannerContext plannerContext, ProjectionBuilder projectionBuilder, int limit, int offset, @Nullable OrderBy order, @Nullable Integer pageSizeHint, Row params, SubQueryResults subQueryResults) { ExecutionPlan sourcePlan = source.build( plannerContext, projectionBuilder, limit, offset, order, pageSizeHint, params, subQueryResults); if (applyCasts != null) { sourcePlan.addProjection(applyCasts); } var boundIndexWriterProjection = writeToTable .bind(x -> SubQueryAndParamBinder.convert(x, params, subQueryResults)); if (sourcePlan.resultDescription().hasRemainingLimitOrOffset()) { ExecutionPlan localMerge = Merge.ensureOnHandler(sourcePlan, plannerContext); localMerge.addProjection(boundIndexWriterProjection); return localMerge; } else { sourcePlan.addProjection(boundIndexWriterProjection); ExecutionPlan localMerge = Merge.ensureOnHandler(sourcePlan, plannerContext); if (sourcePlan != localMerge) { localMerge.addProjection(MergeCountProjection.INSTANCE); } return localMerge; } } ColumnIndexWriterProjection columnIndexWriterProjection() { return writeToTable; } @Override public List<Symbol> outputs() { return (List<Symbol>) writeToTable.outputs(); } @Override public List<AbstractTableRelation<?>> baseTables() { return Collections.emptyList(); } @Override public List<LogicalPlan> sources() { return List.of(source); } @Override public LogicalPlan replaceSources(List<LogicalPlan> sources) { return new Insert(Lists2.getOnlyElement(sources), writeToTable, applyCasts); } @Override public LogicalPlan pruneOutputsExcept(TableStats tableStats, Collection<Symbol> outputsToKeep) { LogicalPlan newSource = source.pruneOutputsExcept(tableStats, source.outputs()); if (newSource == source) { return this; } return replaceSources(List.of(newSource)); } @Override public Map<LogicalPlan, SelectSymbol> dependencies() { return source.dependencies(); } @Override public long numExpectedRows() { return 1; } @Override public long estimatedRowSize() { return source.estimatedRowSize(); } @Override public <C, R> R accept(LogicalPlanVisitor<C, R> visitor, C context) { return visitor.visitInsert(this, context); } @Override public StatementType type() { return StatementType.INSERT; } public Collection<Projection> projections() { if (applyCasts == null) { return List.of(writeToTable); } else { return List.of(applyCasts, writeToTable); } } }
EvilMcJerkface/crate
server/src/main/java/io/crate/planner/operators/Insert.java
Java
apache-2.0
5,454
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.sqs.model; import java.io.Serializable; import com.amazonaws.AmazonWebServiceRequest; /** * */ public class GetQueueUrlRequest extends AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the queue whose URL must be fetched. Maximum 80 characters; * alphanumeric characters, hyphens (-), and underscores (_) are allowed. * </p> */ private String queueName; /** * <p> * The AWS account ID of the account that created the queue. * </p> */ private String queueOwnerAWSAccountId; /** * Default constructor for GetQueueUrlRequest object. Callers should use the * setter or fluent setter (with...) methods to initialize the object after * creating it. */ public GetQueueUrlRequest() { } /** * Constructs a new GetQueueUrlRequest object. Callers should use the setter * or fluent setter (with...) methods to initialize any additional object * members. * * @param queueName * The name of the queue whose URL must be fetched. Maximum 80 * characters; alphanumeric characters, hyphens (-), and underscores * (_) are allowed. */ public GetQueueUrlRequest(String queueName) { setQueueName(queueName); } /** * <p> * The name of the queue whose URL must be fetched. Maximum 80 characters; * alphanumeric characters, hyphens (-), and underscores (_) are allowed. * </p> * * @param queueName * The name of the queue whose URL must be fetched. Maximum 80 * characters; alphanumeric characters, hyphens (-), and underscores * (_) are allowed. */ public void setQueueName(String queueName) { this.queueName = queueName; } /** * <p> * The name of the queue whose URL must be fetched. Maximum 80 characters; * alphanumeric characters, hyphens (-), and underscores (_) are allowed. * </p> * * @return The name of the queue whose URL must be fetched. Maximum 80 * characters; alphanumeric characters, hyphens (-), and underscores * (_) are allowed. */ public String getQueueName() { return this.queueName; } /** * <p> * The name of the queue whose URL must be fetched. Maximum 80 characters; * alphanumeric characters, hyphens (-), and underscores (_) are allowed. * </p> * * @param queueName * The name of the queue whose URL must be fetched. Maximum 80 * characters; alphanumeric characters, hyphens (-), and underscores * (_) are allowed. * @return Returns a reference to this object so that method calls can be * chained together. */ public GetQueueUrlRequest withQueueName(String queueName) { setQueueName(queueName); return this; } /** * <p> * The AWS account ID of the account that created the queue. * </p> * * @param queueOwnerAWSAccountId * The AWS account ID of the account that created the queue. */ public void setQueueOwnerAWSAccountId(String queueOwnerAWSAccountId) { this.queueOwnerAWSAccountId = queueOwnerAWSAccountId; } /** * <p> * The AWS account ID of the account that created the queue. * </p> * * @return The AWS account ID of the account that created the queue. */ public String getQueueOwnerAWSAccountId() { return this.queueOwnerAWSAccountId; } /** * <p> * The AWS account ID of the account that created the queue. * </p> * * @param queueOwnerAWSAccountId * The AWS account ID of the account that created the queue. * @return Returns a reference to this object so that method calls can be * chained together. */ public GetQueueUrlRequest withQueueOwnerAWSAccountId( String queueOwnerAWSAccountId) { setQueueOwnerAWSAccountId(queueOwnerAWSAccountId); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getQueueName() != null) sb.append("QueueName: " + getQueueName() + ","); if (getQueueOwnerAWSAccountId() != null) sb.append("QueueOwnerAWSAccountId: " + getQueueOwnerAWSAccountId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetQueueUrlRequest == false) return false; GetQueueUrlRequest other = (GetQueueUrlRequest) obj; if (other.getQueueName() == null ^ this.getQueueName() == null) return false; if (other.getQueueName() != null && other.getQueueName().equals(this.getQueueName()) == false) return false; if (other.getQueueOwnerAWSAccountId() == null ^ this.getQueueOwnerAWSAccountId() == null) return false; if (other.getQueueOwnerAWSAccountId() != null && other.getQueueOwnerAWSAccountId().equals( this.getQueueOwnerAWSAccountId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getQueueName() == null) ? 0 : getQueueName().hashCode()); hashCode = prime * hashCode + ((getQueueOwnerAWSAccountId() == null) ? 0 : getQueueOwnerAWSAccountId().hashCode()); return hashCode; } @Override public GetQueueUrlRequest clone() { return (GetQueueUrlRequest) super.clone(); } }
trasa/aws-sdk-java
aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/model/GetQueueUrlRequest.java
Java
apache-2.0
6,809
/* * $Id$ * This file is a part of the Arakhne Foundation Classes, http://www.arakhne.org/afc * * Copyright (c) 2000-2012 Stephane GALLAND. * Copyright (c) 2005-10, Multiagent Team, Laboratoire Systemes et Transports, * Universite de Technologie de Belfort-Montbeliard. * Copyright (c) 2013-2020 The original authors, and other 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.arakhne.afc.math.stochastic; import static org.arakhne.afc.testtools.XbaseInlineTestUtil.assertInlineParameterUsage; import org.junit.jupiter.api.Test; import org.arakhne.afc.testtools.AbstractTestCase; @SuppressWarnings("all") public class TriangularStochasticLawTest extends AbstractTestCase { @Test public void random() { assertInlineParameterUsage(TriangularStochasticLaw.class, "random", double.class, double.class, double.class); //$NON-NLS-1$ } }
gallandarakhneorg/afc
core/maths/mathstochastic/src/test/java/org/arakhne/afc/math/stochastic/TriangularStochasticLawTest.java
Java
apache-2.0
1,398
package com.ustwo.boilerplate.base; import android.app.Activity; import android.support.annotation.NonNull; import com.google.android.libraries.cloudtesting.screenshots.ScreenShotter; import com.squareup.spoon.Spoon; public class BaseUiTest { protected final void screenshot(@NonNull final Activity activity, @NonNull final String screenshotName) { try { Spoon.screenshot(activity, screenshotName); ScreenShotter.takeScreenshot(screenshotName, activity); } catch (final RuntimeException exception) { System.err.println("To capture screenshots run with spoon enabled"); } } }
ustwo/android-boilerplate
app/src/androidTest/java/com/ustwo/boilerplate/base/BaseUiTest.java
Java
apache-2.0
658
/* * Copyright 2015-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.rules; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import com.facebook.buck.cli.FakeBuckConfig; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.util.HumanReadableException; import com.google.common.base.Optional; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import org.junit.Test; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; public class RepositoryTest { @Test public void shouldReturnItselfIfRequestedToGetARepoWithAnAbsentOptionalName() throws IOException, InterruptedException { Repository repo = new TestRepositoryBuilder().build(); Repository target = repo.getRepository(Optional.<String>absent()); assertSame(repo, target); } @Test(expected = HumanReadableException.class) public void shouldThrowAnExceptionIfTheNamedRepoIsNotPresent() throws IOException, InterruptedException { Repository repo = new TestRepositoryBuilder().build(); repo.getRepository(Optional.of("not-there")); } @Test public void shouldResolveNamesOfReposAgainstThoseGivenInTheBuckConfig() throws IOException, InterruptedException { FileSystem vfs = Jimfs.newFileSystem(Configuration.unix()); Path root = vfs.getPath("/opt/local/"); Path repo1 = root.resolve("repo1"); Files.createDirectories(repo1); Path repo2 = root.resolve("repo2"); Files.createDirectories(repo2); ProjectFilesystem filesystem = new ProjectFilesystem(repo1.toAbsolutePath()); FakeBuckConfig config = new FakeBuckConfig( filesystem, "[repositories]", "example = " + repo2.toAbsolutePath().toString()); Repository repo = new TestRepositoryBuilder().setBuckConfig(config).setFilesystem( filesystem).build(); Repository other = repo.getRepository(Optional.of("example")); assertEquals(repo2, other.getFilesystem().getRootPath()); } }
dushmis/buck
test/com/facebook/buck/rules/RepositoryTest.java
Java
apache-2.0
2,636
/* * Copyright 2015 OpenCB * * 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.opencb.opencga.serverold; import org.opencb.commons.containers.QueryResult; import org.opencb.opencga.account.db.AccountManagementException; import org.opencb.opencga.account.io.IOManagementException; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.io.IOException; @Path("/account/{accountId}") public class AccountWSServer extends GenericWSServer { private String accountId; public AccountWSServer(@Context UriInfo uriInfo, @Context HttpServletRequest httpServletRequest, @DefaultValue("") @PathParam("accountId") String accountId) throws IOException, AccountManagementException { super(uriInfo, httpServletRequest); this.accountId = accountId; } @GET @Path("/create") public Response create(@DefaultValue("") @QueryParam("password") String password, @DefaultValue("") @QueryParam("name") String name, @DefaultValue("") @QueryParam("email") String email) throws IOException { QueryResult result; try { if (accountId.toLowerCase().equals("anonymous")) { result = cloudSessionManager.createAnonymousAccount(sessionIp); } else { result = cloudSessionManager.createAccount(accountId, password, name, email, sessionIp); } return createOkResponse(result); } catch (AccountManagementException | IOManagementException e) { logger.error(e.toString()); return createErrorResponse("could not create the account"); } } @GET @Path("/login") public Response login(@DefaultValue("") @QueryParam("password") String password) throws IOException { try { QueryResult result; if (accountId.toLowerCase().equals("anonymous")) { System.out.println("TEST ERROR accountId = " + accountId); result = cloudSessionManager.createAnonymousAccount(sessionIp); } else { result = cloudSessionManager.login(accountId, password, sessionIp); } return createOkResponse(result); } catch (AccountManagementException | IOManagementException e) { logger.error(e.toString()); return createErrorResponse("could not login"); } } @GET @Path("/logout") public Response logout() throws IOException { try { QueryResult result; if (accountId.toLowerCase().equals("anonymous")) { result = cloudSessionManager.logoutAnonymous(sessionId); } else { result = cloudSessionManager.logout(accountId, sessionId); } return createOkResponse(result); } catch (AccountManagementException | IOManagementException e) { logger.error(e.toString()); return createErrorResponse("could not logout"); } } @GET @Path("/info") public Response getInfoAccount(@DefaultValue("") @QueryParam("last_activity") String lastActivity) { try { QueryResult result = cloudSessionManager.getAccountInfo(accountId, lastActivity, sessionId); return createOkResponse(result); } catch (AccountManagementException e) { logger.error(accountId); logger.error(e.toString()); return createErrorResponse("could not get account information"); } } // @GET // @Path("/delete/") // public Response deleteAccount() { // try { // cloudSessionManager.deleteAccount(accountId, sessionId); // return createOkResponse("OK"); // } catch (AccountManagementException e) { // logger.error(e.toString()); // return createErrorResponse("could not delete the account"); // } // } // OLD // @GET // @Path("/pipetest/{accountId}/{password}") //Pruebas // public Response pipeTest(@PathParam("accountId") String // accountId,@PathParam("password") String password){ // return createOkResponse(userManager.testPipe(accountId, password)); // } // @GET // @Path("/getuserbyaccountid") // public Response getUserByAccountId(@QueryParam("accountid") String // accountId, // @QueryParam("sessionid") String sessionId) { // return createOkResponse(userManager.getUserByAccountId(accountId, // sessionId)); // } // // @GET // @Path("/getuserbyemail") // public Response getUserByEmail(@QueryParam("email") String email, // @QueryParam("sessionid") String sessionId) { // return createOkResponse(userManager.getUserByEmail(email, sessionId)); // } // @GET // @Path("/{accountId}/createproject") // public Response createProject(@PathParam("accountId") String accountId, // @QueryParam("project") Project project, @QueryParam("sessionId") String // sessionId){ // return createOkResponse(userManager.createProject(project, accountId, // sessionId)); // } // @GET // @Path("/createproject/{accountId}/{password}/{accountName}/{email}") // public Response register(@Context HttpServletRequest // httpServletRequest,@PathParam("accountId") String // accountId,@PathParam("password") String // password,@PathParam("accountName") String accountName, // @PathParam("email") String email){ // String IPaddr = httpServletRequest.getRemoteAddr().toString(); // String timeStamp; // SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); // Calendar calendar = Calendar.getInstance(); // Date now = calendar.getTime(); // timeStamp = sdf.format(now); // Session session = new Session(IPaddr); // // try { // userManager.insertUser(accountId,password,accountName,email,session); // } catch (AccountManagementException e) { // return createErrorResponse(e.toString()); // } // return createOkResponse("OK"); // } }
roalva1/opencga
opencga-server/src/main/java/org/opencb/opencga/serverold/AccountWSServer.java
Java
apache-2.0
6,653
package com.demievil.swiperefreshlayout; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.ActionBarActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends ActionBarActivity { private RefreshLayout mRefreshLayout; private ListView mListView; private ArrayAdapter<String> mArrayAdapter; private ArrayList<String> values; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRefreshLayout = (RefreshLayout) findViewById(R.id.swipe_container); mListView = (ListView) findViewById(R.id.list); mRefreshLayout.setFooterView(R.layout.listview_footer); values = new ArrayList<>(); for (int i = 0; i < 15; i++) { values.add("Item " + i); } mArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, values); mListView.setAdapter(mArrayAdapter); mRefreshLayout.setColorSchemeResources(R.color.google_blue, R.color.google_green, R.color.google_red, R.color.google_yellow); mRefreshLayout.setOnRefreshLoadMoreListener(new RefreshLayout.OnRefreshLoadMoreListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { values.add(0, "Swipe Down to Refresh " + values.size()); mArrayAdapter.notifyDataSetChanged(); mRefreshLayout.setRefreshing(false); } }, 2000); } @Override public void onLoadMore() { new Handler().postDelayed(new Runnable() { @Override public void run() { values.add("Swipe Up to Load More "+ values.size()); mArrayAdapter.notifyDataSetChanged(); mRefreshLayout.setLoading(false); } }, 2000); } }); } }
andforce/SwipeRefreshLayout
app/src/main/java/com/demievil/swiperefreshlayout/MainActivity.java
Java
apache-2.0
2,291
package com.gabrielavara.choiceplayer.beatport; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class BeatportReleaseDistance { private int albumDistance; private int artistDistance; public int getDistanceSum() { return albumDistance + artistDistance; } }
gabrielavara/music-player
src/main/java/com/gabrielavara/choiceplayer/beatport/BeatportReleaseDistance.java
Java
apache-2.0
322
/* * Copyright 2016 Marcel Piestansky (http://marpies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marpies.ane.gameanalytics.functions; import com.adobe.fre.FREContext; import com.adobe.fre.FREObject; import com.gameanalytics.sdk.GameAnalytics; import com.marpies.ane.gameanalytics.utils.FREObjectUtils; public class AddBusinessEventFunction extends BaseFunction { @Override public FREObject call( FREContext context, FREObject[] args ) { super.call( context, args ); String currency = FREObjectUtils.getString( args[0] ); int amount = FREObjectUtils.getInt( args[1] ); String itemType = FREObjectUtils.getString( args[2] ); String itemId = FREObjectUtils.getString( args[3] ); String cartType = FREObjectUtils.getString( args[4] ); String receipt = (args[5] == null) ? "" : FREObjectUtils.getString( args[5] ); String signature = (args[6] == null) ? "" : FREObjectUtils.getString( args[6] ); // args[7] is autoFetchReceipt used on iOS only GameAnalytics.addBusinessEventWithCurrency( currency, amount, itemType, itemId, cartType, receipt, "google_play", signature ); return null; } }
marpies/gameanalytics-ane
android/src/com/marpies/ane/gameanalytics/functions/AddBusinessEventFunction.java
Java
apache-2.0
1,650
package project.com.isly.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import project.com.isly.R; import project.com.isly.adapter.RecyclerAdapter; import project.com.isly.adapter.StudentsAdapter; import project.com.isly.helpers.DBH; import project.com.isly.models.Student; /** * Created by juan on 13/10/15. */ public class Statistics extends Fragment { ListView list_students; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.statistics,container,false); list_students=(ListView)v.findViewById(R.id.list_students); list_students.setAdapter(new StudentsAdapter(getActivity().getApplicationContext(), DBH.getActiveStudents(getActivity().getApplicationContext()))); return v; } }
juanortiz10/Isly
app/src/main/java/project/com/isly/fragments/Statistics.java
Java
apache-2.0
1,126
import javax.annotation.Nonnull; class Test { public static void test(@Nonnull Object... objects) { } public static void main(String[] args) { Object o = null; test(o); } }
consulo/consulo-java
java-impl/src/test/resources/inspection/dataFlow/fixture/PassingNullableIntoVararg.java
Java
apache-2.0
188
package ch.bfh.ti.sed.patmon1.ws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for getPatientsResponse complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="getPatientsResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="patients" type="{http://ch/bfh/ti/sed/patmon1/ws/}patientList" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "getPatientsResponse", propOrder = { "patients" }) public class GetPatientsResponse { protected PatientList patients; /** * Gets the value of the patients property. * * @return * possible object is * {@link PatientList } * */ public PatientList getPatients() { return patients; } /** * Sets the value of the patients property. * * @param value * allowed object is * {@link PatientList } * */ public void setPatients(PatientList value) { this.patients = value; } }
hip4/patmon1
src/ws/src/main/java/ch/bfh/ti/sed/patmon1/ws/GetPatientsResponse.java
Java
apache-2.0
1,412
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ package vnmr.lc; import java.util.*; import java.io.*; import lcaccess.*; import vnmr.ui.*; import vnmr.util.*; /** * A CORBA client that is used for talking to GPIB modules for LC. */ public class LcCorbaClient extends CorbaClient implements LcStatusListener { static private ArrayList<LcGpibModule> m_moduleTable = new ArrayList<LcGpibModule>(); static private int m_gpibAccessorState = ERROR_UNKNOWN; static protected LcControl m_control; static public final int MAX_GPIB_ADDRESS = 15; static public final String V9050_DETECTOR = "9050"; static public final String V9012_PUMP = "9012"; static public final int IDX_9050 = 0; static public final int IDX_9012 = 1; static public final int N_MODULES = 2; // Keep me updated // UPDATE ME: This arrray needs N_MODULES elements. static final private String[] m_moduleName = { "9050 Detector", "9012 Pump", }; public static final int PUMP_OFF = 0; public static final int PUMP_READY = 1; public static final int PUMP_RUNNING = 2; public static final int PUMP_STOPPED = 3; public static final int PUMP_NOT_READY = 4; public static final int PUMP_EQUILIBRATING = 5; public static final int PUMP_WAITING = 6; /** * This holds the handle of the one LcCorbaClient used by all modules. */ static private LcCorbaClient sm_gpibClientObject = null; private int m_pumpAddress = -1; private Thread[] m_threads = new Thread[MAX_GPIB_ADDRESS + 1]; private Set<LcStatusListener> m_pumpListenerList = new HashSet<LcStatusListener>(); private Set<LcStatusListener> m_detectorListenerList = new HashSet<LcStatusListener>(); private int[] m_corbaErrorType = new int[N_MODULES]; // Last downloaded methods private MethodLine[] m_uvMethod = null; private MethodLine[] m_pumpMethod = null; /** * Construct a "dead" version, just so that we can call methods * that could be static, if you could specify static methods * in an interface. */ public LcCorbaClient() { } /** * An LcCorbaClient factory method. * If the client is not already cached, creates it. * This method is synchronized so that only one client object can * get created. */ synchronized static public LcCorbaClient getClient(LcControl control, ButtonIF vif) { if (sm_gpibClientObject == null) { sm_gpibClientObject = new LcCorbaClient(control, vif); } return sm_gpibClientObject; } /** * Private constructor is only called through getClient(). * This is one client for all GPIB modules. */ private LcCorbaClient(LcControl control, ButtonIF vif) { super(vif); m_refPrefix = "gpib"; m_control = control; for (int i = 0; i < N_MODULES; ++i) { m_corbaErrorType[i] = ERROR_OK; } if (m_moduleTable.size() == 0) { initModuleTable(); } //initModuleTable(); //startStatusThreads(); } private boolean isEqualMethod(MethodLine[] m1, MethodLine[] m2) { if (m1 == null || m2 == null) { return false; } int n = m1.length; int m = m2.length; boolean rtn = (m == n); for (int i = 0; rtn && i < n; i++) { // TODO: It would be good if MethodLine.equals() were like this: rtn = ((m1[i].time == m2[i].time) && (m1[i].opCode == m2[i].opCode) && (m1[i].value == m2[i].value)); //rtn = m1[i].equals(m2[i]); } return rtn; } public UvDetector getDetector(String name) { return new Detector(m_expPanel, name); } /** * Gets a "dead" detector, just so that we can call methods * that could be static, if you could specify static methods * in an abstract class. */ public UvDetector getDetector() { return new Detector(m_expPanel); } /** * Start getting status from the pump. * In future, this should return an LC pump interface, so that * different pumps can be supported. See getDetector(). */ public void getPump(String name) { LcGpibModule[] ids = (LcGpibModule[])m_moduleTable.toArray(new LcGpibModule[0]); int address = 0; for (int i = 0; i < ids.length; i++) { if (ids[i].label.indexOf(name) >= 0) { address = ids[i].address; break; } } if (address > 0) { String cmd = "setStatusRate 60"; // Status reports / minute sendMessage(name, address, cmd); m_pumpAddress = address; } else { LcMsg.postError("No connection to " + name + " pump"); } } static public String getFileStatusMsg(int fstat) { // NB: These messages are taken verbatim from the Bear S/W switch (fstat) { default: return null; case 1: return "No Create File"; case 2: return "No Open File"; case 3: return "No Read File"; case 4: return "No Write File"; case 5: return "No Send File"; case 6: return "No Recv File"; case 7: return "Bad Table Name"; case 8: return "No Lock Table"; case 9: return "No Unlock Table"; case 10: return "No Erase Table"; case 11: return "No Read Table"; case 12: return "No Write Table"; case 13: return "Bad Method"; case 14: return "No Copy Method"; case 15: return "No Preset Method"; case 16: return "Bad Event Mask"; case 17: return "No Set Alarm"; case 18: return "No Clr Alarm"; case 19: return "Begin Transfer"; case 20: return "No Rewind"; case 21: return "Alarm Set"; case 22: return "Alarm Cleared"; case 23: return "Table Copied"; case 24: return "Table Preset"; case 25: return "Downloaded"; case 26: return "Uploaded"; case 27: return "No Send Request"; case 28: return "No First Status"; case 29: return "No Transfer"; case 30: return "No Second Status"; } } public boolean addPumpStatusListener(LcStatusListener listener) { return m_pumpListenerList.add(listener); } public boolean addDetectorStatusListener(LcStatusListener listener) { return m_detectorListenerList.add(listener); } public boolean removePumpStatusListener(LcStatusListener listener) { return m_pumpListenerList.remove(listener); } public void clearPumpStatusListeners() { m_pumpListenerList.clear(); } public boolean removeDetectorStatusListener(LcStatusListener listener) { return m_detectorListenerList.remove(listener); } private void notifyDetectorListeners(int fstatus, String msg) { Object[] oList = m_detectorListenerList.toArray(); for (int i = 0; i < oList.length; i++) { ((LcStatusListener)oList[i]).detectorFileStatusChanged(fstatus, msg); } } public void detectorFileStatusChanged(int status, String msg) { Messages.postDebug("DetectorStatus", "Detector File Status: " + msg); } private void notifyPumpListeners(Map<String, Object> state, int fstatus, String msg) { Object[] oList = m_pumpListenerList.toArray(); for (int i = 0; i < oList.length; i++) { if (fstatus >= 0) { ((LcStatusListener)oList[i]).pumpFileStatusChanged(fstatus, msg); } ((LcStatusListener)oList[i]).pumpStateChanged(state); } } public void pumpFileStatusChanged(int status, String msg) { Messages.postDebug("PumpStatus", "Pump File Status: " + msg); } /** * Dummy * @param state The new state of the pump. * */ public void pumpStateChanged(Map<String, Object> state) {} /** * Get a list of modules connected to the GPIB bus. * These are strings giving both the module name and the * GPIB address, similar to: * <br>"9050 Detector [01]" */ public String[] getModuleIds() { if (m_moduleTable.size() == 0) { initModuleTable(); } LcGpibModule[] ids = (LcGpibModule[])m_moduleTable.toArray(new LcGpibModule[0]); String[] labels = new String[ids.length]; String dets = ""; String pumps = ""; for (int i = 0; i < ids.length; i++) { labels[i] = ids[i].label; if (ids[i].type.equals("Detector")) { dets += "\"" + labels[i] + "\" " + ids[i].refName + "\n"; } else if (ids[i].type.equals("Pump")) { pumps += "\"" + labels[i] + "\" " + ids[i].refName + "\n"; } } if (dets.length() > 0) { String path = FileUtil.savePath("SYSTEM/ACQQUEUE/lcDetectors"); dets += "None none\n"; writeFile(path, dets); } if (pumps.length() > 0) { String path = FileUtil.savePath("SYSTEM/ACQQUEUE/lcPumps"); pumps += "None none\n"; writeFile(path, pumps); } return labels; } public boolean writeFile(String filepath, String content) { BufferedWriter fw = null; try { fw = new BufferedWriter(new FileWriter(filepath)); } catch (IOException ioe) { Messages.postError("Cannot open output file: " + filepath); return false; } PrintWriter pw = new PrintWriter(fw); pw.print(content); pw.close(); return true; } public void mainAccessorChanged() { startStatusThreads(); } public void startStatusThreads() { Messages.postDebug("gpibStatus", "startStatusThreads()"); if (m_moduleTable.size() == 0) { initModuleTable(); } String cmd = "setStatusRate 100"; LcGpibModule[] ids = (LcGpibModule[])m_moduleTable.toArray(new LcGpibModule[0]); Messages.postDebug("gpibStatus", "startStatusThreads(): " + "init'ed module table; got " + ids.length + " IDs"); String[] labels = new String[ids.length]; for (int i = 0; i < ids.length; i++) { Messages.postDebug("gpibStatus", "startStatusThreads(): id.label=" + ids[i].label); String label = ids[i].label; if (label.indexOf(V9050_DETECTOR) >= 0 || label.indexOf("310") >= 0) { //Messages.postDebug("gpibStatus", "Start 9050 status"); //send9050Message(ids[i].address, cmd); } else if (label.indexOf(V9012_PUMP) >= 0 || label.indexOf("230") >= 0) { Messages.postDebug("gpibStatus", "Start 9012 status"); send9012Message(ids[i].address, cmd); } } } protected Object getAccessor(String refName) { if (refName == null) { return null; } m_refPrefix = "gpib"; return super.getAccessor(refName); } //protected void invalidateAccessor(String refName) { // if (refName != null && ! refName.equals(GPIB_MODULES)) { // invalidateAccessor(GPIB_MODULES); // } // super.invalidateAccessor(refName); //} private void corbaOK(int idx) { if (m_corbaErrorType[idx] != ERROR_OK) { Messages.postInfo("... CORBA to " + m_moduleName[idx] + " is OK."); m_corbaErrorType[idx] = 0; } } private void corbaError(int idx, int type, String msg) { if (m_corbaErrorType[idx] != type) { m_corbaErrorType[idx] = type; String sType = ""; switch (type) { case ERROR_COMM_FAILURE: sType = "Communication failure"; break; case ERROR_NO_ACCESSOR: sType = "Initialization failure"; break; case ERROR_BAD_ADDRESS: sType = "Invalid GPIB address"; break; case ERROR_BAD_METHOD: sType = "Invalid method"; break; case ERROR_MISC_FAILURE: sType = "Unknown failure"; break; } Messages.postError("CORBA to " + m_moduleName[idx] + ": " + sType + " " + msg + " ..."); } } /** * Initialize info about what modules are connected to the GPIB. */ private void initModuleTable() { Messages.postDebug("gpibStatus", "LcCorbaClient.initModuleTable()"); // Force making new accessor //invalidateAccessor(GPIB_MODULES, ERROR_UNKNOWN); m_corbaOK = false; ModuleAccessor accessor = (ModuleAccessor)getAccessor(GPIB_MODULES); if (accessor == null) { if (m_gpibAccessorState != getAccessorState(GPIB_MODULES)) { m_gpibAccessorState = getAccessorState(GPIB_MODULES); Messages.postDebug("No communication with CORBA server"); } return; } m_moduleTable.clear(); for (int i = 1; i <= MAX_GPIB_ADDRESS; i++) { String name = null; javax.swing.Timer timer; timer = Messages.setTimeout(CORBA_CONNECT_TIMEOUT, "CORBA GPIB server not responding." + " Still trying ..."); try { Messages.postDebug(//"CorbaInit", "LcCorbaClient.initModuleTables: " + "getModuleName " + i + " from accessor ..."); name = accessor.getModuleName(i); Messages.postDebug(//"CorbaInit", "LcCorbaClient.initModuleTables: " + "... got name: " + name); if (! timer.isRunning()) { Messages.postInfo("... CORBA GPIB server OK"); } timer.stop(); corbaOK(); //if (! timer.isRunning()) { // Messages.postDebug("... CORBA GPIB server OK"); //} timer.stop(); m_corbaOK = true; } catch (org.omg.CORBA.COMM_FAILURE ccf) { timer.stop(); Messages.postError("CORBA communication failure"); corbaError(ERROR_COMM_FAILURE, ""); invalidateAccessor(GPIB_MODULES, ERROR_COMM_FAILURE); break; } catch (org.omg.CORBA.SystemException cse) { timer.stop(); Messages.postError("CORBA SystemException"); corbaError(ERROR_COMM_FAILURE, ""); invalidateAccessor(GPIB_MODULES, ERROR_COMM_FAILURE); break; } catch (Exception e) { Messages.postError("CORBA failed to connect: " + e); break; } finally { Messages.postDebug("*** initModuleTable: finally ***"); } Messages.postDebug("*** initModuleTable: after finally ***"); if (name != null && name.length() > 0) { m_moduleTable.add(new LcGpibModule(name, i)); } } } /** * Send a message to a given module */ public boolean sendMessage(String module, String msg) { if (V9012_PUMP.equals(module)) { return sendMessage(module, m_pumpAddress, msg); } return false; } /** * Send a message to a given module at a given GPIB address. */ public boolean sendMessage(String module, int address, String msg) { Messages.postDebug("gpibCmd", "LcCorbaClient.sendMessage(module=" + module + ", addr=" + address + ", msg=" + msg); boolean status = false; if (!m_corbaOK) { return false; } if (module == null) { Messages.postDebug("LcCorbaClient.sendMessage(): null module name"); status = false; } else if (module.equals(V9050_DETECTOR)) { status = send9050Message(address, msg); } else if (module.equals(V9012_PUMP)) { status = send9012Message(address, msg); } else { Messages.postDebug("LcCorbaClient.sendMessage(): Unknown module: " + module); status = false; } return status; } /** * Send a message to the 9050 detector at a given GPIB address. * <br>Messages: * <br>lampOn * <br>lampOff * <br>start * <br>stop * <br>reset * <br>activateMethod methodNumber * <br>setAttenuation value * <br>setStatusRate updatesPerMinute statusVariable * <br> * Setting the status rate to a non-zero value also starts a * separate thread that reads the status. */ private boolean send9050Message(int addr, String msg) { if (msg == null) { Messages.postDebug("LcCorbaClient.send9050Message():" + " Null message for detector"); return false; } if (addr <= 0 || addr > MAX_GPIB_ADDRESS) { Messages.postDebug("LcCorbaClient.send9050Message(): " + "Bad GPIB detector address: " + addr); return false; } String cmd = msg; StringTokenizer toker = new StringTokenizer(msg); if (toker.hasMoreTokens()) { cmd = toker.nextToken(); } boolean status = true; Detector9050 accessor = (Detector9050)getAccessor(V9050_DETECTOR); try { if (accessor == null) { Messages.postDebug("LcCorbaClient.send9050Message(): " + "No accessor for 9050 detector"); status = false; } else if (cmd.equals("lampOn")) { accessor.setLampOn(addr); } else if (cmd.equals("lampOff")) { accessor.setLampOff(addr); } else if (cmd.equals("start")) { accessor.start(addr); } else if (cmd.equals("stop")) { accessor.stop(addr); } else if (cmd.equals("reset")) { accessor.reset(addr); } else if (cmd.equals("autozero")) { accessor.autozero(addr); } else if (cmd.equals("activateMethod")) { if (toker.hasMoreTokens()) { int method = 0; try { method = Integer.parseInt(toker.nextToken()); accessor.activateMethod(addr, method); } catch (NumberFormatException nfe) { Messages.postDebug("LcCorbaClient.send9050Message(): " + "Garbled detector method number: " + msg); status = false; } catch (InvalidValueException ive) { Messages.postDebug("LcCorbaClient.send9050Message(): " + "Bad detector method number:" + msg); status = false; } } } else if (cmd.equals("setStatusRate")) { if (toker.hasMoreTokens()) { int rate = 0; // Updates per minute try { rate = Integer.parseInt(toker.nextToken()); // Sets rate remote server queries module for status accessor.requestStatus(addr, rate); } catch (NumberFormatException nfe) { Messages.postDebug("LcCorbaClient.send9050Message(): " + "Bad detector status rate string:" + msg); status = false; } catch (InvalidValueException ive) { Messages.postDebug("LcCorbaClient.send9050Message(): " + "Bad detector status rate value:" + msg); status = false; } Status9050Thread statusThread = (Status9050Thread)m_threads[addr]; String name = "uv"; if (toker.hasMoreTokens()) { name = toker.nextToken(); } if (rate == 0) { if (statusThread != null) { statusThread.setQuit(true); statusThread.interrupt(); m_threads[addr] = statusThread = null; } } else { int delay = (60 * 1000) / rate; if (statusThread == null) { statusThread = new Status9050Thread(delay, accessor, addr, name); statusThread.start(); m_threads[addr] = statusThread; } else { statusThread.setRate(delay); statusThread.interrupt(); } } } } else if (cmd.equals("downloadMethod")) { m_uvMethod = get9050Method(m_control.getCurrentMethod()); accessor.downloadMethod(addr, m_uvMethod); addDetectorStatusListener(this); } else { Messages.postDebug("Unknown " + V9050_DETECTOR + "detector command: \"" + msg + "\""); status = false; } corbaOK(IDX_9050); } catch (InvalidAddressException iae) { corbaError(IDX_9050, ERROR_BAD_ADDRESS, ""); invalidateAccessor(V9050_DETECTOR, ERROR_BAD_ADDRESS); status = false; } catch (InvalidMethodException ime) { Messages.postDebug("Invalid 9050 detector method"); corbaOK(IDX_9050); status = false; } catch (org.omg.CORBA.SystemException cse) { corbaError(IDX_9050, ERROR_COMM_FAILURE, ""); invalidateAccessor(V9050_DETECTOR, ERROR_COMM_FAILURE); status = false; } return status; } private MethodLine[] get9050Method(LcMethod method) { final int TIME_CONSTANT = 0; final int LAMBDA = 1; final int ATTENUATION = 2; final int AUTOZERO = 3; final int PEAK_WIDTH = 4; final int PEAK_RATIO = 5; final int PEAK_STATE = 6; final int RELAY_PERIOD = 7; final int RELAY_TRIGGER = 8; //final int PEAK_PULSE = 9; // Not used final int RELAYS = 10; final int END_TIME = 11; if (method == null) { return null; } ArrayList<MethodLine> alMethod = new ArrayList<MethodLine>(); alMethod.add(new MethodLine(0, TIME_CONSTANT, 1000)); alMethod.add(new MethodLine(0, LAMBDA, method.getLambda())); alMethod.add(new MethodLine(0, ATTENUATION, 100)); alMethod.add(new MethodLine(0, AUTOZERO, 0)); alMethod.add(new MethodLine(0, PEAK_WIDTH, 4)); alMethod.add(new MethodLine(0, PEAK_RATIO, 8)); alMethod.add(new MethodLine(0, PEAK_STATE, 1)); alMethod.add(new MethodLine(0, RELAY_PERIOD, 4)); alMethod.add(new MethodLine(0, RELAY_TRIGGER, 3)); alMethod.add(new MethodLine(0, RELAYS, 0)); int endTime = (int)(100 * method.getEndTime()); alMethod.add(new MethodLine(endTime, END_TIME, 0)); return alMethod.toArray(new MethodLine[0]); } /** * Send a message to the 9012 pump at a given GPIB address. * <br>Messages: * <br>purge * <br>prime * <br>pump * <br>start * <br>stop * <br>reset * <br>activateMethod methodNumber * <br>setStatusRate updatesPerMinute statusVariable * <br> * Setting the status rate to a non-zero value also starts a * separate thread that reads the status. */ private boolean send9012Message(int addr, String msg) { if (msg == null) { Messages.postDebug("LcCorbaClient.send9012Message():" + " Null message for pump"); return false; } if (addr <= 0 || addr > MAX_GPIB_ADDRESS) { Messages.postDebug("LcCorbaClient.send9012Message(): " + "Bad GPIB pump address: " + addr); return false; } String cmd = msg; StringTokenizer toker = new StringTokenizer(msg); if (toker.hasMoreTokens()) { cmd = toker.nextToken(); } boolean status = true; Pump9012 accessor = (Pump9012)getAccessor(V9012_PUMP); try { if (accessor == null) { Messages.postDebug("LcCorbaClient.send9012Message(): " + "No accessor for 9012 pump"); status = false; } else if (cmd.equals("pump")) { accessor.pump(addr); } else if (cmd.equals("start")) { accessor.start(addr); } else if (cmd.equals("stop")) { accessor.stop(addr); } else if (cmd.equals("reset")) { // NB: In general, takes 2 resets to reset completely accessor.reset(addr); accessor.reset(addr); } else if (cmd.equals("activateMethod")) { if (toker.hasMoreTokens()) { int method = 0; try { method = Integer.parseInt(toker.nextToken()); accessor.activateMethod(addr, method); } catch (NumberFormatException nfe) { Messages.postDebug("LcCorbaClient.send9012Message(): " + "Bad pump method number string:" + msg); status = false; } catch (InvalidValueException ive) { Messages.postDebug("LcCorbaClient.send9012Message(): " + "Bad pump method number:" + msg); status = false; } } } else if (cmd.equals("downloadMethod")) { m_pumpMethod = get9012Method(m_control.getCurrentMethod()); accessor.downloadMethod(addr, m_pumpMethod); addPumpStatusListener(this); } else if (cmd.equals("setStatusRate")) { if (toker.hasMoreTokens()) { int rate = 0; // Updates per minute try { rate = Integer.parseInt(toker.nextToken()); // Sets rate remote server queries module for status accessor.requestStatus(addr, rate); } catch (NumberFormatException nfe) { Messages.postDebug("LcCorbaClient.send9012Message(): " + "Bad pump status rate string:" + msg); status = false; } catch (InvalidValueException ive) { Messages.postDebug("LcCorbaClient.send9012Message(): " + "Bad pump status rate:" + msg); status = false; } Status9012Thread statusThread = getPumpStatusThread(addr); String name = "pump"; if (toker.hasMoreTokens()) { name = toker.nextToken(); } if (rate == 0) { if (statusThread != null) { statusThread.setQuit(true); statusThread.interrupt(); m_threads[addr] = statusThread = null; } } else { int delay = (60 * 1000) / rate; if (statusThread == null) { statusThread = new Status9012Thread(delay, accessor, addr, name); statusThread.start(); m_threads[addr] = statusThread; } else { statusThread.setRate(delay); statusThread.interrupt(); } } } } else { Messages.postDebug("Unknown " + V9012_PUMP + " pump command: \"" + msg + "\""); status = false; } corbaOK(IDX_9012); } catch (InvalidAddressException iae) { corbaError(IDX_9012, ERROR_BAD_ADDRESS, ""); invalidateAccessor(V9012_PUMP, ERROR_BAD_ADDRESS); status = false; } catch (InvalidMethodException ime) { Messages.postDebug("Invalid 9012 pump method"); corbaOK(IDX_9012); status = false; } catch (org.omg.CORBA.SystemException se) { corbaError(IDX_9012, ERROR_COMM_FAILURE, ""); invalidateAccessor(V9012_PUMP, ERROR_COMM_FAILURE); status = false; } return status; } public boolean isPumpDownloaded(LcMethod params) { MethodLine[] aMethod = get9012Method(params); return isEqualMethod(aMethod, m_pumpMethod); } /** * Get the status thread for the pump. * @return The status thread. */ private Status9012Thread getPumpStatusThread() { return getPumpStatusThread(m_pumpAddress); } /** * Get the status thread for the pump at the given GPIB address. * @param addr The GPIB address of the pump. * @return The status thread. */ private Status9012Thread getPumpStatusThread(int addr) { Status9012Thread thread = (Status9012Thread)m_threads[addr]; return thread; } public Map<String,Object> getPumpState() { return getPumpStatusThread().getPumpState(); } static public MethodLine[] get9012Method(LcMethod method) { final int PMAX = 0; final int PMIN = 1; final int RELAYS = 2; final int FLOW = 3; final int PERCENTS = 4; final int END_TIME = 5; final int EQUIL_TIME = 6; if (method == null) { return null; } ArrayList<MethodLine> alMethod = new ArrayList<MethodLine>(); alMethod.add(new MethodLine(0, PMAX, method.getMaxPressure())); alMethod.add(new MethodLine(0, PMIN, method.getMinPressure())); int relays = method.getInitialRelays(); alMethod.add(new MethodLine(0, RELAYS, relays)); int flow = (int)Math.round(1000 * method.getInitialFlow()); alMethod.add(new MethodLine(0, FLOW, flow)); double[] pct = method.getInitialPercents(); int pcts = (int)pct[2] | ((int)pct[1] << 8) | ((int)pct[0] << 16); alMethod.add(new MethodLine(0, PERCENTS, pcts)); int t = (int)(100 * method.getEquilTime()); alMethod.add(new MethodLine(0, EQUIL_TIME, t)); int endTime = (int)(100 * method.getEndTime()); int endAction = method.getEndAction().equals("pumpOff") ? Pump9012.ENDACTION_STOP : Pump9012.ENDACTION_HOLD; Messages.postDebug("lcPumpMethod", "Pump Method: " + "MaxPressure=" + Fmt.f(2, method.getMaxPressure()) + ", Min=" + Fmt.f(2, method.getMinPressure()) + ", Relays=" + Integer.toString(relays, 2) + ", Flow=" + Fmt.f(3, flow / 1000.0) + ", Pcts=" + Fmt.f(1, pct[0]) + ", " + Fmt.f(1, pct[1]) + ", " + Fmt.f(1, pct[2]) + ", Equil=" + Fmt.f(2, t / 100.0) ); int nRows = method.getRowCount(); for (int i = 1; i < nRows; i++) { int time = (int)(100 * method.getTime(i)); if (time < 0) { Messages.postDebug("LC method bad -- internal error"); return null; } else if (time > endTime) { Messages.postDebug("LC method has entries after end time"); break; } int r = method.getRelays(i); if (relays != r) { relays = r; alMethod.add(new MethodLine(time, RELAYS, relays)); Messages.postDebug("lcPumpMethod", "T=" + Fmt.f(2, time / 100.0) + ": relays=" + Integer.toString(relays, 2)); } // TODO: Not allowed to vary the flow for now. int f = (int)Math.round(1000 * method.getInitialFlow()); if (flow != f) { flow = f; alMethod.add(new MethodLine(time, FLOW, flow)); Messages.postDebug("lcPumpMethod", "T=" + Fmt.f(2, time / 100.0) + ": flow=" + Fmt.f(3, flow / 1000.0)); } pct = method.getPercents(i); if (pct != null) { pcts = (int)pct[2] | ((int)pct[1] << 8) | ((int)pct[0] << 16); alMethod.add(new MethodLine(time, PERCENTS, pcts)); Messages.postDebug("lcPumpMethod", "T=" + Fmt.f(2, time / 100.0) + ": Pcts=" + Fmt.f(1, pct[0]) + ", " + Fmt.f(1, pct[1]) + ", " + Fmt.f(1, pct[2])); } } alMethod.add(new MethodLine(endTime, END_TIME, endAction)); Messages.postDebug("lcPumpMethod", "T=" + Fmt.f(2, endTime / 100.0) + ", End action=" + (endAction == Pump9012.ENDACTION_STOP ? "stop" : "hold")); return alMethod.toArray(new MethodLine[0]); } /** * Get the object for calling methods for a given module. * @param refName The base name of the reference string for * the module, e.g. "9050". * @param corbaObj The CORBA Object for the reference string. * @return The object containing methods to call, or null on error. */ protected Object getAccessor(String refName, org.omg.CORBA.Object corbaObj) { Object accessor = null; try { if (refName == null) { return null; } else if (refName.equals("Access")) { accessor = ModuleAccessorHelper.narrow(corbaObj); } else if (refName.equals("9050")) { accessor = Detector9050Helper.narrow(corbaObj); } else if (refName.equals("9012")) { accessor = Pump9012Helper.narrow(corbaObj); } else { Messages.postDebug("LcCorbaClient.getAccessor(): No helper for " + refName); return null; } } catch (org.omg.CORBA.BAD_PARAM cbp) { Messages.postDebug("Cannot narrow CORBA accessor: " + cbp); } catch (org.omg.CORBA.COMM_FAILURE ccf) { Messages.postDebug("Cannot narrow CORBA accessor: " + ccf); } return accessor; } /** * Check if we have contact with the CORBA server. * @param status The previous access status: ACCESS_STATUS_OK * or ACCESS_STATUS_NO_CONTACT. * @return The current access status. */ protected int checkAccessStatus(int status) { ModuleAccessor accessor = (ModuleAccessor)getAccessor(GPIB_MODULES); if (accessor == null && status != ACCESS_STATUS_NO_CONTACT) { status = ACCESS_STATUS_NO_CONTACT; Messages.postError("No contact with CORBA server ..."); } else if (accessor != null) { try { accessor.getNumberOfConnectedModules(); corbaOK(); } catch (org.omg.CORBA.COMM_FAILURE cfe) { corbaError(ERROR_COMM_FAILURE, ""); invalidateAccessor(GPIB_MODULES, ERROR_COMM_FAILURE); } catch (org.omg.CORBA.SystemException cse) { corbaError(ERROR_MISC_FAILURE, ""); invalidateAccessor(GPIB_MODULES, ERROR_MISC_FAILURE); } finally { Messages.postDebug("LcCorbaClient", "*** StatusCorbaAccessThread: " + "in finally ***"); } Messages.postDebug("LcCorbaClient", "*** StatusCorbaAccessThread: " + "after finally ***"); } return status; } class Status9050Thread extends Thread { private int m_rate = 0; //private Detector9050 m_accessor = null; private int m_address = 0; private String m_statusName = ""; private volatile boolean m_quit = false; /** * @param rate Number of milliseconds between status queries. * @param accessor The CORBA accessor for the status requests. * @param address The GPIB address of the module . * @param statusName What to call this module in the status string. */ Status9050Thread(int rate, Detector9050 accessor, int address, String statusName) { m_rate = rate; //m_accessor = accessor; m_address = address > MAX_GPIB_ADDRESS ? 0 : Math.max(0, address); m_statusName = statusName; if (m_address == 0) { Messages.postDebug("LcCorbaClient.Status9050Thread.<init>: " + "Invalid GPIB detector address: " + address); } } public void setQuit(boolean quit) { m_quit = quit; } public void setRate(int rate) { m_rate = rate; } public synchronized void run() { boolean firstTime = true; int methodState = -1; int lampState = -1; int lambda = -1; int runtime = -1; double absorb = -1; int zero = -999999; long tZero = 0; int[] status = null; int fileStatus = -1; int[] fstatus = null; boolean lampOnOk = false; boolean lampOffOk = false; boolean autoZeroOk = false; boolean resetOk = false; boolean downloadOk = false; boolean startOk = false; boolean stopOk = false; if (m_address == 0) { return; // Can't deal with this } while (!m_quit) { try { Thread.sleep(m_rate); } catch (InterruptedException ie) { // This is OK } Detector9050 accessor = (Detector9050)getAccessor(V9050_DETECTOR); if (accessor == null) { continue; // Try again later } try { status = accessor.getLatestStatus(m_address); if (status == null) { Messages.postDebug("LcCorbaClient.Status9050Thread.run:" + " Detector status not available"); } else if (status.length < 24) { if (status.length == 0) { int updatesPerMinute = (60 * 1000) / m_rate; try { accessor.requestStatus(m_address, updatesPerMinute); } catch (InvalidValueException ive) { Messages.postDebug("Status9050Thread.run: " + "Bad status rate value:" + updatesPerMinute); m_rate = 1000; } } else { Messages.postDebug("LcCorbaClient.Status9050Thread:" + " Short detector status: " + status.length + " words"); } } else if (status.length > 35) { Messages.postDebug("LcCorbaClient.Status9050Thread.run:" + " Long detector status: " + status.length + " words"); } else { // Detector ID if (firstTime) { m_expPanel.processStatusData("uvId 310 / 9050"); m_expPanel.processStatusData("uvTitle UV"); firstTime = false; } // Lamp status if (lampState != status[9]) { lampState = status[9]; String state; switch (lampState) { case 0: state = "On"; break; case 1: state = "Starting"; break; case 2: state = "Off"; break; default: state = "LampState=" + lampState; break; } String msg = m_statusName + "LampStatus " + state; m_expPanel.processStatusData(msg); Messages.postDebug("gpibStatus", "gpibStatus: " + msg); } // Read run time if (runtime != status[29]) { runtime = status[29]; String msg = m_statusName + "Time " + (runtime / 100.0) + " min"; m_expPanel.processStatusData(msg); Messages.postDebug("gpibStatus", "gpibStatus: " + msg); } // Read wavelength { lambda = status[15]; String msg = m_statusName + "Lambda " + lambda + " nm"; m_expPanel.processStatusData(msg); Messages.postDebug("gpibStatus", "gpibStatus: " + msg); } // Check for auto zero if (status[17] != zero) { zero = status[17]; tZero = System.currentTimeMillis(); m_control.setUvOffset(); Messages.postDebug("Zero","zero=" + zero); } // Read absorption { String msg = m_statusName + "Attn "; if (status[23] > 2) { // Is detector ready? // NB: Cannot get absorption from CORBA. // Get latest value read from SLIM. if (tZero != 0 && System.currentTimeMillis() - tZero < 2000) { m_control.setUvOffset(); } absorb = m_control.getUvAbsorption(); msg += Fmt.f(4, absorb) + " AU"; } m_expPanel.processStatusData(msg); Messages.postDebug("lcAdc", "gpibStatus: " + msg); } // Read method status if (methodState != status[23]) { methodState = status[23]; String state; switch (methodState) { case 0: if (lampState == 1 || lampState == 2) { state = "Lamp_Off"; } else { state = "Not_Ready"; } break; case 1: state = "Initialize"; break; case 2: state = "Baseline"; break; case 3: state = "Ready"; break; case 4: state = "Run"; break; case 5: state = "Stop"; break; default: state = "State=" + methodState; break; } String msg = m_statusName + "Status " + state; m_expPanel.processStatusData(msg); Messages.postDebug("gpibStatus", "gpibStatus: " + msg); if (methodState >= 3) { m_expPanel.processStatusData(m_statusName + "LampOn true"); } else if (methodState == 0) { m_expPanel.processStatusData(m_statusName + "LampOn false"); } } } // Which actions are OK to do in the current state boolean ok = (methodState == 0 && lampState == 2); if (ok != lampOnOk) { lampOnOk = ok; m_expPanel.processStatusData("uvLampOnOk " + ok); } ok = (methodState == 3 || methodState == 5 || (methodState == 0 && lampState == 0)); if (ok != lampOffOk) { lampOffOk = ok; m_expPanel.processStatusData("uvLampOffOk " + ok); } //ok = (methodState == 3); ok = true; if (ok != autoZeroOk) { autoZeroOk = ok; m_expPanel.processStatusData("uvAutoZeroOk " + ok); } //ok = (methodState == 2 // || methodState == 3 // || methodState == 5); ok = true; if (ok != resetOk) { resetOk = ok; m_expPanel.processStatusData("uvResetOk " + ok); } ok = (methodState == 0 || methodState == 3 || methodState == 5); if (ok != downloadOk) { downloadOk = ok; m_expPanel.processStatusData("uvDownloadOk " + ok); } ok = (methodState == 3 || methodState == 5); if (ok != startOk) { startOk = ok; m_expPanel.processStatusData("uvStartOk " + ok); } ok = (methodState == 4); if (ok != stopOk) { stopOk = ok; m_expPanel.processStatusData("uvStopOk " + ok); } // Check the file status (result of method download) fstatus = accessor.getFileStatus(m_address); if (fstatus == null) { Messages.postDebug("LcCorbaClient.Status9050Thread.run:" + " Detector file status not found"); } else if (fstatus.length != 2) { Messages.postDebug("LcCorbaClient.Status9050Thread.run:" + " Detector file status bad length: " + fstatus.length + " words"); } else { if (fileStatus != fstatus[1]) { fileStatus = fstatus[1]; String msg = getFileStatusMsg(fileStatus); if (msg != null) { notifyDetectorListeners(fileStatus, msg); } } } corbaOK(IDX_9050); } catch (InvalidAddressException iae) { corbaError(IDX_9050, ERROR_BAD_ADDRESS, ""); invalidateAccessor(V9050_DETECTOR, ERROR_BAD_ADDRESS); } catch (org.omg.CORBA.SystemException se) { corbaError(IDX_9050, ERROR_COMM_FAILURE, ""); invalidateAccessor(V9050_DETECTOR, ERROR_COMM_FAILURE); } } // Reset status to "unknown"? } } class Status9012Thread extends Thread { private int m_rate = 0; //private Pump9012 m_accessor = null; private int m_address = 0; private String m_statusName = ""; private String m_sPcts = ""; private int m_pctA = -1; private int m_pctB = -1; private int m_pctC = -1; private int m_flow = -1; private volatile boolean m_quit = false; private Map<String, Object> state = new TreeMap<String, Object>(); /** * @param rate Number of milliseconds between status queries. * @param accessor The CORBA accessor for the status requests. * @param address The GPIB address of the module . * @param statusName What to call this module in the status string. */ Status9012Thread(int rate, Pump9012 accessor, int address, String statusName) { m_rate = rate; //m_accessor = accessor; m_address = address > MAX_GPIB_ADDRESS ? 0 : Math.max(0, address); m_statusName = statusName; if (m_address == 0) { Messages.postDebug("LcCorbaClient.Status9012Thread.<init>: " + "Invalid GPIB pump address: " + address); } } public Map<String, Object> getPumpState() { return state; } public void setQuit(boolean quit) { m_quit = quit; } public void setRate(int rate) { m_rate = rate; } public synchronized void run() { boolean firstTime = true; int methodState = -1; int pumpState = -1; int pressure = -1; int runtime = -1; int fileStatus = -1; int[] fstatus = null; int[] status = null; LcMsg.postDebug("gpibStatus", "LcCorbaClient.Status9012Thread.run()"); if (m_address == 0) { return; // Can't deal with this } while (!m_quit) { try { Thread.sleep(m_rate); } catch (InterruptedException ie) { // This is OK } Pump9012 accessor = (Pump9012)getAccessor(V9012_PUMP); if (accessor == null) { continue; // Try again later } boolean change = false; try { LcMsg.postDebug("gpibStatus", "LcCorbaClient.Status9012Thread: " + "get status"); status = accessor.getLatestStatus(m_address); if (DebugOutput.isSetFor("pumpStatus+")) { Messages.postDebug("Pump Status:"); for (int i = 0; i < status.length; i++) { System.out.println(i + "\t: " + status[i]); } } if (status == null) { Messages.postDebug("LcCorbaClient.Status9012Thread.run:" + " Pump status not available"); } else if (status.length < 16) { if (status.length == 0) { int updatesPerMinute = (60 * 1000) / m_rate; try { accessor.requestStatus(m_address, updatesPerMinute); } catch (InvalidValueException ive) { Messages.postDebug("Status9012Thread.run: " + "Bad status rate value:" + updatesPerMinute); m_rate = 1000; } } else { Messages.postDebug("LcCorbaClient.Status9012Thread:" + " Short pump status: " + status.length + " words"); } } else if (status.length > 27) { Messages.postDebug("LcCorbaClient.Status9012Thread.run:" + " Long pump status: " + status.length + " words"); } else { // Pump ID if (firstTime) { m_expPanel.processStatusData("pumpId 230 / 9012"); firstTime = false; } // Read run time if (runtime != status[19]) { runtime = status[19]; String msg = m_statusName + "Time " + Fmt.f(2, runtime / 100.0) + " min"; m_expPanel.processStatusData(msg); Messages.postDebug("gpibStatus", "gpibStatus: " + msg); } // Read pressure if (pressure != status[6]) { pressure = status[6]; String msg = m_statusName + "Press " + pressure + " atm"; m_expPanel.processStatusData(msg); state.put("pressure", new Double(pressure)); Messages.postDebug("gpibStatus", "gpibStatus: " + msg); } // Read flow rate if (m_flow != status[5] || pumpState != status[3]) { m_flow = status[5]; pumpState = status[3]; String msg = m_statusName + "Flow "; if (pumpState == 0) { msg += "Stopped"; } else { msg += (m_flow / 1000.0) + " mL/min"; } m_expPanel.processStatusData(msg); state.put("flow", new Integer(m_flow)); Messages.postDebug("gpibStatus", "gpibStatus: " + msg); // Send message for pump status msg = m_statusName + "Pump "; if (pumpState == 0) { msg += "Stopped"; } else if (pumpState == 1) { msg += "Running"; } else if (pumpState == 2) { msg += "Purging"; } else if (pumpState == 3) { msg += "Priming"; } m_expPanel.processStatusData(msg); Messages.postDebug("gpibStatus", "gpibStatus: " + msg); change = true; } // Read percents if (m_pctA != status[7]) { m_pctA = status[7]; String msg = m_statusName + "PctA " + m_pctA + " %A"; m_expPanel.processStatusData(msg); state.put("percentA", new Double(m_pctA)); change = true; } if (m_pctB != status[8]) { m_pctB = status[8]; String msg = m_statusName + "PctB " + m_pctB + " %B"; m_expPanel.processStatusData(msg); state.put("percentB", new Double(m_pctB)); change = true; } if (m_pctC != status[9]) { m_pctC = status[9]; String msg = m_statusName + "PctC " + m_pctC + " %C"; m_expPanel.processStatusData(msg); state.put("percentC", new Double(m_pctC)); change = true; } String sPcts = (m_statusName + "Pct " + m_pctA + "%A, " + m_pctB + "%B, " + m_pctC + "%C" + " " + (m_flow / 1000.0) + " mL/min" + " " + pressure + " atm"); if (!sPcts.equals(m_sPcts)) { m_sPcts = sPcts; m_expPanel.processStatusData(sPcts); } //Messages.postDebug("Pcts=" + m_sPcts); if (methodState != status[15]) { methodState = status[15]; state.put("state", new Integer(methodState)); change = true; String strMethodState; switch (methodState) { case PUMP_OFF: strMethodState = "Pump_Off"; break; case PUMP_READY: strMethodState = "Ready"; break; case PUMP_RUNNING: strMethodState = "Running"; break; case PUMP_STOPPED: strMethodState = "Stopped"; break; case PUMP_NOT_READY: strMethodState = "Not_Ready'"; break; case PUMP_EQUILIBRATING: strMethodState = "Equilibrate"; break; case PUMP_WAITING: strMethodState = "Waiting"; break; default: strMethodState = "State=" + methodState; break; } String msg = m_statusName + "Status " + strMethodState; m_expPanel.processStatusData(msg); Messages.postDebug("gpibStatus", "gpibStatus: " + msg); } } if (change) { notifyPumpListeners(state, -1, null); } // Check the file status (result of method download) fstatus = accessor.getFileStatus(m_address); if (fstatus == null) { Messages.postDebug("LcCorbaClient.Status9012Thread.run:" + " Pump File Status not available"); } else if (fstatus.length != 2) { Messages.postDebug("LcCorbaClient.Status9012Thread.run:" + " Pump File Status wrong length: " + fstatus.length + " words"); } else { if (fileStatus != fstatus[1]) { fileStatus = fstatus[1]; String msg = getFileStatusMsg(fileStatus); if (msg != null) { notifyPumpListeners(state, fileStatus, msg); } } } corbaOK(IDX_9012); } catch (InvalidAddressException iae) { corbaError(IDX_9012, ERROR_BAD_ADDRESS, ""); invalidateAccessor(V9012_PUMP, ERROR_BAD_ADDRESS); } catch (org.omg.CORBA.SystemException se) { corbaError(IDX_9012, ERROR_COMM_FAILURE, ""); invalidateAccessor(V9012_PUMP, ERROR_COMM_FAILURE); } //Thread.sleep(m_rate); } // Reset status to "unknown"? } } public class Detector extends UvDetector { /** GPIB address of detector. */ private int mm_gpibAddress = -1; /** Name of detector. */ private String mm_name = null; /** The time between status reports, in ms. */ private int mm_statusPeriod = 500; /** * Construct a "dead" version, just so that we can call methods * that could be static, if you could specify static methods * in an abstract class. */ public Detector(StatusManager manager) { super(manager); } /** * Normal constructor. Starts up status polling. */ public Detector(StatusManager manager, String name) { super(manager); LcGpibModule[] ids = (LcGpibModule[])m_moduleTable.toArray(new LcGpibModule[0]); for (int i = 0; i < ids.length; i++) { if (ids[i].label.indexOf(name) >= 0) { mm_gpibAddress = ids[i].address; mm_name = name; break; } } readStatus(mm_statusPeriod); // Start the status polling } /** * Return the name of this detector, typically the model number, as * a string. */ public String getName() { return mm_name; } /** * Read the status from the detector periodically. This will include * the absorption at selected wavelengths, if possible. These * wavelengths may be changed by downloadMethod(). * @param period The time between samples in ms. If 0, read status once. */ public boolean readStatus(int period) { mm_statusPeriod = period; int rate = period <= 0 ? 0 : 60000 / period; rate = Math.min(rate, 100); // Max rate is 100 / minute String cmd = "setStatusRate " + rate; return sendMessage(mm_name, mm_gpibAddress, cmd); } /** See if the detector is ready to start a run. */ public boolean isReady() { return true; // TODO: Implement isReady() } /** * Open communication with the detector. This just starts the * status polling, as communication is always possible unless * there is some problem. */ public boolean connect() { return readStatus(mm_statusPeriod); } /** * Shut down communication with the detector. * Just shuts down the status polling. */ public void disconnect() { readStatus(0); } /** Determine if detector communication is OK. */ public boolean isConnected() { return mm_gpibAddress > 0; } /** Turn on the lamp(s). */ public boolean lampOn() { return sendMessage(mm_name, mm_gpibAddress, "lampOn"); } /** Turn off the lamp(s). */ public boolean lampOff() { return sendMessage(mm_name, mm_gpibAddress, "lampOff"); } /** Make the current absorption the zero reference. */ public boolean autoZero() { return sendMessage(mm_name, mm_gpibAddress, "autozero"); } /** Download a (constant) run method with maximum run time. */ public boolean downloadMethod(LcMethod params) { // "parms" arg is not used, as "sendMessage" grabs the // methodEditor on its own. return sendMessage(mm_name, mm_gpibAddress, "downloadMethod"); } public boolean isDownloaded(LcMethod params) { if (m_uvMethod == null) { return false; } MethodLine[] aMethod = get9050Method(params); return isEqualMethod(aMethod, m_uvMethod); } /** * Start a run, if possible. */ public boolean start() { return sendMessage(mm_name, mm_gpibAddress, "start"); } /** * Stop a run and save data, continue monitoring selected * wavelength(s). */ public boolean stop() { return sendMessage(mm_name, mm_gpibAddress, "stop"); } /** Stop a run in such a way that it can be resumed. */ public boolean pause() { return sendMessage(mm_name, mm_gpibAddress, "stop"); } /** Restart a paused run. */ public boolean restart() { return sendMessage(mm_name, mm_gpibAddress, "start"); } /** Reset the detector state to be ready to start a new run. */ public boolean reset() { return sendMessage(mm_name, mm_gpibAddress, "reset"); } /** * Selects who deals with the data. * @return Returns false, as data * must be retrieved through the analog-output. */ public boolean setDataListener(LcDataListener listener) { return false; } /** * Selects channels and wavelengths to monitor for the chromatogram. * @return Returns "false", as data is only available through * the analog output. */ public boolean setChromatogramChannels(float[] lambdas, int[] traces, LcRun chromatogramManager) { return false; } /** * Gets the interval between data points. Since this detector * interface does not support direct return of data, returns 0. * @return Zero, indicating data obtained only through ADC. */ public int getDataInterval() { return 0; } /** * Get the string that uniquely identifies this detector type to the * software. * @return Returns "9050". */ public String getCanonicalIdString() { return "9050"; } /** * Get the label shown to the user to identify the detector type. * @return Returns "335 PDA". */ public String getIdString() { return "310/9050 UV-Vis"; } /** * Get the wavelength range this type of detector is good for. * @return Two ints, the min and max wavelengths, respectively, in nm. */ public int[] getMaxWavelengthRange() { int[] rtn = {200, 800}; return rtn; } /** * @return Returns false, since this detector cannot return spectra. */ public boolean isPda() { return false; } /** * The number of "monitor" wavelengths this detector can support. * These may be monitored either from getting status or from * reading an analog-out value, but must be obtainable outside * of a run. * @return Returns 1. */ public int getNumberOfMonitorWavelengths() { return 1; } /** * The number of "analog outputs" this detector supports, and * that we want the software to support. * @return Returns 1; the analog output is supported. */ public int getNumberOfAnalogChannels() { return 1; } } }
OpenVnmrJ/OpenVnmrJ
src/vnmrj/src/vnmr/lc/LcCorbaClient.java
Java
apache-2.0
73,019
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ package vnmr.bo; public interface VObjDef { static final int TYPE = 1; static final int LABEL = 2; static final int FGCOLOR = 3; static final int BGCOLOR = 4; static final int VARIABLE = 5; // VNMR variables static final int CMD = 6; static final int CMD2 = 7; static final int SHOW = 8; // show condition static final int FONT_NAME = 9; static final int FONT_STYLE = 10; static final int FONT_SIZE = 11; static final int SETVAL = 12; // commmand to set value static final int SETCHOICE = 13; static final int SETCHVAL = 14; // choice value static final int VALUE = 15; static final int CHOICE = 16; static final int CHVAL = 17; static final int DIGITAL = 18; // show digital readout on dial static final int MIN = 19; // Minimum value on dial, slider, etc. static final int MAX = 20; // Maximum value on dial, slider, etc. static final int SHOWMIN = 21; // Show min marker on dial static final int SHOWMAX = 22; // Show max marker on dial static final int INCR1 = 23; // Size of increment to change value static final int INCR2 = 24; // Alt size of increment to change value static final int STATPAR = 25; // Status parameter to display static final int EDITABLE = 26; // for textArea static final int VALUES = 27; // values list static final int PANEL_TAB = 28; static final int PANEL_NAME = 29; static final int PANEL_FILE = 30; static final int PANEL_PARAM = 31; static final int ACTION_FILE = 32; static final int BORDER = 33; // Type of border to draw static final int SIDE = 34; // Which side to put label static final int JUSTIFY = 35; // Justification mode static final int TAB = 36; // Whether to use this as an index tab static final int SAVEKIDS = 37; // Whether to save children in XML static final int VAR2 = 38; // Alt Vnmr variable list static final int SETVAL2 = 39; // Alt command to set value static final int NUMDIGIT = 40; // number of digits static final int TITLE = 41; // title string static final int STATKEY = 42; // status key variable static final int STATSET = 43; // status set variable static final int STATCOL = 44; // set status color to background static final int ENABLED = 45; // enable expression for buttons etc. static final int POINTY = 46; // for shim buttons static final int ROCKER = 47; // for shim buttons static final int ARROW = 48; // for shim buttons static final int ARROW_COLOR = 49; // for shim buttons static final int ORIENTATION = 50; static final int COUNT = 51; static final int COLOR1 = 52; static final int COLOR2 = 53; static final int COLOR3 = 54; static final int STATVAL = 55; // Status values that select static final int STATSHOW = 56; // Status values that enable static final int PANEL_TYPE = 57; // panel type code (acquisition etc) static final int KEYSTR = 58; // search key static final int KEYVAL = 59; // search key value static final int ICON = 60; // icon static final int ENABLE = 61; // enable expression static final int VISIBLE = 62; // visible expression static final int ELASTIC = 63; // Autoscale range of display static final int RADIOBUTTON = 64; // Manage as part of button group static final int DISPLAY = 65; // display options static final int REFERENCE = 66; // reference file static final int USEREF = 67; // use reference file static final int HOTKEY = 68; // accelerator key static final int IMAGEORLABEL = 69; static final int SET_VC = 70; static final int TOOL_TIP = 71; // toolTip static final int JOINPTS = 72; // for joining the points in scatter plot. static final int FILLHISTGM = 73; // for filling the histogram. static final int POINTSIZE = 74; // size of the points in scatter plot. static final int DISABLE = 75; // style of disable: grayed out or label. static final int LCVARIABLE = 76; // variable for the left histogram cursor. static final int RCVARIABLE = 77; // variable for the right histogram cursor. static final int LCSETVAL = 78; // set value of the left histogram cursor. static final int RCSETVAL = 79; // set value of the right histogram cursor. static final int LCCMD = 80; // for the cmd for the left histogram cursor. static final int RCCMD = 81; // for the cmd for the right histogram cursor. static final int LCCMD2 = 82; // for the cmd2 for the left histogram cursor. static final int RCCMD2 = 83; // for the cmd2 for the right histogram cursor. static final int LCCMD3 = 84; // for the cmd3 for the left histogram cursor. static final int RCCMD3 = 85; // for the cmd3 for the right histogram cursor. static final int LCVAL = 86; // value of variable of left histogram cursor. static final int RCVAL = 87; // value of variable of right histogram cursor. static final int LCSHOW = 88; // show condition of left histogram cursor. static final int RCSHOW = 89; // show condition of right histogram cursor. static final int LCCOLOR = 90; // color of the left cursor of the histogram. static final int RCCOLOR = 91; // color of the right cursor of the histogram. static final int GRAPHBGCOL = 92; // color of the background of the canvas. static final int GRAPHFGCOL = 93; // color of the foreground of the canvas. static final int XAXISSHOW = 94; static final int YAXISSHOW = 95; static final int XLABELSHOW = 96; static final int YLABELSHOW = 97; static final int LOGXAXIS = 98; static final int LOGYAXIS = 99; static final int SHOWGRID = 100; static final int RANGE = 101; static final int GRIDCOLOR = 102; static final int TICKCOLOR = 103; static final int SUBTYPE = 104; static final int TABLED = 105; static final int LAYOUT = 106; static final int GRAPHFGCOL2 = 107; // Second data color for graphs static final int GRAPHFGCOL3 = 108; // Third data color for graphs static final int KEYWORD = 109; static final int PATH1 = 110; static final int PATH2 = 111; static final int WRAP = 112; static final int EXPANDED = 113; static final int DRAG = 114; static final int SIZE1 = 115; static final int SIZE2 = 116; static final int UNITS = 117; static final int ROW = 118; // number of rows for the gridlayout static final int COLUMN = 119; // number of columns for the gridlayout static final int PREFIX = 120; static final int COLOR4 = 121; static final int COLOR5 = 122; static final int COLOR6 = 123; static final int COLOR7 = 124; static final int COLOR8 = 125; static final int COLOR9 = 126; static final int COLOR10 = 127; static final int COLOR11 = 128; static final int COLOR12 = 129; static final int COLOR13 = 130; static final int COLOR14 = 131; static final int COLOR15 = 132; static final int DECOR1 = 133; static final int DECOR2 = 134; static final int DECOR3 = 135; static final int SEPERATOR = 136; static final int HALIGN = 137; // horizontalAlignment static final int VALIGN = 138; // verticalAlignment static final int ANNOTATION = 139; static final int DOCKAT = 140; static final int LOCX = 141; // the ratio of width static final int LOCY = 142; // the ratio of height static final int PSFONT = 143; // the PostScript font static final int PSSIZE = 144; // the PostScript font size static final int CHECKENABLED = 145; static final int CHECKVALUE = 146; static final int CHECKCMD = 147; static final int CHECKCMD2 = 148; static final int ENTRYVALUE = 149; static final int ENTRYCMD = 150; static final int ENTRYSIZE = 151; static final int UNITSENABLED = 152; static final int UNITSLABEL = 153; static final int UNITSVALUE = 154; static final int UNITSCMD = 155; static final int UNITSSIZE = 156; static final int COLUMNS = 157; // the number of columns of table static final int ROWS = 158; // the number of rows of table static final int GRAPHBGCOL2 = 159; // Alternate background for canvas static final int OBJID = 160; // the id of obj static final int CHECKMARK = 161; static final int CHECKOBJ = 162; static final int SHOWOBJ = 163; static final int ACTIONCMD = 164; // Command for Java ActionListener static final int TRACKVIEWPORT = 165; // Always talk to active viewport static final int SETINCREMENTS = 166; // Set shim button increment static final int TOOLTIP = 167; // tooltip static final int HELPLINK = 168; // help static final int GRID_COLUMN = 169; // grid-column static final int GRID_ROW = 170; // grid-row static final int GRID_XSPAN = 171; // grid-column-span static final int GRID_YSPAN = 172; // grid-row-span static final int GRID_ROWALIGN = 173; // grid-row-align static final int STRETCH = 174; // stretch static final int LABELVARIABLE = 175; static final int LABELVALUE = 176; static final int SQUISH = 177; // squish static final int MODALCLOSE = 178; // modalclose }
OpenVnmrJ/OpenVnmrJ
src/vnmrj/src/vnmr/bo/VObjDef.java
Java
apache-2.0
9,414
/* * This file is part of the CVSS Calculator. * * 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 us.springett.cvss; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class CvssV2Test { private CvssV2 cvssV2; private CvssV2 cvssV2Temporal; @Before public void setup() { cvssV2 = new CvssV2() .attackVector(CvssV2.AttackVector.NETWORK) .attackComplexity(CvssV2.AttackComplexity.MEDIUM) .authentication(CvssV2.Authentication.NONE) .confidentiality(CvssV2.CIA.PARTIAL) .integrity(CvssV2.CIA.PARTIAL) .availability(CvssV2.CIA.PARTIAL); cvssV2Temporal = new CvssV2() .attackVector(CvssV2.AttackVector.NETWORK) .attackComplexity(CvssV2.AttackComplexity.HIGH) .authentication(CvssV2.Authentication.NONE) .confidentiality(CvssV2.CIA.PARTIAL) .integrity(CvssV2.CIA.NONE) .availability(CvssV2.CIA.NONE) .exploitability(CvssV2.Exploitability.FUNCTIONAL) .remediationLevel(CvssV2.RemediationLevel.WORKAROUND) .reportConfidence(CvssV2.ReportConfidence.CONFIRMED); } @Test public void attackVectorTest() { cvssV2.attackVector(CvssV2.AttackVector.NETWORK); Score score = cvssV2.calculateScore(); Assert.assertEquals(6.8, score.getBaseScore(), 0); Assert.assertEquals(6.4, score.getImpactSubScore(), 0); Assert.assertEquals(8.6, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:N/C:P/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.AttackVector.NETWORK, cvssV2.getAttackVector()); cvssV2.attackVector(CvssV2.AttackVector.ADJACENT); score = cvssV2.calculateScore(); Assert.assertEquals(5.4, score.getBaseScore(), 0); Assert.assertEquals(6.4, score.getImpactSubScore(), 0); Assert.assertEquals(5.5, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:A/AC:M/Au:N/C:P/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.AttackVector.ADJACENT, cvssV2.getAttackVector()); cvssV2.attackVector(CvssV2.AttackVector.LOCAL); score = cvssV2.calculateScore(); Assert.assertEquals(4.4, score.getBaseScore(), 0); Assert.assertEquals(6.4, score.getImpactSubScore(), 0); Assert.assertEquals(3.4, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:L/AC:M/Au:N/C:P/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.AttackVector.LOCAL, cvssV2.getAttackVector()); } @Test public void attackComplexityTest() { cvssV2.attackComplexity(CvssV2.AttackComplexity.LOW); Score score = cvssV2.calculateScore(); Assert.assertEquals(7.5, score.getBaseScore(), 0); Assert.assertEquals(6.4, score.getImpactSubScore(), 0); Assert.assertEquals(10.0, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:L/Au:N/C:P/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.AttackComplexity.LOW, cvssV2.getAttackComplexity()); cvssV2.attackComplexity(CvssV2.AttackComplexity.MEDIUM); score = cvssV2.calculateScore(); Assert.assertEquals(6.8, score.getBaseScore(), 0); Assert.assertEquals(6.4, score.getImpactSubScore(), 0); Assert.assertEquals(8.6, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:N/C:P/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.AttackComplexity.MEDIUM, cvssV2.getAttackComplexity()); cvssV2.attackComplexity(CvssV2.AttackComplexity.HIGH); score = cvssV2.calculateScore(); Assert.assertEquals(5.1, score.getBaseScore(), 0); Assert.assertEquals(6.4, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.AttackComplexity.HIGH, cvssV2.getAttackComplexity()); } @Test public void authenticationTest() { cvssV2.authentication(CvssV2.Authentication.NONE); Score score = cvssV2.calculateScore(); Assert.assertEquals(6.8, score.getBaseScore(), 0); Assert.assertEquals(6.4, score.getImpactSubScore(), 0); Assert.assertEquals(8.6, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:N/C:P/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.Authentication.NONE, cvssV2.getAuthentication()); cvssV2.authentication(CvssV2.Authentication.SINGLE); score = cvssV2.calculateScore(); Assert.assertEquals(6.0, score.getBaseScore(), 0); Assert.assertEquals(6.4, score.getImpactSubScore(), 0); Assert.assertEquals(6.8, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:S/C:P/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.Authentication.SINGLE, cvssV2.getAuthentication()); cvssV2.authentication(CvssV2.Authentication.MULTIPLE); score = cvssV2.calculateScore(); Assert.assertEquals(5.4, score.getBaseScore(), 0); Assert.assertEquals(6.4, score.getImpactSubScore(), 0); Assert.assertEquals(5.5, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:M/C:P/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.Authentication.MULTIPLE, cvssV2.getAuthentication()); } @Test public void confidentialityTest() { cvssV2.confidentiality(CvssV2.CIA.NONE); Score score = cvssV2.calculateScore(); Assert.assertEquals(5.8, score.getBaseScore(), 0); Assert.assertEquals(4.9, score.getImpactSubScore(), 0); Assert.assertEquals(8.6, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:N/C:N/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.CIA.NONE, cvssV2.getConfidentiality()); cvssV2.confidentiality(CvssV2.CIA.PARTIAL); score = cvssV2.calculateScore(); Assert.assertEquals(6.8, score.getBaseScore(), 0); Assert.assertEquals(6.4, score.getImpactSubScore(), 0); Assert.assertEquals(8.6, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:N/C:P/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.CIA.PARTIAL, cvssV2.getConfidentiality()); cvssV2.confidentiality(CvssV2.CIA.COMPLETE); score = cvssV2.calculateScore(); Assert.assertEquals(8.3, score.getBaseScore(), 0); Assert.assertEquals(8.5, score.getImpactSubScore(), 0); Assert.assertEquals(8.6, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:N/C:C/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.CIA.COMPLETE, cvssV2.getConfidentiality()); } @Test public void integrityTest() { cvssV2.integrity(CvssV2.CIA.NONE); Score score = cvssV2.calculateScore(); Assert.assertEquals(5.8, score.getBaseScore(), 0); Assert.assertEquals(4.9, score.getImpactSubScore(), 0); Assert.assertEquals(8.6, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:N/C:P/I:N/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.CIA.NONE, cvssV2.getIntegrity()); cvssV2.integrity(CvssV2.CIA.PARTIAL); score = cvssV2.calculateScore(); Assert.assertEquals(6.8, score.getBaseScore(), 0); Assert.assertEquals(6.4, score.getImpactSubScore(), 0); Assert.assertEquals(8.6, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:N/C:P/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.CIA.PARTIAL, cvssV2.getIntegrity()); cvssV2.integrity(CvssV2.CIA.COMPLETE); score = cvssV2.calculateScore(); Assert.assertEquals(8.3, score.getBaseScore(), 0); Assert.assertEquals(8.5, score.getImpactSubScore(), 0); Assert.assertEquals(8.6, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:N/C:P/I:C/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.CIA.COMPLETE, cvssV2.getIntegrity()); } @Test public void availabilityTest() { cvssV2.availability(CvssV2.CIA.NONE); Score score = cvssV2.calculateScore(); Assert.assertEquals(5.8, score.getBaseScore(), 0); Assert.assertEquals(4.9, score.getImpactSubScore(), 0); Assert.assertEquals(8.6, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:N/C:P/I:P/A:N)", cvssV2.getVector()); Assert.assertEquals(CvssV2.CIA.NONE, cvssV2.getAvailability()); cvssV2.availability(CvssV2.CIA.PARTIAL); score = cvssV2.calculateScore(); Assert.assertEquals(6.8, score.getBaseScore(), 0); Assert.assertEquals(6.4, score.getImpactSubScore(), 0); Assert.assertEquals(8.6, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:N/C:P/I:P/A:P)", cvssV2.getVector()); Assert.assertEquals(CvssV2.CIA.PARTIAL, cvssV2.getAvailability()); cvssV2.availability(CvssV2.CIA.COMPLETE); score = cvssV2.calculateScore(); Assert.assertEquals(8.3, score.getBaseScore(), 0); Assert.assertEquals(8.5, score.getImpactSubScore(), 0); Assert.assertEquals(8.6, score.getExploitabilitySubScore(), 0); Assert.assertEquals(null, "(AV:N/AC:M/Au:N/C:P/I:P/A:C)", cvssV2.getVector()); Assert.assertEquals(CvssV2.CIA.COMPLETE, cvssV2.getAvailability()); } @Test public void temporalTestExploitability() { Score score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.3, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:F/RL:W/RC:C)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.Exploitability.FUNCTIONAL, cvssV2Temporal.getExploitability()); cvssV2Temporal.exploitability(CvssV2.Exploitability.HIGH); score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.5, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:H/RL:W/RC:C)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.Exploitability.HIGH, cvssV2Temporal.getExploitability()); cvssV2Temporal.exploitability(CvssV2.Exploitability.UNPROVEN); score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.1, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:U/RL:W/RC:C)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.Exploitability.UNPROVEN, cvssV2Temporal.getExploitability()); cvssV2Temporal.exploitability(CvssV2.Exploitability.POC); score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.2, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:POC/RL:W/RC:C)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.Exploitability.POC, cvssV2Temporal.getExploitability()); cvssV2Temporal.exploitability(CvssV2.Exploitability.NOT_DEFINED); score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.5, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:ND/RL:W/RC:C)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.Exploitability.NOT_DEFINED, cvssV2Temporal.getExploitability()); } @Test public void temporalTestRemediation() { Score score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.3, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:F/RL:W/RC:C)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.RemediationLevel.WORKAROUND, cvssV2Temporal.getRemediationLevel()); cvssV2Temporal.remediationLevel(CvssV2.RemediationLevel.UNAVAILABLE); score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.5, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:F/RL:U/RC:C)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.RemediationLevel.UNAVAILABLE, cvssV2Temporal.getRemediationLevel()); cvssV2Temporal.remediationLevel(CvssV2.RemediationLevel.TEMPORARY); score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.2, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:F/RL:TF/RC:C)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.RemediationLevel.TEMPORARY, cvssV2Temporal.getRemediationLevel()); cvssV2Temporal.remediationLevel(CvssV2.RemediationLevel.OFFICIAL); score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.1, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:F/RL:OF/RC:C)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.RemediationLevel.OFFICIAL, cvssV2Temporal.getRemediationLevel()); cvssV2Temporal.remediationLevel(CvssV2.RemediationLevel.NOT_DEFINED); score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.5, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:F/RL:ND/RC:C)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.RemediationLevel.NOT_DEFINED, cvssV2Temporal.getRemediationLevel()); } @Test public void temporalTestReportConfidence() { Score score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.3, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:F/RL:W/RC:C)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.ReportConfidence.CONFIRMED, cvssV2Temporal.getReportConfidence()); cvssV2Temporal.reportConfidence(CvssV2.ReportConfidence.UNCORROBORATED); score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.2, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:F/RL:W/RC:UR)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.ReportConfidence.UNCORROBORATED, cvssV2Temporal.getReportConfidence()); cvssV2Temporal.reportConfidence(CvssV2.ReportConfidence.UNCONFIRMED); score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.1, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:F/RL:W/RC:UC)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.ReportConfidence.UNCONFIRMED, cvssV2Temporal.getReportConfidence()); cvssV2Temporal.reportConfidence(CvssV2.ReportConfidence.NOT_DEFINED); score = cvssV2Temporal.calculateScore(); Assert.assertEquals(2.6, score.getBaseScore(), 0); Assert.assertEquals(2.9, score.getImpactSubScore(), 0); Assert.assertEquals(4.9, score.getExploitabilitySubScore(), 0); Assert.assertEquals(2.3, score.getTemporalScore(), 0); Assert.assertEquals(null, "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:F/RL:W/RC:ND)", cvssV2Temporal.getVector()); Assert.assertEquals(CvssV2.ReportConfidence.NOT_DEFINED, cvssV2Temporal.getReportConfidence()); } @Test public void testRegexPattern() { // Without temporal vector elements String cvss2Vector = "(AV:N/AC:H/Au:N/C:P/I:N/A:N)"; Cvss cvssV2 = Cvss.fromVector(cvss2Vector); Assert.assertNotNull(cvssV2); Assert.assertEquals(cvss2Vector, cvssV2.getVector()); // With temporal vector elements cvss2Vector = "(AV:N/AC:H/Au:N/C:P/I:N/A:N/E:F/RL:W/RC:ND)"; cvssV2 = Cvss.fromVector(cvss2Vector); Assert.assertNotNull(cvssV2); Assert.assertEquals(cvss2Vector, cvssV2.getVector()); } }
stevespringett/cvss-calculator
src/test/java/us/springett/cvss/CvssV2Test.java
Java
apache-2.0
19,262
package org.divy.sonar.hybris.java.checks; import org.sonar.java.checks.verifier.JavaCheckVerifier; // Compliant import de.hybris.platform.servicelayer.user.userservice; // Noncompliant {{Refactor Controller to use facade instead of service directly}} public class ServiceLowerCaseUsageTestSampleController { userservice classMemberService; // Noncompliant {{Refactor Controller to use facade instead of service directly}} void nonCompliantMethod() { userservice userService; // Noncompliant {{Refactor Controller to use facade instead of service directly}} } void compliantMethod() { JavaCheckVerifier localJavaCheckVerifier; // Compliant } }
divyakumarjain/sonar-hybris-plugin
src/test/files/controller/ServiceLowerCaseUsageTestSampleController.java
Java
apache-2.0
676
package br.ufpe.activiti.behaviour.ciclo.mapek; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.deckfour.xes.model.XLog; import br.ufpe.activiti.behaviour.gestaoLTL.GestaoLTL; import br.ufpe.activiti.behaviour.gestaoLTL.MapemanetoFormulasLTL; import br.ufpe.activiti.behaviour.model.ProcessoNegocio; import br.ufpe.activiti.behaviour.model.Servico; import br.ufpe.activiti.behaviour.model.Tarefa; public class Analisador { public Map<String, Double> Analisar(XLog xlog, List<ProcessoNegocio> processosDeNegocios) { GestaoLTL gestaoLTL = new GestaoLTL(); Map<String, Double> mapaDeAnalise = new LinkedHashMap<String, Double>(); MapemanetoFormulasLTL mapemanetoFormulasLTL = new MapemanetoFormulasLTL(); String formulaConsulta = mapemanetoFormulasLTL.eventualmenteAcontece ("AuthenticationServiceOne", "authentication", "ClientAuthentication"); String formulaConsulta2 = mapemanetoFormulasLTL.eventualmenteAcontece ("AuthenticationServiceTwo", "authenticationTwo", "ClientAuthentication"); try { Double valor = gestaoLTL.invocarMinerarFormula(xlog,formulaConsulta); Double valor2 = gestaoLTL.invocarMinerarFormula(xlog,formulaConsulta2); if(valor==null) mapaDeAnalise.put("ClientAuthentication:AuthenticationServiceOne:authentication:Existence", valor); if(valor2==null) mapaDeAnalise.put("ClientAuthentication:AuthenticationServiceTwo:authenticationTwo:Existence", valor2); } catch (Exception e) { e.printStackTrace(); } /*for(ProcessoNegocio processoNegocio: processosDeNegocios) { for(Tarefa tarefa: processoNegocio.getListaTarefas()) { for(Servico servico: tarefa.getListaServicos()) { formulaConsulta = mapemanetoFormulasLTL.recursoParaUmaAtividade (servico.getNome(), servico.getOperacao(), tarefa.getNome()); try { Double valor = gestaoLTL.invocarMinerarFormula(xlog,formulaConsulta); if(valor!=null) { mapaDeAnalise.put(tarefa.getNome()+":"+servico.getNome()+":"+servico.getOperacao(), valor); } } catch (Exception e) { e.printStackTrace(); } } } }*/ return mapaDeAnalise; } }
wellisonraul/ProjetoDoutorado
activiti-behaviour/src/main/java/br/ufpe/activiti/behaviour/ciclo/mapek/Analisador.java
Java
apache-2.0
2,217
package com.pilotojsf.managedbean.dia2.navigation; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; @ManagedBean(name="navigatorManagedBean") @ViewScoped public class NavigatorManagedBean implements Serializable { private Integer codigo; public String navegacaoImplicita(){ return "destinyNavigation"; } public String navegacaoImplicitaErrada(){ return "destinyNavigationWrong"; } public String navegacaoExplicita(){ return "nextPage"; } public String navegacaoExplicitaErrada(){ return "nextPageWrong"; } public String navegacaoCondicionalManagedBean(){ if(codigo != null){ if(codigo > 10){ return "destinyNavigation"; } } return "conditionalNavigation"; } public String navegacaoExplicitaErradaFaces(){ return "nextPageWrongFaces"; } public Integer getCodigo() { return codigo; } public void setCodigo(Integer codigo) { this.codigo = codigo; } }
antoniolazaro/jsflabs
jsflab/src/main/java/com/pilotojsf/managedbean/dia2/navigation/NavigatorManagedBean.java
Java
apache-2.0
964
/* * 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; /** * @author vlads * */ public class DynamicallyLoadedStatus { static boolean runnerSuccess = false; static { runnerSuccess = false; } }
freeVM/freeVM
enhanced/microemulator/microemu-tests/bytecode-test-app/src/main/java/org/DynamicallyLoadedStatus.java
Java
apache-2.0
987
/* * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.rxjava3.schedulers; import static org.junit.Assert.*; import java.util.concurrent.*; import io.reactivex.rxjava3.core.*; import io.reactivex.rxjava3.subscribers.DefaultSubscriber; final class SchedulerTestHelper { private SchedulerTestHelper() { // No instances. } /** * Verifies that the given Scheduler does not deliver handled errors to its executing Thread's * {@link java.lang.Thread.UncaughtExceptionHandler}. * * @param scheduler {@link Scheduler} to verify. */ static void handledErrorIsNotDeliveredToThreadHandler(Scheduler scheduler) throws InterruptedException { Thread.UncaughtExceptionHandler originalHandler = Thread.getDefaultUncaughtExceptionHandler(); try { CapturingUncaughtExceptionHandler handler = new CapturingUncaughtExceptionHandler(); CapturingObserver<Object> observer = new CapturingObserver<>(); Thread.setDefaultUncaughtExceptionHandler(handler); IllegalStateException error = new IllegalStateException("Should be delivered to handler"); Flowable.error(error) .subscribeOn(scheduler) .subscribe(observer); if (!observer.completed.await(3, TimeUnit.SECONDS)) { fail("timed out"); } if (handler.count != 0) { handler.caught.printStackTrace(); } assertEquals("Handler should not have received anything: " + handler.caught, 0, handler.count); assertEquals("Observer should have received an error", 1, observer.errorCount); assertEquals("Observer should not have received a next value", 0, observer.nextCount); Throwable cause = observer.error; while (cause != null) { if (error.equals(cause)) { break; } if (cause == cause.getCause()) { break; } cause = cause.getCause(); } assertEquals("Our error should have been delivered to the observer", error, cause); } finally { Thread.setDefaultUncaughtExceptionHandler(originalHandler); } } private static final class CapturingUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { int count; Throwable caught; CountDownLatch completed = new CountDownLatch(1); @Override public void uncaughtException(Thread t, Throwable e) { count++; caught = e; completed.countDown(); } } static final class CapturingObserver<T> extends DefaultSubscriber<T> { CountDownLatch completed = new CountDownLatch(1); int errorCount; int nextCount; Throwable error; @Override public void onComplete() { } @Override public void onError(Throwable e) { errorCount++; error = e; completed.countDown(); } @Override public void onNext(T t) { nextCount++; } } }
ReactiveX/RxJava
src/test/java/io/reactivex/rxjava3/schedulers/SchedulerTestHelper.java
Java
apache-2.0
3,716
/* * Copyright 2010 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; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.javascript.jscomp.ReplaceStrings.Result; import com.google.javascript.rhino.Node; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Tests for {@link ReplaceStrings}. * */ public class ReplaceStringsTest extends CompilerTestCase { private ReplaceStrings pass; private Set<String> reserved; private VariableMap previous; private boolean runDisambiguateProperties = false; private final List<String> functionsToInspect = Lists.newArrayList( "Error(?)", "goog.debug.Trace.startTracer(*)", "goog.debug.Logger.getLogger(?)", "goog.debug.Logger.prototype.info(?)", "goog.log.getLogger(?)", "goog.log.info(,?)" ); private static final String EXTERNS = "var goog = {};\n" + "goog.debug = {};\n" + "/** @constructor */\n" + "goog.debug.Trace = function() {};\n" + "goog.debug.Trace.startTracer = function (var_args) {};\n" + "/** @constructor */\n" + "goog.debug.Logger = function() {};\n" + "goog.debug.Logger.prototype.info = function(msg, opt_ex) {};\n" + "/**\n" + " * @param {string} name\n" + " * @return {!goog.debug.Logger}\n" + " */\n" + "goog.debug.Logger.getLogger = function(name){};\n" + "goog.log = {}\n" + "goog.log.getLogger = function(name){};\n" + "goog.log.info = function(logger, msg, opt_ex) {};\n" ; public ReplaceStringsTest() { super(EXTERNS, true); enableNormalize(); parseTypeInfo = true; compareJsDoc = false; } @Override protected CompilerOptions getOptions() { CompilerOptions options = super.getOptions(); options.setWarningLevel( DiagnosticGroups.MISSING_PROPERTIES, CheckLevel.OFF); return options; } @Override protected void setUp() throws Exception { super.setUp(); super.enableLineNumberCheck(false); super.enableTypeCheck(CheckLevel.WARNING); reserved = Collections.emptySet(); previous = null; } @Override public CompilerPass getProcessor(final Compiler compiler) { pass = new ReplaceStrings( compiler, "`", functionsToInspect, reserved, previous); return new CompilerPass() { @Override public void process(Node externs, Node js) { Map<String, CheckLevel> propertiesToErrorFor = new HashMap<>(); propertiesToErrorFor.put("foobar", CheckLevel.ERROR); new CollapseProperties(compiler, true, true).process(externs, js); if (runDisambiguateProperties) { SourceInformationAnnotator sia = new SourceInformationAnnotator( "test", false /* doSanityChecks */); NodeTraversal.traverse(compiler, js, sia); DisambiguateProperties.forJSTypeSystem( compiler, propertiesToErrorFor).process(externs, js); } pass.process(externs, js); } }; } @Override public int getNumRepetitions() { // This compiler pass is not idempotent and should only be run over a // parse tree once. return 1; } public void testStable1() { previous = VariableMap.fromMap(ImmutableMap.of("previous", "xyz")); testDebugStrings( "Error('xyz');", "Error('previous');", (new String[] { "previous", "xyz" })); reserved = ImmutableSet.of("a", "b", "previous"); testDebugStrings( "Error('xyz');", "Error('c');", (new String[] { "c", "xyz" })); } public void testStable2() { // Two things happen here: // 1) a previously used name "a" is not used for another string, "b" is // chosen instead. // 2) a previously used name "a" is dropped from the output map if // it isn't used. previous = VariableMap.fromMap(ImmutableMap.of("a", "unused")); testDebugStrings( "Error('xyz');", "Error('b');", (new String[] { "b", "xyz" })); } public void testThrowError1() { testDebugStrings( "throw Error('xyz');", "throw Error('a');", (new String[] { "a", "xyz" })); previous = VariableMap.fromMap(ImmutableMap.of("previous", "xyz")); testDebugStrings( "throw Error('xyz');", "throw Error('previous');", (new String[] { "previous", "xyz" })); } public void testThrowError2() { testDebugStrings( "throw Error('x' +\n 'yz');", "throw Error('a');", (new String[] { "a", "xyz" })); } public void testThrowError3() { testDebugStrings( "throw Error('Unhandled mail' + ' search type ' + type);", "throw Error('a' + '`' + type);", (new String[] { "a", "Unhandled mail search type `" })); } public void testThrowError4() { testDebugStrings( "/** @constructor */\n" + "var A = function() {};\n" + "A.prototype.m = function(child) {\n" + " if (this.haveChild(child)) {\n" + " throw Error('Node: ' + this.getDataPath() +\n" + " ' already has a child named ' + child);\n" + " } else if (child.parentNode) {\n" + " throw Error('Node: ' + child.getDataPath() +\n" + " ' already has a parent');\n" + " }\n" + " child.parentNode = this;\n" + "};", "var A = function(){};\n" + "A.prototype.m = function(child) {\n" + " if (this.haveChild(child)) {\n" + " throw Error('a' + '`' + this.getDataPath() + '`' + child);\n" + " } else if (child.parentNode) {\n" + " throw Error('b' + '`' + child.getDataPath());\n" + " }\n" + " child.parentNode = this;\n" + "};", (new String[] { "a", "Node: ` already has a child named `", "b", "Node: ` already has a parent", })); } public void testThrowNonStringError() { // No replacement is done when an error is neither a string literal nor // a string concatenation expression. testDebugStrings( "throw Error(x('abc'));", "throw Error(x('abc'));", (new String[] { })); } public void testThrowConstStringError() { testDebugStrings( "var AA = 'uvw', AB = 'xyz'; throw Error(AB);", "var AA = 'uvw', AB = 'xyz'; throw Error('a');", (new String [] { "a", "xyz" })); } public void testThrowNewError1() { testDebugStrings( "throw new Error('abc');", "throw new Error('a');", (new String[] { "a", "abc" })); } public void testThrowNewError2() { testDebugStrings( "throw new Error();", "throw new Error();", new String[] {}); } public void testStartTracer1() { testDebugStrings( "goog.debug.Trace.startTracer('HistoryManager.updateHistory');", "goog.debug.Trace.startTracer('a');", (new String[] { "a", "HistoryManager.updateHistory" })); } public void testStartTracer2() { testDebugStrings( "goog$debug$Trace.startTracer('HistoryManager', 'updateHistory');", "goog$debug$Trace.startTracer('a', 'b');", (new String[] { "a", "HistoryManager", "b", "updateHistory" })); } public void testStartTracer3() { testDebugStrings( "goog$debug$Trace.startTracer('ThreadlistView',\n" + " 'Updating ' + array.length + ' rows');", "goog$debug$Trace.startTracer('a', 'b' + '`' + array.length);", new String[] { "a", "ThreadlistView", "b", "Updating ` rows" }); } public void testStartTracer4() { testDebugStrings( "goog.debug.Trace.startTracer(s, 'HistoryManager.updateHistory');", "goog.debug.Trace.startTracer(s, 'a');", (new String[] { "a", "HistoryManager.updateHistory" })); } public void testLoggerInitialization() { testDebugStrings( "goog$debug$Logger$getLogger('my.app.Application');", "goog$debug$Logger$getLogger('a');", (new String[] { "a", "my.app.Application" })); } public void testLoggerOnObject1() { testDebugStrings( "var x = {};" + "x.logger_ = goog.debug.Logger.getLogger('foo');" + "x.logger_.info('Some message');", "var x$logger_ = goog.debug.Logger.getLogger('a');" + "x$logger_.info('b');", new String[] { "a", "foo", "b", "Some message"}); } // Non-matching "info" property. public void testLoggerOnObject2() { test( "var x = {};" + "x.info = function(a) {};" + "x.info('Some message');", "var x$info = function(a) {};" + "x$info('Some message');"); } // Non-matching "info" prototype property. public void testLoggerOnObject3a() { testSame( "/** @constructor */\n" + "var x = function() {};\n" + "x.prototype.info = function(a) {};" + "(new x).info('Some message');"); } // Non-matching "info" prototype property. public void testLoggerOnObject3b() { testSame( "/** @constructor */\n" + "var x = function() {};\n" + "x.prototype.info = function(a) {};" + "var y = (new x); this.info('Some message');"); } // Non-matching "info" property on "NoObject" type. public void testLoggerOnObject4() { testSame("(new x).info('Some message');"); } // Non-matching "info" property on "UnknownObject" type. public void testLoggerOnObject5() { testSame("my$Thing.logger_.info('Some message');"); } public void testLoggerOnVar() { testDebugStrings( "var logger = goog.debug.Logger.getLogger('foo');" + "logger.info('Some message');", "var logger = goog.debug.Logger.getLogger('a');" + "logger.info('b');", new String[] { "a", "foo", "b", "Some message"}); } public void testLoggerOnThis() { testDebugStrings( "function f() {" + " this.logger_ = goog.debug.Logger.getLogger('foo');" + " this.logger_.info('Some message');" + "}", "function f() {" + " this.logger_ = goog.debug.Logger.getLogger('a');" + " this.logger_.info('b');" + "}", new String[] { "a", "foo", "b", "Some message"}); } public void testRepeatedErrorString1() { testDebugStrings( "Error('abc');Error('def');Error('abc');", "Error('a');Error('b');Error('a');", (new String[] { "a", "abc", "b", "def" })); } public void testRepeatedErrorString2() { testDebugStrings( "Error('a:' + u + ', b:' + v); Error('a:' + x + ', b:' + y);", "Error('a' + '`' + u + '`' + v); Error('a' + '`' + x + '`' + y);", (new String[] { "a", "a:`, b:`" })); } public void testRepeatedErrorString3() { testDebugStrings( "var AB = 'b'; throw Error(AB); throw Error(AB);", "var AB = 'b'; throw Error('a'); throw Error('a');", (new String[] { "a", "b" })); } public void testRepeatedTracerString() { testDebugStrings( "goog$debug$Trace.startTracer('A', 'B', 'A');", "goog$debug$Trace.startTracer('a', 'b', 'a');", (new String[] { "a", "A", "b", "B" })); } public void testRepeatedLoggerString() { testDebugStrings( "goog$debug$Logger$getLogger('goog.net.XhrTransport');" + "goog$debug$Logger$getLogger('my.app.Application');" + "goog$debug$Logger$getLogger('my.app.Application');", "goog$debug$Logger$getLogger('a');" + "goog$debug$Logger$getLogger('b');" + "goog$debug$Logger$getLogger('b');", new String[] { "a", "goog.net.XhrTransport", "b", "my.app.Application" }); } public void testRepeatedStringsWithDifferentMethods() { test( "throw Error('A');" + "goog$debug$Trace.startTracer('B', 'A');" + "goog$debug$Logger$getLogger('C');" + "goog$debug$Logger$getLogger('B');" + "goog$debug$Logger$getLogger('A');" + "throw Error('D');" + "throw Error('C');" + "throw Error('B');" + "throw Error('A');", "throw Error('a');" + "goog$debug$Trace.startTracer('b', 'a');" + "goog$debug$Logger$getLogger('c');" + "goog$debug$Logger$getLogger('b');" + "goog$debug$Logger$getLogger('a');" + "throw Error('d');" + "throw Error('c');" + "throw Error('b');" + "throw Error('a');"); } public void testReserved() { testDebugStrings( "throw Error('xyz');", "throw Error('a');", (new String[] { "a", "xyz" })); reserved = ImmutableSet.of("a", "b", "c"); testDebugStrings( "throw Error('xyz');", "throw Error('d');", (new String[] { "d", "xyz" })); } public void testLoggerWithNoReplacedParam() { testDebugStrings( "var x = {};" + "x.logger_ = goog.log.getLogger('foo');" + "goog.log.info(x.logger_, 'Some message');", "var x$logger_ = goog.log.getLogger('a');" + "goog.log.info(x$logger_, 'b');", new String[] { "a", "foo", "b", "Some message"}); } public void testWithDisambiguateProperties() throws Exception { runDisambiguateProperties = true; functionsToInspect.add("A.prototype.f(?)"); functionsToInspect.add("C.prototype.f(?)"); String js = "/** @constructor */function A() {}\n" + "/** @param {string} p\n" + " * @return {string} */\n" + "A.prototype.f = function(p) {return 'a' + p;};\n" + "/** @constructor */function B() {}\n" + "/** @param {string} p\n" + " * @return {string} */\n" + "B.prototype.f = function(p) {return p + 'b';};\n" + "/** @constructor */function C() {}\n" + "/** @param {string} p\n" + " * @return {string} */\n" + "C.prototype.f = function(p) {return 'c' + p + 'c';};\n" + "/** @type {A|B} */var ab = 1 ? new B : new A;\n" + "/** @type {string} */var n = ab.f('not replaced');\n" + "(new A).f('replaced with a');" + "(new C).f('replaced with b');"; String output = "function A() {}\n" + "A.prototype.A_prototype$f = function(p) { return'a'+p; };\n" + "function B() {}\n" + "B.prototype.A_prototype$f = function(p) { return p+'b'; };\n" + "function C() {}\n" + "C.prototype.C_prototype$f = function(p) { return'c'+p+'c'; };\n" + "var ab = 1 ? new B : new A;\n" + "var n = ab.A_prototype$f('not replaced');\n" + "(new A).A_prototype$f('a');" + "(new C).C_prototype$f('b');"; testDebugStrings(js, output, new String[] { "a", "replaced with a", "b", "replaced with b"}); } private void testDebugStrings(String js, String expected, String[] substitutedStrings) { // Verify that the strings are substituted correctly in the JS code. test(js, expected); List<Result> results = pass.getResult(); assertTrue(substitutedStrings.length % 2 == 0); assertEquals(substitutedStrings.length / 2, results.size()); // Verify that substituted strings are decoded correctly. for (int i = 0; i < substitutedStrings.length; i += 2) { Result result = results.get(i / 2); String original = substitutedStrings[i + 1]; assertEquals(original, result.original); String replacement = substitutedStrings[i]; assertEquals(replacement, result.replacement); } } }
zombiezen/cardcpx
third_party/closure-compiler/test/com/google/javascript/jscomp/ReplaceStringsTest.java
Java
apache-2.0
16,444
package eu.softisland.warsjava.view.webbrowser; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; public class WebViewActivity extends FragmentActivity { private static final String TAG = WebViewActivity.class.getName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebViewFragment webViewFragment = new WebViewFragment(); Intent i = this.getIntent(); String link = i.getExtras().getString("link"); Log.d(TAG, "In separate Activity, open url [" + link + "]"); webViewFragment.init(link); getSupportFragmentManager().beginTransaction().add(android.R.id.content, webViewFragment).commit(); } }
pawelByszewski/warsjava2013
begin/start/src/eu/softisland/warsjava/view/webbrowser/WebViewActivity.java
Java
apache-2.0
809
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.androidenterprise; /** * Service definition for AndroidEnterprise (v1). * * <p> * Manages the deployment of apps to Android for Work users. * </p> * * <p> * For more information about this service, see the * <a href="https://developers.google.com/android/work/play/emm-api" target="_blank">API Documentation</a> * </p> * * <p> * This service uses {@link AndroidEnterpriseRequestInitializer} to initialize global parameters via its * {@link Builder}. * </p> * * @since 1.3 * @author Google, Inc. */ @SuppressWarnings("javadoc") public class AndroidEnterprise extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient { // Note: Leave this static initializer at the top of the file. static { com.google.api.client.util.Preconditions.checkState( com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 && com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15, "You are currently running with version %s of google-api-client. " + "You need at least version 1.15 of google-api-client to run version " + "1.27.0 of the Google Play EMM API library.", com.google.api.client.googleapis.GoogleUtils.VERSION); } /** * The default encoded root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_ROOT_URL = "https://www.googleapis.com/"; /** * The default encoded service path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_SERVICE_PATH = "androidenterprise/v1/"; /** * The default encoded batch path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.23 */ public static final String DEFAULT_BATCH_PATH = "batch/androidenterprise/v1"; /** * The default encoded base URL of the service. This is determined when the library is generated * and normally should not be changed. */ public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; /** * Constructor. * * <p> * Use {@link Builder} if you need to specify any of the optional parameters. * </p> * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public AndroidEnterprise(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, jsonFactory, httpRequestInitializer)); } /** * @param builder builder */ AndroidEnterprise(Builder builder) { super(builder); } @Override protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException { super.initialize(httpClientRequest); } /** * An accessor for creating requests from the Devices collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Devices.List request = androidenterprise.devices().list(parameters ...)} * </pre> * * @return the resource collection */ public Devices devices() { return new Devices(); } /** * The "devices" collection of methods. */ public class Devices { /** * Uploads a report containing any changes in app states on the device since the last report was * generated. You can call this method up to 3 times every 24 hours for a given device. * * Create a request for the method "devices.forceReportUpload". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link ForceReportUpload#execute()} method to invoke the remote * operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The ID of the device. * @return the request */ public ForceReportUpload forceReportUpload(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId) throws java.io.IOException { ForceReportUpload result = new ForceReportUpload(enterpriseId, userId, deviceId); initialize(result); return result; } public class ForceReportUpload extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/forceReportUpload"; /** * Uploads a report containing any changes in app states on the device since the last report was * generated. You can call this method up to 3 times every 24 hours for a given device. * * Create a request for the method "devices.forceReportUpload". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link ForceReportUpload#execute()} method to invoke the * remote operation. <p> {@link ForceReportUpload#initialize(com.google.api.client.googleapis.serv * ices.AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The ID of the device. * @since 1.13 */ protected ForceReportUpload(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId) { super(AndroidEnterprise.this, "POST", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); } @Override public ForceReportUpload setAlt(java.lang.String alt) { return (ForceReportUpload) super.setAlt(alt); } @Override public ForceReportUpload setFields(java.lang.String fields) { return (ForceReportUpload) super.setFields(fields); } @Override public ForceReportUpload setKey(java.lang.String key) { return (ForceReportUpload) super.setKey(key); } @Override public ForceReportUpload setOauthToken(java.lang.String oauthToken) { return (ForceReportUpload) super.setOauthToken(oauthToken); } @Override public ForceReportUpload setPrettyPrint(java.lang.Boolean prettyPrint) { return (ForceReportUpload) super.setPrettyPrint(prettyPrint); } @Override public ForceReportUpload setQuotaUser(java.lang.String quotaUser) { return (ForceReportUpload) super.setQuotaUser(quotaUser); } @Override public ForceReportUpload setUserIp(java.lang.String userIp) { return (ForceReportUpload) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public ForceReportUpload setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public ForceReportUpload setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The ID of the device. */ public ForceReportUpload setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } @Override public ForceReportUpload set(String parameterName, Object value) { return (ForceReportUpload) super.set(parameterName, value); } } /** * Retrieves the details of a device. * * Create a request for the method "devices.get". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The ID of the device. * @return the request */ public Get get(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId) throws java.io.IOException { Get result = new Get(enterpriseId, userId, deviceId); initialize(result); return result; } public class Get extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Device> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}"; /** * Retrieves the details of a device. * * Create a request for the method "devices.get". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The ID of the device. * @since 1.13 */ protected Get(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.Device.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUserIp(java.lang.String userIp) { return (Get) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Get setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Get setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The ID of the device. */ public Get setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Retrieves whether a device's access to Google services is enabled or disabled. The device state * takes effect only if enforcing EMM policies on Android devices is enabled in the Google Admin * Console. Otherwise, the device state is ignored and all devices are allowed access to Google * services. This is only supported for Google-managed users. * * Create a request for the method "devices.getState". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link GetState#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The ID of the device. * @return the request */ public GetState getState(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId) throws java.io.IOException { GetState result = new GetState(enterpriseId, userId, deviceId); initialize(result); return result; } public class GetState extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.DeviceState> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/state"; /** * Retrieves whether a device's access to Google services is enabled or disabled. The device state * takes effect only if enforcing EMM policies on Android devices is enabled in the Google Admin * Console. Otherwise, the device state is ignored and all devices are allowed access to Google * services. This is only supported for Google-managed users. * * Create a request for the method "devices.getState". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link GetState#execute()} method to invoke the remote * operation. <p> {@link * GetState#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The ID of the device. * @since 1.13 */ protected GetState(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.DeviceState.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public GetState setAlt(java.lang.String alt) { return (GetState) super.setAlt(alt); } @Override public GetState setFields(java.lang.String fields) { return (GetState) super.setFields(fields); } @Override public GetState setKey(java.lang.String key) { return (GetState) super.setKey(key); } @Override public GetState setOauthToken(java.lang.String oauthToken) { return (GetState) super.setOauthToken(oauthToken); } @Override public GetState setPrettyPrint(java.lang.Boolean prettyPrint) { return (GetState) super.setPrettyPrint(prettyPrint); } @Override public GetState setQuotaUser(java.lang.String quotaUser) { return (GetState) super.setQuotaUser(quotaUser); } @Override public GetState setUserIp(java.lang.String userIp) { return (GetState) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public GetState setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public GetState setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The ID of the device. */ public GetState setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } @Override public GetState set(String parameterName, Object value) { return (GetState) super.set(parameterName, value); } } /** * Retrieves the IDs of all of a user's devices. * * Create a request for the method "devices.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @return the request */ public List list(java.lang.String enterpriseId, java.lang.String userId) throws java.io.IOException { List result = new List(enterpriseId, userId); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.DevicesListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices"; /** * Retrieves the IDs of all of a user's devices. * * Create a request for the method "devices.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @since 1.13 */ protected List(java.lang.String enterpriseId, java.lang.String userId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.DevicesListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public List setUserId(java.lang.String userId) { this.userId = userId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates the device policy. This method supports patch semantics. * * Create a request for the method "devices.patch". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The ID of the device. * @param content the {@link com.google.api.services.androidenterprise.model.Device} * @return the request */ public Patch patch(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, com.google.api.services.androidenterprise.model.Device content) throws java.io.IOException { Patch result = new Patch(enterpriseId, userId, deviceId, content); initialize(result); return result; } public class Patch extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Device> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}"; /** * Updates the device policy. This method supports patch semantics. * * Create a request for the method "devices.patch". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Patch#execute()} method to invoke the remote * operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The ID of the device. * @param content the {@link com.google.api.services.androidenterprise.model.Device} * @since 1.13 */ protected Patch(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, com.google.api.services.androidenterprise.model.Device content) { super(AndroidEnterprise.this, "PATCH", REST_PATH, content, com.google.api.services.androidenterprise.model.Device.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUserIp(java.lang.String userIp) { return (Patch) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Patch setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Patch setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The ID of the device. */ public Patch setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } /** * Mask that identifies which fields to update. If not set, all modifiable fields will be * modified. * * When set in a query parameter, this field should be specified as updateMask=,,... */ @com.google.api.client.util.Key private java.lang.String updateMask; /** Mask that identifies which fields to update. If not set, all modifiable fields will be modified. When set in a query parameter, this field should be specified as updateMask=,,... */ public java.lang.String getUpdateMask() { return updateMask; } /** * Mask that identifies which fields to update. If not set, all modifiable fields will be * modified. * * When set in a query parameter, this field should be specified as updateMask=,,... */ public Patch setUpdateMask(java.lang.String updateMask) { this.updateMask = updateMask; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * Sets whether a device's access to Google services is enabled or disabled. The device state takes * effect only if enforcing EMM policies on Android devices is enabled in the Google Admin Console. * Otherwise, the device state is ignored and all devices are allowed access to Google services. * This is only supported for Google-managed users. * * Create a request for the method "devices.setState". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link SetState#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The ID of the device. * @param content the {@link com.google.api.services.androidenterprise.model.DeviceState} * @return the request */ public SetState setState(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, com.google.api.services.androidenterprise.model.DeviceState content) throws java.io.IOException { SetState result = new SetState(enterpriseId, userId, deviceId, content); initialize(result); return result; } public class SetState extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.DeviceState> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/state"; /** * Sets whether a device's access to Google services is enabled or disabled. The device state * takes effect only if enforcing EMM policies on Android devices is enabled in the Google Admin * Console. Otherwise, the device state is ignored and all devices are allowed access to Google * services. This is only supported for Google-managed users. * * Create a request for the method "devices.setState". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link SetState#execute()} method to invoke the remote * operation. <p> {@link * SetState#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The ID of the device. * @param content the {@link com.google.api.services.androidenterprise.model.DeviceState} * @since 1.13 */ protected SetState(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, com.google.api.services.androidenterprise.model.DeviceState content) { super(AndroidEnterprise.this, "PUT", REST_PATH, content, com.google.api.services.androidenterprise.model.DeviceState.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); } @Override public SetState setAlt(java.lang.String alt) { return (SetState) super.setAlt(alt); } @Override public SetState setFields(java.lang.String fields) { return (SetState) super.setFields(fields); } @Override public SetState setKey(java.lang.String key) { return (SetState) super.setKey(key); } @Override public SetState setOauthToken(java.lang.String oauthToken) { return (SetState) super.setOauthToken(oauthToken); } @Override public SetState setPrettyPrint(java.lang.Boolean prettyPrint) { return (SetState) super.setPrettyPrint(prettyPrint); } @Override public SetState setQuotaUser(java.lang.String quotaUser) { return (SetState) super.setQuotaUser(quotaUser); } @Override public SetState setUserIp(java.lang.String userIp) { return (SetState) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public SetState setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public SetState setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The ID of the device. */ public SetState setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } @Override public SetState set(String parameterName, Object value) { return (SetState) super.set(parameterName, value); } } /** * Updates the device policy * * Create a request for the method "devices.update". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The ID of the device. * @param content the {@link com.google.api.services.androidenterprise.model.Device} * @return the request */ public Update update(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, com.google.api.services.androidenterprise.model.Device content) throws java.io.IOException { Update result = new Update(enterpriseId, userId, deviceId, content); initialize(result); return result; } public class Update extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Device> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}"; /** * Updates the device policy * * Create a request for the method "devices.update". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Update#execute()} method to invoke the remote * operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The ID of the device. * @param content the {@link com.google.api.services.androidenterprise.model.Device} * @since 1.13 */ protected Update(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, com.google.api.services.androidenterprise.model.Device content) { super(AndroidEnterprise.this, "PUT", REST_PATH, content, com.google.api.services.androidenterprise.model.Device.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUserIp(java.lang.String userIp) { return (Update) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Update setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Update setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The ID of the device. */ public Update setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } /** * Mask that identifies which fields to update. If not set, all modifiable fields will be * modified. * * When set in a query parameter, this field should be specified as updateMask=,,... */ @com.google.api.client.util.Key private java.lang.String updateMask; /** Mask that identifies which fields to update. If not set, all modifiable fields will be modified. When set in a query parameter, this field should be specified as updateMask=,,... */ public java.lang.String getUpdateMask() { return updateMask; } /** * Mask that identifies which fields to update. If not set, all modifiable fields will be * modified. * * When set in a query parameter, this field should be specified as updateMask=,,... */ public Update setUpdateMask(java.lang.String updateMask) { this.updateMask = updateMask; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Enterprises collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Enterprises.List request = androidenterprise.enterprises().list(parameters ...)} * </pre> * * @return the resource collection */ public Enterprises enterprises() { return new Enterprises(); } /** * The "enterprises" collection of methods. */ public class Enterprises { /** * Acknowledges notifications that were received from Enterprises.PullNotificationSet to prevent * subsequent calls from returning the same notifications. * * Create a request for the method "enterprises.acknowledgeNotificationSet". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link AcknowledgeNotificationSet#execute()} method to invoke the * remote operation. * * @return the request */ public AcknowledgeNotificationSet acknowledgeNotificationSet() throws java.io.IOException { AcknowledgeNotificationSet result = new AcknowledgeNotificationSet(); initialize(result); return result; } public class AcknowledgeNotificationSet extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/acknowledgeNotificationSet"; /** * Acknowledges notifications that were received from Enterprises.PullNotificationSet to prevent * subsequent calls from returning the same notifications. * * Create a request for the method "enterprises.acknowledgeNotificationSet". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link AcknowledgeNotificationSet#execute()} method to invoke * the remote operation. <p> {@link AcknowledgeNotificationSet#initialize(com.google.api.client.go * ogleapis.services.AbstractGoogleClientRequest)} must be called to initialize this instance * immediately after invoking the constructor. </p> * * @since 1.13 */ protected AcknowledgeNotificationSet() { super(AndroidEnterprise.this, "POST", REST_PATH, null, Void.class); } @Override public AcknowledgeNotificationSet setAlt(java.lang.String alt) { return (AcknowledgeNotificationSet) super.setAlt(alt); } @Override public AcknowledgeNotificationSet setFields(java.lang.String fields) { return (AcknowledgeNotificationSet) super.setFields(fields); } @Override public AcknowledgeNotificationSet setKey(java.lang.String key) { return (AcknowledgeNotificationSet) super.setKey(key); } @Override public AcknowledgeNotificationSet setOauthToken(java.lang.String oauthToken) { return (AcknowledgeNotificationSet) super.setOauthToken(oauthToken); } @Override public AcknowledgeNotificationSet setPrettyPrint(java.lang.Boolean prettyPrint) { return (AcknowledgeNotificationSet) super.setPrettyPrint(prettyPrint); } @Override public AcknowledgeNotificationSet setQuotaUser(java.lang.String quotaUser) { return (AcknowledgeNotificationSet) super.setQuotaUser(quotaUser); } @Override public AcknowledgeNotificationSet setUserIp(java.lang.String userIp) { return (AcknowledgeNotificationSet) super.setUserIp(userIp); } /** * The notification set ID as returned by Enterprises.PullNotificationSet. This must be * provided. */ @com.google.api.client.util.Key private java.lang.String notificationSetId; /** The notification set ID as returned by Enterprises.PullNotificationSet. This must be provided. */ public java.lang.String getNotificationSetId() { return notificationSetId; } /** * The notification set ID as returned by Enterprises.PullNotificationSet. This must be * provided. */ public AcknowledgeNotificationSet setNotificationSetId(java.lang.String notificationSetId) { this.notificationSetId = notificationSetId; return this; } @Override public AcknowledgeNotificationSet set(String parameterName, Object value) { return (AcknowledgeNotificationSet) super.set(parameterName, value); } } /** * Completes the signup flow, by specifying the Completion token and Enterprise token. This request * must not be called multiple times for a given Enterprise Token. * * Create a request for the method "enterprises.completeSignup". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link CompleteSignup#execute()} method to invoke the remote * operation. * * @return the request */ public CompleteSignup completeSignup() throws java.io.IOException { CompleteSignup result = new CompleteSignup(); initialize(result); return result; } public class CompleteSignup extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Enterprise> { private static final String REST_PATH = "enterprises/completeSignup"; /** * Completes the signup flow, by specifying the Completion token and Enterprise token. This * request must not be called multiple times for a given Enterprise Token. * * Create a request for the method "enterprises.completeSignup". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link CompleteSignup#execute()} method to invoke the remote * operation. <p> {@link CompleteSignup#initialize(com.google.api.client.googleapis.services.Abstr * actGoogleClientRequest)} must be called to initialize this instance immediately after invoking * the constructor. </p> * * @since 1.13 */ protected CompleteSignup() { super(AndroidEnterprise.this, "POST", REST_PATH, null, com.google.api.services.androidenterprise.model.Enterprise.class); } @Override public CompleteSignup setAlt(java.lang.String alt) { return (CompleteSignup) super.setAlt(alt); } @Override public CompleteSignup setFields(java.lang.String fields) { return (CompleteSignup) super.setFields(fields); } @Override public CompleteSignup setKey(java.lang.String key) { return (CompleteSignup) super.setKey(key); } @Override public CompleteSignup setOauthToken(java.lang.String oauthToken) { return (CompleteSignup) super.setOauthToken(oauthToken); } @Override public CompleteSignup setPrettyPrint(java.lang.Boolean prettyPrint) { return (CompleteSignup) super.setPrettyPrint(prettyPrint); } @Override public CompleteSignup setQuotaUser(java.lang.String quotaUser) { return (CompleteSignup) super.setQuotaUser(quotaUser); } @Override public CompleteSignup setUserIp(java.lang.String userIp) { return (CompleteSignup) super.setUserIp(userIp); } /** The Completion token initially returned by GenerateSignupUrl. */ @com.google.api.client.util.Key private java.lang.String completionToken; /** The Completion token initially returned by GenerateSignupUrl. */ public java.lang.String getCompletionToken() { return completionToken; } /** The Completion token initially returned by GenerateSignupUrl. */ public CompleteSignup setCompletionToken(java.lang.String completionToken) { this.completionToken = completionToken; return this; } /** The Enterprise token appended to the Callback URL. */ @com.google.api.client.util.Key private java.lang.String enterpriseToken; /** The Enterprise token appended to the Callback URL. */ public java.lang.String getEnterpriseToken() { return enterpriseToken; } /** The Enterprise token appended to the Callback URL. */ public CompleteSignup setEnterpriseToken(java.lang.String enterpriseToken) { this.enterpriseToken = enterpriseToken; return this; } @Override public CompleteSignup set(String parameterName, Object value) { return (CompleteSignup) super.set(parameterName, value); } } /** * Returns a unique token to access an embeddable UI. To generate a web UI, pass the generated token * into the managed Google Play javascript API. Each token may only be used to start one UI session. * See the javascript API documentation for further information. * * Create a request for the method "enterprises.createWebToken". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link CreateWebToken#execute()} method to invoke the remote * operation. * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.AdministratorWebTokenSpec} * @return the request */ public CreateWebToken createWebToken(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.AdministratorWebTokenSpec content) throws java.io.IOException { CreateWebToken result = new CreateWebToken(enterpriseId, content); initialize(result); return result; } public class CreateWebToken extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.AdministratorWebToken> { private static final String REST_PATH = "enterprises/{enterpriseId}/createWebToken"; /** * Returns a unique token to access an embeddable UI. To generate a web UI, pass the generated * token into the managed Google Play javascript API. Each token may only be used to start one UI * session. See the javascript API documentation for further information. * * Create a request for the method "enterprises.createWebToken". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link CreateWebToken#execute()} method to invoke the remote * operation. <p> {@link CreateWebToken#initialize(com.google.api.client.googleapis.services.Abstr * actGoogleClientRequest)} must be called to initialize this instance immediately after invoking * the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.AdministratorWebTokenSpec} * @since 1.13 */ protected CreateWebToken(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.AdministratorWebTokenSpec content) { super(AndroidEnterprise.this, "POST", REST_PATH, content, com.google.api.services.androidenterprise.model.AdministratorWebToken.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public CreateWebToken setAlt(java.lang.String alt) { return (CreateWebToken) super.setAlt(alt); } @Override public CreateWebToken setFields(java.lang.String fields) { return (CreateWebToken) super.setFields(fields); } @Override public CreateWebToken setKey(java.lang.String key) { return (CreateWebToken) super.setKey(key); } @Override public CreateWebToken setOauthToken(java.lang.String oauthToken) { return (CreateWebToken) super.setOauthToken(oauthToken); } @Override public CreateWebToken setPrettyPrint(java.lang.Boolean prettyPrint) { return (CreateWebToken) super.setPrettyPrint(prettyPrint); } @Override public CreateWebToken setQuotaUser(java.lang.String quotaUser) { return (CreateWebToken) super.setQuotaUser(quotaUser); } @Override public CreateWebToken setUserIp(java.lang.String userIp) { return (CreateWebToken) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public CreateWebToken setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public CreateWebToken set(String parameterName, Object value) { return (CreateWebToken) super.set(parameterName, value); } } /** * Enrolls an enterprise with the calling EMM. * * Create a request for the method "enterprises.enroll". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Enroll#execute()} method to invoke the remote operation. * * @param token The token provided by the enterprise to register the EMM. * @param content the {@link com.google.api.services.androidenterprise.model.Enterprise} * @return the request */ public Enroll enroll(java.lang.String token, com.google.api.services.androidenterprise.model.Enterprise content) throws java.io.IOException { Enroll result = new Enroll(token, content); initialize(result); return result; } public class Enroll extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Enterprise> { private static final String REST_PATH = "enterprises/enroll"; /** * Enrolls an enterprise with the calling EMM. * * Create a request for the method "enterprises.enroll". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Enroll#execute()} method to invoke the remote * operation. <p> {@link * Enroll#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param token The token provided by the enterprise to register the EMM. * @param content the {@link com.google.api.services.androidenterprise.model.Enterprise} * @since 1.13 */ protected Enroll(java.lang.String token, com.google.api.services.androidenterprise.model.Enterprise content) { super(AndroidEnterprise.this, "POST", REST_PATH, content, com.google.api.services.androidenterprise.model.Enterprise.class); this.token = com.google.api.client.util.Preconditions.checkNotNull(token, "Required parameter token must be specified."); } @Override public Enroll setAlt(java.lang.String alt) { return (Enroll) super.setAlt(alt); } @Override public Enroll setFields(java.lang.String fields) { return (Enroll) super.setFields(fields); } @Override public Enroll setKey(java.lang.String key) { return (Enroll) super.setKey(key); } @Override public Enroll setOauthToken(java.lang.String oauthToken) { return (Enroll) super.setOauthToken(oauthToken); } @Override public Enroll setPrettyPrint(java.lang.Boolean prettyPrint) { return (Enroll) super.setPrettyPrint(prettyPrint); } @Override public Enroll setQuotaUser(java.lang.String quotaUser) { return (Enroll) super.setQuotaUser(quotaUser); } @Override public Enroll setUserIp(java.lang.String userIp) { return (Enroll) super.setUserIp(userIp); } /** The token provided by the enterprise to register the EMM. */ @com.google.api.client.util.Key private java.lang.String token; /** The token provided by the enterprise to register the EMM. */ public java.lang.String getToken() { return token; } /** The token provided by the enterprise to register the EMM. */ public Enroll setToken(java.lang.String token) { this.token = token; return this; } @Override public Enroll set(String parameterName, Object value) { return (Enroll) super.set(parameterName, value); } } /** * Generates a sign-up URL. * * Create a request for the method "enterprises.generateSignupUrl". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link GenerateSignupUrl#execute()} method to invoke the remote * operation. * * @return the request */ public GenerateSignupUrl generateSignupUrl() throws java.io.IOException { GenerateSignupUrl result = new GenerateSignupUrl(); initialize(result); return result; } public class GenerateSignupUrl extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.SignupInfo> { private static final String REST_PATH = "enterprises/signupUrl"; /** * Generates a sign-up URL. * * Create a request for the method "enterprises.generateSignupUrl". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link GenerateSignupUrl#execute()} method to invoke the * remote operation. <p> {@link GenerateSignupUrl#initialize(com.google.api.client.googleapis.serv * ices.AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @since 1.13 */ protected GenerateSignupUrl() { super(AndroidEnterprise.this, "POST", REST_PATH, null, com.google.api.services.androidenterprise.model.SignupInfo.class); } @Override public GenerateSignupUrl setAlt(java.lang.String alt) { return (GenerateSignupUrl) super.setAlt(alt); } @Override public GenerateSignupUrl setFields(java.lang.String fields) { return (GenerateSignupUrl) super.setFields(fields); } @Override public GenerateSignupUrl setKey(java.lang.String key) { return (GenerateSignupUrl) super.setKey(key); } @Override public GenerateSignupUrl setOauthToken(java.lang.String oauthToken) { return (GenerateSignupUrl) super.setOauthToken(oauthToken); } @Override public GenerateSignupUrl setPrettyPrint(java.lang.Boolean prettyPrint) { return (GenerateSignupUrl) super.setPrettyPrint(prettyPrint); } @Override public GenerateSignupUrl setQuotaUser(java.lang.String quotaUser) { return (GenerateSignupUrl) super.setQuotaUser(quotaUser); } @Override public GenerateSignupUrl setUserIp(java.lang.String userIp) { return (GenerateSignupUrl) super.setUserIp(userIp); } /** * The callback URL to which the Admin will be redirected after successfully creating an * enterprise. Before redirecting there the system will add a single query parameter to this * URL named "enterpriseToken" which will contain an opaque token to be used for the * CompleteSignup request. Beware that this means that the URL will be parsed, the parameter * added and then a new URL formatted, i.e. there may be some minor formatting changes and, * more importantly, the URL must be well-formed so that it can be parsed. */ @com.google.api.client.util.Key private java.lang.String callbackUrl; /** The callback URL to which the Admin will be redirected after successfully creating an enterprise. Before redirecting there the system will add a single query parameter to this URL named "enterpriseToken" which will contain an opaque token to be used for the CompleteSignup request. Beware that this means that the URL will be parsed, the parameter added and then a new URL formatted, i.e. there may be some minor formatting changes and, more importantly, the URL must be well-formed so that it can be parsed. */ public java.lang.String getCallbackUrl() { return callbackUrl; } /** * The callback URL to which the Admin will be redirected after successfully creating an * enterprise. Before redirecting there the system will add a single query parameter to this * URL named "enterpriseToken" which will contain an opaque token to be used for the * CompleteSignup request. Beware that this means that the URL will be parsed, the parameter * added and then a new URL formatted, i.e. there may be some minor formatting changes and, * more importantly, the URL must be well-formed so that it can be parsed. */ public GenerateSignupUrl setCallbackUrl(java.lang.String callbackUrl) { this.callbackUrl = callbackUrl; return this; } @Override public GenerateSignupUrl set(String parameterName, Object value) { return (GenerateSignupUrl) super.set(parameterName, value); } } /** * Retrieves the name and domain of an enterprise. * * Create a request for the method "enterprises.get". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @return the request */ public Get get(java.lang.String enterpriseId) throws java.io.IOException { Get result = new Get(enterpriseId); initialize(result); return result; } public class Get extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Enterprise> { private static final String REST_PATH = "enterprises/{enterpriseId}"; /** * Retrieves the name and domain of an enterprise. * * Create a request for the method "enterprises.get". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @since 1.13 */ protected Get(java.lang.String enterpriseId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.Enterprise.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUserIp(java.lang.String userIp) { return (Get) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Get setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Returns a service account and credentials. The service account can be bound to the enterprise by * calling setAccount. The service account is unique to this enterprise and EMM, and will be deleted * if the enterprise is unbound. The credentials contain private key data and are not stored server- * side. * * This method can only be called after calling Enterprises.Enroll or Enterprises.CompleteSignup, * and before Enterprises.SetAccount; at other times it will return an error. * * Subsequent calls after the first will generate a new, unique set of credentials, and invalidate * the previously generated credentials. * * Once the service account is bound to the enterprise, it can be managed using the * serviceAccountKeys resource. * * Create a request for the method "enterprises.getServiceAccount". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link GetServiceAccount#execute()} method to invoke the remote * operation. * * @param enterpriseId The ID of the enterprise. * @return the request */ public GetServiceAccount getServiceAccount(java.lang.String enterpriseId) throws java.io.IOException { GetServiceAccount result = new GetServiceAccount(enterpriseId); initialize(result); return result; } public class GetServiceAccount extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ServiceAccount> { private static final String REST_PATH = "enterprises/{enterpriseId}/serviceAccount"; /** * Returns a service account and credentials. The service account can be bound to the enterprise * by calling setAccount. The service account is unique to this enterprise and EMM, and will be * deleted if the enterprise is unbound. The credentials contain private key data and are not * stored server-side. * * This method can only be called after calling Enterprises.Enroll or Enterprises.CompleteSignup, * and before Enterprises.SetAccount; at other times it will return an error. * * Subsequent calls after the first will generate a new, unique set of credentials, and invalidate * the previously generated credentials. * * Once the service account is bound to the enterprise, it can be managed using the * serviceAccountKeys resource. * * Create a request for the method "enterprises.getServiceAccount". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link GetServiceAccount#execute()} method to invoke the * remote operation. <p> {@link GetServiceAccount#initialize(com.google.api.client.googleapis.serv * ices.AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @since 1.13 */ protected GetServiceAccount(java.lang.String enterpriseId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.ServiceAccount.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public GetServiceAccount setAlt(java.lang.String alt) { return (GetServiceAccount) super.setAlt(alt); } @Override public GetServiceAccount setFields(java.lang.String fields) { return (GetServiceAccount) super.setFields(fields); } @Override public GetServiceAccount setKey(java.lang.String key) { return (GetServiceAccount) super.setKey(key); } @Override public GetServiceAccount setOauthToken(java.lang.String oauthToken) { return (GetServiceAccount) super.setOauthToken(oauthToken); } @Override public GetServiceAccount setPrettyPrint(java.lang.Boolean prettyPrint) { return (GetServiceAccount) super.setPrettyPrint(prettyPrint); } @Override public GetServiceAccount setQuotaUser(java.lang.String quotaUser) { return (GetServiceAccount) super.setQuotaUser(quotaUser); } @Override public GetServiceAccount setUserIp(java.lang.String userIp) { return (GetServiceAccount) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public GetServiceAccount setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The type of credential to return with the service account. Required. */ @com.google.api.client.util.Key private java.lang.String keyType; /** The type of credential to return with the service account. Required. */ public java.lang.String getKeyType() { return keyType; } /** The type of credential to return with the service account. Required. */ public GetServiceAccount setKeyType(java.lang.String keyType) { this.keyType = keyType; return this; } @Override public GetServiceAccount set(String parameterName, Object value) { return (GetServiceAccount) super.set(parameterName, value); } } /** * Returns the store layout for the enterprise. If the store layout has not been set, returns * "basic" as the store layout type and no homepage. * * Create a request for the method "enterprises.getStoreLayout". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link GetStoreLayout#execute()} method to invoke the remote * operation. * * @param enterpriseId The ID of the enterprise. * @return the request */ public GetStoreLayout getStoreLayout(java.lang.String enterpriseId) throws java.io.IOException { GetStoreLayout result = new GetStoreLayout(enterpriseId); initialize(result); return result; } public class GetStoreLayout extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.StoreLayout> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout"; /** * Returns the store layout for the enterprise. If the store layout has not been set, returns * "basic" as the store layout type and no homepage. * * Create a request for the method "enterprises.getStoreLayout". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link GetStoreLayout#execute()} method to invoke the remote * operation. <p> {@link GetStoreLayout#initialize(com.google.api.client.googleapis.services.Abstr * actGoogleClientRequest)} must be called to initialize this instance immediately after invoking * the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @since 1.13 */ protected GetStoreLayout(java.lang.String enterpriseId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.StoreLayout.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public GetStoreLayout setAlt(java.lang.String alt) { return (GetStoreLayout) super.setAlt(alt); } @Override public GetStoreLayout setFields(java.lang.String fields) { return (GetStoreLayout) super.setFields(fields); } @Override public GetStoreLayout setKey(java.lang.String key) { return (GetStoreLayout) super.setKey(key); } @Override public GetStoreLayout setOauthToken(java.lang.String oauthToken) { return (GetStoreLayout) super.setOauthToken(oauthToken); } @Override public GetStoreLayout setPrettyPrint(java.lang.Boolean prettyPrint) { return (GetStoreLayout) super.setPrettyPrint(prettyPrint); } @Override public GetStoreLayout setQuotaUser(java.lang.String quotaUser) { return (GetStoreLayout) super.setQuotaUser(quotaUser); } @Override public GetStoreLayout setUserIp(java.lang.String userIp) { return (GetStoreLayout) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public GetStoreLayout setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public GetStoreLayout set(String parameterName, Object value) { return (GetStoreLayout) super.set(parameterName, value); } } /** * Looks up an enterprise by domain name. This is only supported for enterprises created via the * Google-initiated creation flow. Lookup of the id is not needed for enterprises created via the * EMM-initiated flow since the EMM learns the enterprise ID in the callback specified in the * Enterprises.generateSignupUrl call. * * Create a request for the method "enterprises.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param domain The exact primary domain name of the enterprise to look up. * @return the request */ public List list(java.lang.String domain) throws java.io.IOException { List result = new List(domain); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.EnterprisesListResponse> { private static final String REST_PATH = "enterprises"; /** * Looks up an enterprise by domain name. This is only supported for enterprises created via the * Google-initiated creation flow. Lookup of the id is not needed for enterprises created via the * EMM-initiated flow since the EMM learns the enterprise ID in the callback specified in the * Enterprises.generateSignupUrl call. * * Create a request for the method "enterprises.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param domain The exact primary domain name of the enterprise to look up. * @since 1.13 */ protected List(java.lang.String domain) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.EnterprisesListResponse.class); this.domain = com.google.api.client.util.Preconditions.checkNotNull(domain, "Required parameter domain must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The exact primary domain name of the enterprise to look up. */ @com.google.api.client.util.Key private java.lang.String domain; /** The exact primary domain name of the enterprise to look up. */ public java.lang.String getDomain() { return domain; } /** The exact primary domain name of the enterprise to look up. */ public List setDomain(java.lang.String domain) { this.domain = domain; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Pulls and returns a notification set for the enterprises associated with the service account * authenticated for the request. The notification set may be empty if no notification are pending. * A notification set returned needs to be acknowledged within 20 seconds by calling * Enterprises.AcknowledgeNotificationSet, unless the notification set is empty. Notifications that * are not acknowledged within the 20 seconds will eventually be included again in the response to * another PullNotificationSet request, and those that are never acknowledged will ultimately be * deleted according to the Google Cloud Platform Pub/Sub system policy. Multiple requests might be * performed concurrently to retrieve notifications, in which case the pending notifications (if * any) will be split among each caller, if any are pending. If no notifications are present, an * empty notification list is returned. Subsequent requests may return more notifications once they * become available. * * Create a request for the method "enterprises.pullNotificationSet". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link PullNotificationSet#execute()} method to invoke the remote * operation. * * @return the request */ public PullNotificationSet pullNotificationSet() throws java.io.IOException { PullNotificationSet result = new PullNotificationSet(); initialize(result); return result; } public class PullNotificationSet extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.NotificationSet> { private static final String REST_PATH = "enterprises/pullNotificationSet"; /** * Pulls and returns a notification set for the enterprises associated with the service account * authenticated for the request. The notification set may be empty if no notification are * pending. A notification set returned needs to be acknowledged within 20 seconds by calling * Enterprises.AcknowledgeNotificationSet, unless the notification set is empty. Notifications * that are not acknowledged within the 20 seconds will eventually be included again in the * response to another PullNotificationSet request, and those that are never acknowledged will * ultimately be deleted according to the Google Cloud Platform Pub/Sub system policy. Multiple * requests might be performed concurrently to retrieve notifications, in which case the pending * notifications (if any) will be split among each caller, if any are pending. If no notifications * are present, an empty notification list is returned. Subsequent requests may return more * notifications once they become available. * * Create a request for the method "enterprises.pullNotificationSet". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link PullNotificationSet#execute()} method to invoke the * remote operation. <p> {@link PullNotificationSet#initialize(com.google.api.client.googleapis.se * rvices.AbstractGoogleClientRequest)} must be called to initialize this instance immediately * after invoking the constructor. </p> * * @since 1.13 */ protected PullNotificationSet() { super(AndroidEnterprise.this, "POST", REST_PATH, null, com.google.api.services.androidenterprise.model.NotificationSet.class); } @Override public PullNotificationSet setAlt(java.lang.String alt) { return (PullNotificationSet) super.setAlt(alt); } @Override public PullNotificationSet setFields(java.lang.String fields) { return (PullNotificationSet) super.setFields(fields); } @Override public PullNotificationSet setKey(java.lang.String key) { return (PullNotificationSet) super.setKey(key); } @Override public PullNotificationSet setOauthToken(java.lang.String oauthToken) { return (PullNotificationSet) super.setOauthToken(oauthToken); } @Override public PullNotificationSet setPrettyPrint(java.lang.Boolean prettyPrint) { return (PullNotificationSet) super.setPrettyPrint(prettyPrint); } @Override public PullNotificationSet setQuotaUser(java.lang.String quotaUser) { return (PullNotificationSet) super.setQuotaUser(quotaUser); } @Override public PullNotificationSet setUserIp(java.lang.String userIp) { return (PullNotificationSet) super.setUserIp(userIp); } /** * The request mode for pulling notifications. Specifying waitForNotifications will cause the * request to block and wait until one or more notifications are present, or return an empty * notification list if no notifications are present after some time. Speciying * returnImmediately will cause the request to immediately return the pending notifications, * or an empty list if no notifications are present. If omitted, defaults to * waitForNotifications. */ @com.google.api.client.util.Key private java.lang.String requestMode; /** The request mode for pulling notifications. Specifying waitForNotifications will cause the request to block and wait until one or more notifications are present, or return an empty notification list if no notifications are present after some time. Speciying returnImmediately will cause the request to immediately return the pending notifications, or an empty list if no notifications are present. If omitted, defaults to waitForNotifications. */ public java.lang.String getRequestMode() { return requestMode; } /** * The request mode for pulling notifications. Specifying waitForNotifications will cause the * request to block and wait until one or more notifications are present, or return an empty * notification list if no notifications are present after some time. Speciying * returnImmediately will cause the request to immediately return the pending notifications, * or an empty list if no notifications are present. If omitted, defaults to * waitForNotifications. */ public PullNotificationSet setRequestMode(java.lang.String requestMode) { this.requestMode = requestMode; return this; } @Override public PullNotificationSet set(String parameterName, Object value) { return (PullNotificationSet) super.set(parameterName, value); } } /** * Sends a test notification to validate the EMM integration with the Google Cloud Pub/Sub service * for this enterprise. * * Create a request for the method "enterprises.sendTestPushNotification". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link SendTestPushNotification#execute()} method to invoke the * remote operation. * * @param enterpriseId The ID of the enterprise. * @return the request */ public SendTestPushNotification sendTestPushNotification(java.lang.String enterpriseId) throws java.io.IOException { SendTestPushNotification result = new SendTestPushNotification(enterpriseId); initialize(result); return result; } public class SendTestPushNotification extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.EnterprisesSendTestPushNotificationResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/sendTestPushNotification"; /** * Sends a test notification to validate the EMM integration with the Google Cloud Pub/Sub service * for this enterprise. * * Create a request for the method "enterprises.sendTestPushNotification". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link SendTestPushNotification#execute()} method to invoke * the remote operation. <p> {@link SendTestPushNotification#initialize(com.google.api.client.goog * leapis.services.AbstractGoogleClientRequest)} must be called to initialize this instance * immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @since 1.13 */ protected SendTestPushNotification(java.lang.String enterpriseId) { super(AndroidEnterprise.this, "POST", REST_PATH, null, com.google.api.services.androidenterprise.model.EnterprisesSendTestPushNotificationResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public SendTestPushNotification setAlt(java.lang.String alt) { return (SendTestPushNotification) super.setAlt(alt); } @Override public SendTestPushNotification setFields(java.lang.String fields) { return (SendTestPushNotification) super.setFields(fields); } @Override public SendTestPushNotification setKey(java.lang.String key) { return (SendTestPushNotification) super.setKey(key); } @Override public SendTestPushNotification setOauthToken(java.lang.String oauthToken) { return (SendTestPushNotification) super.setOauthToken(oauthToken); } @Override public SendTestPushNotification setPrettyPrint(java.lang.Boolean prettyPrint) { return (SendTestPushNotification) super.setPrettyPrint(prettyPrint); } @Override public SendTestPushNotification setQuotaUser(java.lang.String quotaUser) { return (SendTestPushNotification) super.setQuotaUser(quotaUser); } @Override public SendTestPushNotification setUserIp(java.lang.String userIp) { return (SendTestPushNotification) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public SendTestPushNotification setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public SendTestPushNotification set(String parameterName, Object value) { return (SendTestPushNotification) super.set(parameterName, value); } } /** * Sets the account that will be used to authenticate to the API as the enterprise. * * Create a request for the method "enterprises.setAccount". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link SetAccount#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.EnterpriseAccount} * @return the request */ public SetAccount setAccount(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.EnterpriseAccount content) throws java.io.IOException { SetAccount result = new SetAccount(enterpriseId, content); initialize(result); return result; } public class SetAccount extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.EnterpriseAccount> { private static final String REST_PATH = "enterprises/{enterpriseId}/account"; /** * Sets the account that will be used to authenticate to the API as the enterprise. * * Create a request for the method "enterprises.setAccount". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link SetAccount#execute()} method to invoke the remote * operation. <p> {@link * SetAccount#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.EnterpriseAccount} * @since 1.13 */ protected SetAccount(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.EnterpriseAccount content) { super(AndroidEnterprise.this, "PUT", REST_PATH, content, com.google.api.services.androidenterprise.model.EnterpriseAccount.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public SetAccount setAlt(java.lang.String alt) { return (SetAccount) super.setAlt(alt); } @Override public SetAccount setFields(java.lang.String fields) { return (SetAccount) super.setFields(fields); } @Override public SetAccount setKey(java.lang.String key) { return (SetAccount) super.setKey(key); } @Override public SetAccount setOauthToken(java.lang.String oauthToken) { return (SetAccount) super.setOauthToken(oauthToken); } @Override public SetAccount setPrettyPrint(java.lang.Boolean prettyPrint) { return (SetAccount) super.setPrettyPrint(prettyPrint); } @Override public SetAccount setQuotaUser(java.lang.String quotaUser) { return (SetAccount) super.setQuotaUser(quotaUser); } @Override public SetAccount setUserIp(java.lang.String userIp) { return (SetAccount) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public SetAccount setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public SetAccount set(String parameterName, Object value) { return (SetAccount) super.set(parameterName, value); } } /** * Sets the store layout for the enterprise. By default, storeLayoutType is set to "basic" and the * basic store layout is enabled. The basic layout only contains apps approved by the admin, and * that have been added to the available product set for a user (using the setAvailableProductSet * call). Apps on the page are sorted in order of their product ID value. If you create a custom * store layout (by setting storeLayoutType = "custom" and setting a homepage), the basic store * layout is disabled. * * Create a request for the method "enterprises.setStoreLayout". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link SetStoreLayout#execute()} method to invoke the remote * operation. * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.StoreLayout} * @return the request */ public SetStoreLayout setStoreLayout(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.StoreLayout content) throws java.io.IOException { SetStoreLayout result = new SetStoreLayout(enterpriseId, content); initialize(result); return result; } public class SetStoreLayout extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.StoreLayout> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout"; /** * Sets the store layout for the enterprise. By default, storeLayoutType is set to "basic" and the * basic store layout is enabled. The basic layout only contains apps approved by the admin, and * that have been added to the available product set for a user (using the setAvailableProductSet * call). Apps on the page are sorted in order of their product ID value. If you create a custom * store layout (by setting storeLayoutType = "custom" and setting a homepage), the basic store * layout is disabled. * * Create a request for the method "enterprises.setStoreLayout". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link SetStoreLayout#execute()} method to invoke the remote * operation. <p> {@link SetStoreLayout#initialize(com.google.api.client.googleapis.services.Abstr * actGoogleClientRequest)} must be called to initialize this instance immediately after invoking * the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.StoreLayout} * @since 1.13 */ protected SetStoreLayout(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.StoreLayout content) { super(AndroidEnterprise.this, "PUT", REST_PATH, content, com.google.api.services.androidenterprise.model.StoreLayout.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public SetStoreLayout setAlt(java.lang.String alt) { return (SetStoreLayout) super.setAlt(alt); } @Override public SetStoreLayout setFields(java.lang.String fields) { return (SetStoreLayout) super.setFields(fields); } @Override public SetStoreLayout setKey(java.lang.String key) { return (SetStoreLayout) super.setKey(key); } @Override public SetStoreLayout setOauthToken(java.lang.String oauthToken) { return (SetStoreLayout) super.setOauthToken(oauthToken); } @Override public SetStoreLayout setPrettyPrint(java.lang.Boolean prettyPrint) { return (SetStoreLayout) super.setPrettyPrint(prettyPrint); } @Override public SetStoreLayout setQuotaUser(java.lang.String quotaUser) { return (SetStoreLayout) super.setQuotaUser(quotaUser); } @Override public SetStoreLayout setUserIp(java.lang.String userIp) { return (SetStoreLayout) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public SetStoreLayout setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public SetStoreLayout set(String parameterName, Object value) { return (SetStoreLayout) super.set(parameterName, value); } } /** * Unenrolls an enterprise from the calling EMM. * * Create a request for the method "enterprises.unenroll". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Unenroll#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @return the request */ public Unenroll unenroll(java.lang.String enterpriseId) throws java.io.IOException { Unenroll result = new Unenroll(enterpriseId); initialize(result); return result; } public class Unenroll extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/unenroll"; /** * Unenrolls an enterprise from the calling EMM. * * Create a request for the method "enterprises.unenroll". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Unenroll#execute()} method to invoke the remote * operation. <p> {@link * Unenroll#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @since 1.13 */ protected Unenroll(java.lang.String enterpriseId) { super(AndroidEnterprise.this, "POST", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public Unenroll setAlt(java.lang.String alt) { return (Unenroll) super.setAlt(alt); } @Override public Unenroll setFields(java.lang.String fields) { return (Unenroll) super.setFields(fields); } @Override public Unenroll setKey(java.lang.String key) { return (Unenroll) super.setKey(key); } @Override public Unenroll setOauthToken(java.lang.String oauthToken) { return (Unenroll) super.setOauthToken(oauthToken); } @Override public Unenroll setPrettyPrint(java.lang.Boolean prettyPrint) { return (Unenroll) super.setPrettyPrint(prettyPrint); } @Override public Unenroll setQuotaUser(java.lang.String quotaUser) { return (Unenroll) super.setQuotaUser(quotaUser); } @Override public Unenroll setUserIp(java.lang.String userIp) { return (Unenroll) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Unenroll setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public Unenroll set(String parameterName, Object value) { return (Unenroll) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Entitlements collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Entitlements.List request = androidenterprise.entitlements().list(parameters ...)} * </pre> * * @return the resource collection */ public Entitlements entitlements() { return new Entitlements(); } /** * The "entitlements" collection of methods. */ public class Entitlements { /** * Removes an entitlement to an app for a user. * * Create a request for the method "entitlements.delete". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param entitlementId The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". * @return the request */ public Delete delete(java.lang.String enterpriseId, java.lang.String userId, java.lang.String entitlementId) throws java.io.IOException { Delete result = new Delete(enterpriseId, userId, entitlementId); initialize(result); return result; } public class Delete extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/entitlements/{entitlementId}"; /** * Removes an entitlement to an app for a user. * * Create a request for the method "entitlements.delete". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Delete#execute()} method to invoke the remote * operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param entitlementId The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". * @since 1.13 */ protected Delete(java.lang.String enterpriseId, java.lang.String userId, java.lang.String entitlementId) { super(AndroidEnterprise.this, "DELETE", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.entitlementId = com.google.api.client.util.Preconditions.checkNotNull(entitlementId, "Required parameter entitlementId must be specified."); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUserIp(java.lang.String userIp) { return (Delete) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Delete setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Delete setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String entitlementId; /** The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". */ public java.lang.String getEntitlementId() { return entitlementId; } /** The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". */ public Delete setEntitlementId(java.lang.String entitlementId) { this.entitlementId = entitlementId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Retrieves details of an entitlement. * * Create a request for the method "entitlements.get". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param entitlementId The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". * @return the request */ public Get get(java.lang.String enterpriseId, java.lang.String userId, java.lang.String entitlementId) throws java.io.IOException { Get result = new Get(enterpriseId, userId, entitlementId); initialize(result); return result; } public class Get extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Entitlement> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/entitlements/{entitlementId}"; /** * Retrieves details of an entitlement. * * Create a request for the method "entitlements.get". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param entitlementId The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". * @since 1.13 */ protected Get(java.lang.String enterpriseId, java.lang.String userId, java.lang.String entitlementId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.Entitlement.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.entitlementId = com.google.api.client.util.Preconditions.checkNotNull(entitlementId, "Required parameter entitlementId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUserIp(java.lang.String userIp) { return (Get) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Get setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Get setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String entitlementId; /** The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". */ public java.lang.String getEntitlementId() { return entitlementId; } /** The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". */ public Get setEntitlementId(java.lang.String entitlementId) { this.entitlementId = entitlementId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists all entitlements for the specified user. Only the ID is set. * * Create a request for the method "entitlements.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @return the request */ public List list(java.lang.String enterpriseId, java.lang.String userId) throws java.io.IOException { List result = new List(enterpriseId, userId); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.EntitlementsListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/entitlements"; /** * Lists all entitlements for the specified user. Only the ID is set. * * Create a request for the method "entitlements.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @since 1.13 */ protected List(java.lang.String enterpriseId, java.lang.String userId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.EntitlementsListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public List setUserId(java.lang.String userId) { this.userId = userId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Adds or updates an entitlement to an app for a user. This method supports patch semantics. * * Create a request for the method "entitlements.patch". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param entitlementId The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.Entitlement} * @return the request */ public Patch patch(java.lang.String enterpriseId, java.lang.String userId, java.lang.String entitlementId, com.google.api.services.androidenterprise.model.Entitlement content) throws java.io.IOException { Patch result = new Patch(enterpriseId, userId, entitlementId, content); initialize(result); return result; } public class Patch extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Entitlement> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/entitlements/{entitlementId}"; /** * Adds or updates an entitlement to an app for a user. This method supports patch semantics. * * Create a request for the method "entitlements.patch". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Patch#execute()} method to invoke the remote * operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param entitlementId The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.Entitlement} * @since 1.13 */ protected Patch(java.lang.String enterpriseId, java.lang.String userId, java.lang.String entitlementId, com.google.api.services.androidenterprise.model.Entitlement content) { super(AndroidEnterprise.this, "PATCH", REST_PATH, content, com.google.api.services.androidenterprise.model.Entitlement.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.entitlementId = com.google.api.client.util.Preconditions.checkNotNull(entitlementId, "Required parameter entitlementId must be specified."); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUserIp(java.lang.String userIp) { return (Patch) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Patch setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Patch setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String entitlementId; /** The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". */ public java.lang.String getEntitlementId() { return entitlementId; } /** The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". */ public Patch setEntitlementId(java.lang.String entitlementId) { this.entitlementId = entitlementId; return this; } /** * Set to true to also install the product on all the user's devices where possible. Failure * to install on one or more devices will not prevent this operation from returning * successfully, as long as the entitlement was successfully assigned to the user. */ @com.google.api.client.util.Key private java.lang.Boolean install; /** Set to true to also install the product on all the user's devices where possible. Failure to install on one or more devices will not prevent this operation from returning successfully, as long as the entitlement was successfully assigned to the user. */ public java.lang.Boolean getInstall() { return install; } /** * Set to true to also install the product on all the user's devices where possible. Failure * to install on one or more devices will not prevent this operation from returning * successfully, as long as the entitlement was successfully assigned to the user. */ public Patch setInstall(java.lang.Boolean install) { this.install = install; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * Adds or updates an entitlement to an app for a user. * * Create a request for the method "entitlements.update". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param entitlementId The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.Entitlement} * @return the request */ public Update update(java.lang.String enterpriseId, java.lang.String userId, java.lang.String entitlementId, com.google.api.services.androidenterprise.model.Entitlement content) throws java.io.IOException { Update result = new Update(enterpriseId, userId, entitlementId, content); initialize(result); return result; } public class Update extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Entitlement> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/entitlements/{entitlementId}"; /** * Adds or updates an entitlement to an app for a user. * * Create a request for the method "entitlements.update". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Update#execute()} method to invoke the remote * operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param entitlementId The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.Entitlement} * @since 1.13 */ protected Update(java.lang.String enterpriseId, java.lang.String userId, java.lang.String entitlementId, com.google.api.services.androidenterprise.model.Entitlement content) { super(AndroidEnterprise.this, "PUT", REST_PATH, content, com.google.api.services.androidenterprise.model.Entitlement.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.entitlementId = com.google.api.client.util.Preconditions.checkNotNull(entitlementId, "Required parameter entitlementId must be specified."); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUserIp(java.lang.String userIp) { return (Update) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Update setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Update setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String entitlementId; /** The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". */ public java.lang.String getEntitlementId() { return entitlementId; } /** The ID of the entitlement (a product ID), e.g. "app:com.google.android.gm". */ public Update setEntitlementId(java.lang.String entitlementId) { this.entitlementId = entitlementId; return this; } /** * Set to true to also install the product on all the user's devices where possible. Failure * to install on one or more devices will not prevent this operation from returning * successfully, as long as the entitlement was successfully assigned to the user. */ @com.google.api.client.util.Key private java.lang.Boolean install; /** Set to true to also install the product on all the user's devices where possible. Failure to install on one or more devices will not prevent this operation from returning successfully, as long as the entitlement was successfully assigned to the user. */ public java.lang.Boolean getInstall() { return install; } /** * Set to true to also install the product on all the user's devices where possible. Failure * to install on one or more devices will not prevent this operation from returning * successfully, as long as the entitlement was successfully assigned to the user. */ public Update setInstall(java.lang.Boolean install) { this.install = install; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Grouplicenses collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Grouplicenses.List request = androidenterprise.grouplicenses().list(parameters ...)} * </pre> * * @return the resource collection */ public Grouplicenses grouplicenses() { return new Grouplicenses(); } /** * The "grouplicenses" collection of methods. */ public class Grouplicenses { /** * Retrieves details of an enterprise's group license for a product. * * Create a request for the method "grouplicenses.get". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param groupLicenseId The ID of the product the group license is for, e.g. "app:com.google.android.gm". * @return the request */ public Get get(java.lang.String enterpriseId, java.lang.String groupLicenseId) throws java.io.IOException { Get result = new Get(enterpriseId, groupLicenseId); initialize(result); return result; } public class Get extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.GroupLicense> { private static final String REST_PATH = "enterprises/{enterpriseId}/groupLicenses/{groupLicenseId}"; /** * Retrieves details of an enterprise's group license for a product. * * Create a request for the method "grouplicenses.get". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param groupLicenseId The ID of the product the group license is for, e.g. "app:com.google.android.gm". * @since 1.13 */ protected Get(java.lang.String enterpriseId, java.lang.String groupLicenseId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.GroupLicense.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.groupLicenseId = com.google.api.client.util.Preconditions.checkNotNull(groupLicenseId, "Required parameter groupLicenseId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUserIp(java.lang.String userIp) { return (Get) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Get setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the product the group license is for, e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String groupLicenseId; /** The ID of the product the group license is for, e.g. "app:com.google.android.gm". */ public java.lang.String getGroupLicenseId() { return groupLicenseId; } /** The ID of the product the group license is for, e.g. "app:com.google.android.gm". */ public Get setGroupLicenseId(java.lang.String groupLicenseId) { this.groupLicenseId = groupLicenseId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Retrieves IDs of all products for which the enterprise has a group license. * * Create a request for the method "grouplicenses.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @return the request */ public List list(java.lang.String enterpriseId) throws java.io.IOException { List result = new List(enterpriseId); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.GroupLicensesListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/groupLicenses"; /** * Retrieves IDs of all products for which the enterprise has a group license. * * Create a request for the method "grouplicenses.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @since 1.13 */ protected List(java.lang.String enterpriseId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.GroupLicensesListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Grouplicenseusers collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Grouplicenseusers.List request = androidenterprise.grouplicenseusers().list(parameters ...)} * </pre> * * @return the resource collection */ public Grouplicenseusers grouplicenseusers() { return new Grouplicenseusers(); } /** * The "grouplicenseusers" collection of methods. */ public class Grouplicenseusers { /** * Retrieves the IDs of the users who have been granted entitlements under the license. * * Create a request for the method "grouplicenseusers.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param groupLicenseId The ID of the product the group license is for, e.g. "app:com.google.android.gm". * @return the request */ public List list(java.lang.String enterpriseId, java.lang.String groupLicenseId) throws java.io.IOException { List result = new List(enterpriseId, groupLicenseId); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.GroupLicenseUsersListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/groupLicenses/{groupLicenseId}/users"; /** * Retrieves the IDs of the users who have been granted entitlements under the license. * * Create a request for the method "grouplicenseusers.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param groupLicenseId The ID of the product the group license is for, e.g. "app:com.google.android.gm". * @since 1.13 */ protected List(java.lang.String enterpriseId, java.lang.String groupLicenseId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.GroupLicenseUsersListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.groupLicenseId = com.google.api.client.util.Preconditions.checkNotNull(groupLicenseId, "Required parameter groupLicenseId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the product the group license is for, e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String groupLicenseId; /** The ID of the product the group license is for, e.g. "app:com.google.android.gm". */ public java.lang.String getGroupLicenseId() { return groupLicenseId; } /** The ID of the product the group license is for, e.g. "app:com.google.android.gm". */ public List setGroupLicenseId(java.lang.String groupLicenseId) { this.groupLicenseId = groupLicenseId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Installs collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Installs.List request = androidenterprise.installs().list(parameters ...)} * </pre> * * @return the resource collection */ public Installs installs() { return new Installs(); } /** * The "installs" collection of methods. */ public class Installs { /** * Requests to remove an app from a device. A call to get or list will still show the app as * installed on the device until it is actually removed. * * Create a request for the method "installs.delete". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param installId The ID of the product represented by the install, e.g. "app:com.google.android.gm". * @return the request */ public Delete delete(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String installId) throws java.io.IOException { Delete result = new Delete(enterpriseId, userId, deviceId, installId); initialize(result); return result; } public class Delete extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/installs/{installId}"; /** * Requests to remove an app from a device. A call to get or list will still show the app as * installed on the device until it is actually removed. * * Create a request for the method "installs.delete". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Delete#execute()} method to invoke the remote * operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param installId The ID of the product represented by the install, e.g. "app:com.google.android.gm". * @since 1.13 */ protected Delete(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String installId) { super(AndroidEnterprise.this, "DELETE", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); this.installId = com.google.api.client.util.Preconditions.checkNotNull(installId, "Required parameter installId must be specified."); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUserIp(java.lang.String userIp) { return (Delete) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Delete setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Delete setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The Android ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The Android ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The Android ID of the device. */ public Delete setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } /** The ID of the product represented by the install, e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String installId; /** The ID of the product represented by the install, e.g. "app:com.google.android.gm". */ public java.lang.String getInstallId() { return installId; } /** The ID of the product represented by the install, e.g. "app:com.google.android.gm". */ public Delete setInstallId(java.lang.String installId) { this.installId = installId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Retrieves details of an installation of an app on a device. * * Create a request for the method "installs.get". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param installId The ID of the product represented by the install, e.g. "app:com.google.android.gm". * @return the request */ public Get get(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String installId) throws java.io.IOException { Get result = new Get(enterpriseId, userId, deviceId, installId); initialize(result); return result; } public class Get extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Install> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/installs/{installId}"; /** * Retrieves details of an installation of an app on a device. * * Create a request for the method "installs.get". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param installId The ID of the product represented by the install, e.g. "app:com.google.android.gm". * @since 1.13 */ protected Get(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String installId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.Install.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); this.installId = com.google.api.client.util.Preconditions.checkNotNull(installId, "Required parameter installId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUserIp(java.lang.String userIp) { return (Get) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Get setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Get setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The Android ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The Android ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The Android ID of the device. */ public Get setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } /** The ID of the product represented by the install, e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String installId; /** The ID of the product represented by the install, e.g. "app:com.google.android.gm". */ public java.lang.String getInstallId() { return installId; } /** The ID of the product represented by the install, e.g. "app:com.google.android.gm". */ public Get setInstallId(java.lang.String installId) { this.installId = installId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Retrieves the details of all apps installed on the specified device. * * Create a request for the method "installs.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @return the request */ public List list(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId) throws java.io.IOException { List result = new List(enterpriseId, userId, deviceId); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.InstallsListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/installs"; /** * Retrieves the details of all apps installed on the specified device. * * Create a request for the method "installs.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @since 1.13 */ protected List(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.InstallsListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public List setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The Android ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The Android ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The Android ID of the device. */ public List setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Requests to install the latest version of an app to a device. If the app is already installed, * then it is updated to the latest version if necessary. This method supports patch semantics. * * Create a request for the method "installs.patch". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param installId The ID of the product represented by the install, e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.Install} * @return the request */ public Patch patch(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String installId, com.google.api.services.androidenterprise.model.Install content) throws java.io.IOException { Patch result = new Patch(enterpriseId, userId, deviceId, installId, content); initialize(result); return result; } public class Patch extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Install> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/installs/{installId}"; /** * Requests to install the latest version of an app to a device. If the app is already installed, * then it is updated to the latest version if necessary. This method supports patch semantics. * * Create a request for the method "installs.patch". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Patch#execute()} method to invoke the remote * operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param installId The ID of the product represented by the install, e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.Install} * @since 1.13 */ protected Patch(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String installId, com.google.api.services.androidenterprise.model.Install content) { super(AndroidEnterprise.this, "PATCH", REST_PATH, content, com.google.api.services.androidenterprise.model.Install.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); this.installId = com.google.api.client.util.Preconditions.checkNotNull(installId, "Required parameter installId must be specified."); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUserIp(java.lang.String userIp) { return (Patch) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Patch setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Patch setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The Android ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The Android ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The Android ID of the device. */ public Patch setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } /** The ID of the product represented by the install, e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String installId; /** The ID of the product represented by the install, e.g. "app:com.google.android.gm". */ public java.lang.String getInstallId() { return installId; } /** The ID of the product represented by the install, e.g. "app:com.google.android.gm". */ public Patch setInstallId(java.lang.String installId) { this.installId = installId; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * Requests to install the latest version of an app to a device. If the app is already installed, * then it is updated to the latest version if necessary. * * Create a request for the method "installs.update". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param installId The ID of the product represented by the install, e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.Install} * @return the request */ public Update update(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String installId, com.google.api.services.androidenterprise.model.Install content) throws java.io.IOException { Update result = new Update(enterpriseId, userId, deviceId, installId, content); initialize(result); return result; } public class Update extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Install> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/installs/{installId}"; /** * Requests to install the latest version of an app to a device. If the app is already installed, * then it is updated to the latest version if necessary. * * Create a request for the method "installs.update". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Update#execute()} method to invoke the remote * operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param installId The ID of the product represented by the install, e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.Install} * @since 1.13 */ protected Update(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String installId, com.google.api.services.androidenterprise.model.Install content) { super(AndroidEnterprise.this, "PUT", REST_PATH, content, com.google.api.services.androidenterprise.model.Install.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); this.installId = com.google.api.client.util.Preconditions.checkNotNull(installId, "Required parameter installId must be specified."); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUserIp(java.lang.String userIp) { return (Update) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Update setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Update setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The Android ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The Android ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The Android ID of the device. */ public Update setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } /** The ID of the product represented by the install, e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String installId; /** The ID of the product represented by the install, e.g. "app:com.google.android.gm". */ public java.lang.String getInstallId() { return installId; } /** The ID of the product represented by the install, e.g. "app:com.google.android.gm". */ public Update setInstallId(java.lang.String installId) { this.installId = installId; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Managedconfigurationsfordevice collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Managedconfigurationsfordevice.List request = androidenterprise.managedconfigurationsfordevice().list(parameters ...)} * </pre> * * @return the resource collection */ public Managedconfigurationsfordevice managedconfigurationsfordevice() { return new Managedconfigurationsfordevice(); } /** * The "managedconfigurationsfordevice" collection of methods. */ public class Managedconfigurationsfordevice { /** * Removes a per-device managed configuration for an app for the specified device. * * Create a request for the method "managedconfigurationsfordevice.delete". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param managedConfigurationForDeviceId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @return the request */ public Delete delete(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String managedConfigurationForDeviceId) throws java.io.IOException { Delete result = new Delete(enterpriseId, userId, deviceId, managedConfigurationForDeviceId); initialize(result); return result; } public class Delete extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/managedConfigurationsForDevice/{managedConfigurationForDeviceId}"; /** * Removes a per-device managed configuration for an app for the specified device. * * Create a request for the method "managedconfigurationsfordevice.delete". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Delete#execute()} method to invoke the remote * operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param managedConfigurationForDeviceId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @since 1.13 */ protected Delete(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String managedConfigurationForDeviceId) { super(AndroidEnterprise.this, "DELETE", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); this.managedConfigurationForDeviceId = com.google.api.client.util.Preconditions.checkNotNull(managedConfigurationForDeviceId, "Required parameter managedConfigurationForDeviceId must be specified."); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUserIp(java.lang.String userIp) { return (Delete) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Delete setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Delete setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The Android ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The Android ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The Android ID of the device. */ public Delete setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String managedConfigurationForDeviceId; /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public java.lang.String getManagedConfigurationForDeviceId() { return managedConfigurationForDeviceId; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public Delete setManagedConfigurationForDeviceId(java.lang.String managedConfigurationForDeviceId) { this.managedConfigurationForDeviceId = managedConfigurationForDeviceId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Retrieves details of a per-device managed configuration. * * Create a request for the method "managedconfigurationsfordevice.get". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param managedConfigurationForDeviceId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @return the request */ public Get get(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String managedConfigurationForDeviceId) throws java.io.IOException { Get result = new Get(enterpriseId, userId, deviceId, managedConfigurationForDeviceId); initialize(result); return result; } public class Get extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ManagedConfiguration> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/managedConfigurationsForDevice/{managedConfigurationForDeviceId}"; /** * Retrieves details of a per-device managed configuration. * * Create a request for the method "managedconfigurationsfordevice.get". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param managedConfigurationForDeviceId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @since 1.13 */ protected Get(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String managedConfigurationForDeviceId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.ManagedConfiguration.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); this.managedConfigurationForDeviceId = com.google.api.client.util.Preconditions.checkNotNull(managedConfigurationForDeviceId, "Required parameter managedConfigurationForDeviceId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUserIp(java.lang.String userIp) { return (Get) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Get setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Get setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The Android ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The Android ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The Android ID of the device. */ public Get setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String managedConfigurationForDeviceId; /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public java.lang.String getManagedConfigurationForDeviceId() { return managedConfigurationForDeviceId; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public Get setManagedConfigurationForDeviceId(java.lang.String managedConfigurationForDeviceId) { this.managedConfigurationForDeviceId = managedConfigurationForDeviceId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists all the per-device managed configurations for the specified device. Only the ID is set. * * Create a request for the method "managedconfigurationsfordevice.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @return the request */ public List list(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId) throws java.io.IOException { List result = new List(enterpriseId, userId, deviceId); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ManagedConfigurationsForDeviceListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/managedConfigurationsForDevice"; /** * Lists all the per-device managed configurations for the specified device. Only the ID is set. * * Create a request for the method "managedconfigurationsfordevice.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @since 1.13 */ protected List(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.ManagedConfigurationsForDeviceListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public List setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The Android ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The Android ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The Android ID of the device. */ public List setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Adds or updates a per-device managed configuration for an app for the specified device. This * method supports patch semantics. * * Create a request for the method "managedconfigurationsfordevice.patch". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param managedConfigurationForDeviceId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.ManagedConfiguration} * @return the request */ public Patch patch(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String managedConfigurationForDeviceId, com.google.api.services.androidenterprise.model.ManagedConfiguration content) throws java.io.IOException { Patch result = new Patch(enterpriseId, userId, deviceId, managedConfigurationForDeviceId, content); initialize(result); return result; } public class Patch extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ManagedConfiguration> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/managedConfigurationsForDevice/{managedConfigurationForDeviceId}"; /** * Adds or updates a per-device managed configuration for an app for the specified device. This * method supports patch semantics. * * Create a request for the method "managedconfigurationsfordevice.patch". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Patch#execute()} method to invoke the remote * operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param managedConfigurationForDeviceId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.ManagedConfiguration} * @since 1.13 */ protected Patch(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String managedConfigurationForDeviceId, com.google.api.services.androidenterprise.model.ManagedConfiguration content) { super(AndroidEnterprise.this, "PATCH", REST_PATH, content, com.google.api.services.androidenterprise.model.ManagedConfiguration.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); this.managedConfigurationForDeviceId = com.google.api.client.util.Preconditions.checkNotNull(managedConfigurationForDeviceId, "Required parameter managedConfigurationForDeviceId must be specified."); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUserIp(java.lang.String userIp) { return (Patch) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Patch setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Patch setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The Android ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The Android ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The Android ID of the device. */ public Patch setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String managedConfigurationForDeviceId; /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public java.lang.String getManagedConfigurationForDeviceId() { return managedConfigurationForDeviceId; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public Patch setManagedConfigurationForDeviceId(java.lang.String managedConfigurationForDeviceId) { this.managedConfigurationForDeviceId = managedConfigurationForDeviceId; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * Adds or updates a per-device managed configuration for an app for the specified device. * * Create a request for the method "managedconfigurationsfordevice.update". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param managedConfigurationForDeviceId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.ManagedConfiguration} * @return the request */ public Update update(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String managedConfigurationForDeviceId, com.google.api.services.androidenterprise.model.ManagedConfiguration content) throws java.io.IOException { Update result = new Update(enterpriseId, userId, deviceId, managedConfigurationForDeviceId, content); initialize(result); return result; } public class Update extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ManagedConfiguration> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/managedConfigurationsForDevice/{managedConfigurationForDeviceId}"; /** * Adds or updates a per-device managed configuration for an app for the specified device. * * Create a request for the method "managedconfigurationsfordevice.update". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Update#execute()} method to invoke the remote * operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param deviceId The Android ID of the device. * @param managedConfigurationForDeviceId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.ManagedConfiguration} * @since 1.13 */ protected Update(java.lang.String enterpriseId, java.lang.String userId, java.lang.String deviceId, java.lang.String managedConfigurationForDeviceId, com.google.api.services.androidenterprise.model.ManagedConfiguration content) { super(AndroidEnterprise.this, "PUT", REST_PATH, content, com.google.api.services.androidenterprise.model.ManagedConfiguration.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.deviceId = com.google.api.client.util.Preconditions.checkNotNull(deviceId, "Required parameter deviceId must be specified."); this.managedConfigurationForDeviceId = com.google.api.client.util.Preconditions.checkNotNull(managedConfigurationForDeviceId, "Required parameter managedConfigurationForDeviceId must be specified."); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUserIp(java.lang.String userIp) { return (Update) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Update setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Update setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The Android ID of the device. */ @com.google.api.client.util.Key private java.lang.String deviceId; /** The Android ID of the device. */ public java.lang.String getDeviceId() { return deviceId; } /** The Android ID of the device. */ public Update setDeviceId(java.lang.String deviceId) { this.deviceId = deviceId; return this; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String managedConfigurationForDeviceId; /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public java.lang.String getManagedConfigurationForDeviceId() { return managedConfigurationForDeviceId; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public Update setManagedConfigurationForDeviceId(java.lang.String managedConfigurationForDeviceId) { this.managedConfigurationForDeviceId = managedConfigurationForDeviceId; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Managedconfigurationsforuser collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Managedconfigurationsforuser.List request = androidenterprise.managedconfigurationsforuser().list(parameters ...)} * </pre> * * @return the resource collection */ public Managedconfigurationsforuser managedconfigurationsforuser() { return new Managedconfigurationsforuser(); } /** * The "managedconfigurationsforuser" collection of methods. */ public class Managedconfigurationsforuser { /** * Removes a per-user managed configuration for an app for the specified user. * * Create a request for the method "managedconfigurationsforuser.delete". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param managedConfigurationForUserId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @return the request */ public Delete delete(java.lang.String enterpriseId, java.lang.String userId, java.lang.String managedConfigurationForUserId) throws java.io.IOException { Delete result = new Delete(enterpriseId, userId, managedConfigurationForUserId); initialize(result); return result; } public class Delete extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/managedConfigurationsForUser/{managedConfigurationForUserId}"; /** * Removes a per-user managed configuration for an app for the specified user. * * Create a request for the method "managedconfigurationsforuser.delete". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Delete#execute()} method to invoke the remote * operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param managedConfigurationForUserId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @since 1.13 */ protected Delete(java.lang.String enterpriseId, java.lang.String userId, java.lang.String managedConfigurationForUserId) { super(AndroidEnterprise.this, "DELETE", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.managedConfigurationForUserId = com.google.api.client.util.Preconditions.checkNotNull(managedConfigurationForUserId, "Required parameter managedConfigurationForUserId must be specified."); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUserIp(java.lang.String userIp) { return (Delete) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Delete setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Delete setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String managedConfigurationForUserId; /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public java.lang.String getManagedConfigurationForUserId() { return managedConfigurationForUserId; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public Delete setManagedConfigurationForUserId(java.lang.String managedConfigurationForUserId) { this.managedConfigurationForUserId = managedConfigurationForUserId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Retrieves details of a per-user managed configuration for an app for the specified user. * * Create a request for the method "managedconfigurationsforuser.get". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param managedConfigurationForUserId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @return the request */ public Get get(java.lang.String enterpriseId, java.lang.String userId, java.lang.String managedConfigurationForUserId) throws java.io.IOException { Get result = new Get(enterpriseId, userId, managedConfigurationForUserId); initialize(result); return result; } public class Get extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ManagedConfiguration> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/managedConfigurationsForUser/{managedConfigurationForUserId}"; /** * Retrieves details of a per-user managed configuration for an app for the specified user. * * Create a request for the method "managedconfigurationsforuser.get". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param managedConfigurationForUserId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @since 1.13 */ protected Get(java.lang.String enterpriseId, java.lang.String userId, java.lang.String managedConfigurationForUserId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.ManagedConfiguration.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.managedConfigurationForUserId = com.google.api.client.util.Preconditions.checkNotNull(managedConfigurationForUserId, "Required parameter managedConfigurationForUserId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUserIp(java.lang.String userIp) { return (Get) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Get setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Get setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String managedConfigurationForUserId; /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public java.lang.String getManagedConfigurationForUserId() { return managedConfigurationForUserId; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public Get setManagedConfigurationForUserId(java.lang.String managedConfigurationForUserId) { this.managedConfigurationForUserId = managedConfigurationForUserId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists all the per-user managed configurations for the specified user. Only the ID is set. * * Create a request for the method "managedconfigurationsforuser.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @return the request */ public List list(java.lang.String enterpriseId, java.lang.String userId) throws java.io.IOException { List result = new List(enterpriseId, userId); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ManagedConfigurationsForUserListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/managedConfigurationsForUser"; /** * Lists all the per-user managed configurations for the specified user. Only the ID is set. * * Create a request for the method "managedconfigurationsforuser.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @since 1.13 */ protected List(java.lang.String enterpriseId, java.lang.String userId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.ManagedConfigurationsForUserListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public List setUserId(java.lang.String userId) { this.userId = userId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Adds or updates the managed configuration settings for an app for the specified user. If you * support the Managed configurations iframe, you can apply managed configurations to a user by * specifying an mcmId and its associated configuration variables (if any) in the request. * Alternatively, all EMMs can apply managed configurations by passing a list of managed properties. * This method supports patch semantics. * * Create a request for the method "managedconfigurationsforuser.patch". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param managedConfigurationForUserId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.ManagedConfiguration} * @return the request */ public Patch patch(java.lang.String enterpriseId, java.lang.String userId, java.lang.String managedConfigurationForUserId, com.google.api.services.androidenterprise.model.ManagedConfiguration content) throws java.io.IOException { Patch result = new Patch(enterpriseId, userId, managedConfigurationForUserId, content); initialize(result); return result; } public class Patch extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ManagedConfiguration> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/managedConfigurationsForUser/{managedConfigurationForUserId}"; /** * Adds or updates the managed configuration settings for an app for the specified user. If you * support the Managed configurations iframe, you can apply managed configurations to a user by * specifying an mcmId and its associated configuration variables (if any) in the request. * Alternatively, all EMMs can apply managed configurations by passing a list of managed * properties. This method supports patch semantics. * * Create a request for the method "managedconfigurationsforuser.patch". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Patch#execute()} method to invoke the remote * operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param managedConfigurationForUserId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.ManagedConfiguration} * @since 1.13 */ protected Patch(java.lang.String enterpriseId, java.lang.String userId, java.lang.String managedConfigurationForUserId, com.google.api.services.androidenterprise.model.ManagedConfiguration content) { super(AndroidEnterprise.this, "PATCH", REST_PATH, content, com.google.api.services.androidenterprise.model.ManagedConfiguration.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.managedConfigurationForUserId = com.google.api.client.util.Preconditions.checkNotNull(managedConfigurationForUserId, "Required parameter managedConfigurationForUserId must be specified."); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUserIp(java.lang.String userIp) { return (Patch) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Patch setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Patch setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String managedConfigurationForUserId; /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public java.lang.String getManagedConfigurationForUserId() { return managedConfigurationForUserId; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public Patch setManagedConfigurationForUserId(java.lang.String managedConfigurationForUserId) { this.managedConfigurationForUserId = managedConfigurationForUserId; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * Adds or updates the managed configuration settings for an app for the specified user. If you * support the Managed configurations iframe, you can apply managed configurations to a user by * specifying an mcmId and its associated configuration variables (if any) in the request. * Alternatively, all EMMs can apply managed configurations by passing a list of managed properties. * * Create a request for the method "managedconfigurationsforuser.update". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param managedConfigurationForUserId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.ManagedConfiguration} * @return the request */ public Update update(java.lang.String enterpriseId, java.lang.String userId, java.lang.String managedConfigurationForUserId, com.google.api.services.androidenterprise.model.ManagedConfiguration content) throws java.io.IOException { Update result = new Update(enterpriseId, userId, managedConfigurationForUserId, content); initialize(result); return result; } public class Update extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ManagedConfiguration> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/managedConfigurationsForUser/{managedConfigurationForUserId}"; /** * Adds or updates the managed configuration settings for an app for the specified user. If you * support the Managed configurations iframe, you can apply managed configurations to a user by * specifying an mcmId and its associated configuration variables (if any) in the request. * Alternatively, all EMMs can apply managed configurations by passing a list of managed * properties. * * Create a request for the method "managedconfigurationsforuser.update". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Update#execute()} method to invoke the remote * operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param managedConfigurationForUserId The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". * @param content the {@link com.google.api.services.androidenterprise.model.ManagedConfiguration} * @since 1.13 */ protected Update(java.lang.String enterpriseId, java.lang.String userId, java.lang.String managedConfigurationForUserId, com.google.api.services.androidenterprise.model.ManagedConfiguration content) { super(AndroidEnterprise.this, "PUT", REST_PATH, content, com.google.api.services.androidenterprise.model.ManagedConfiguration.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); this.managedConfigurationForUserId = com.google.api.client.util.Preconditions.checkNotNull(managedConfigurationForUserId, "Required parameter managedConfigurationForUserId must be specified."); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUserIp(java.lang.String userIp) { return (Update) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Update setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Update setUserId(java.lang.String userId) { this.userId = userId; return this; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String managedConfigurationForUserId; /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public java.lang.String getManagedConfigurationForUserId() { return managedConfigurationForUserId; } /** The ID of the managed configuration (a product ID), e.g. "app:com.google.android.gm". */ public Update setManagedConfigurationForUserId(java.lang.String managedConfigurationForUserId) { this.managedConfigurationForUserId = managedConfigurationForUserId; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Managedconfigurationssettings collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Managedconfigurationssettings.List request = androidenterprise.managedconfigurationssettings().list(parameters ...)} * </pre> * * @return the resource collection */ public Managedconfigurationssettings managedconfigurationssettings() { return new Managedconfigurationssettings(); } /** * The "managedconfigurationssettings" collection of methods. */ public class Managedconfigurationssettings { /** * Lists all the managed configurations settings for the specified app. Only the ID and the name is * set. * * Create a request for the method "managedconfigurationssettings.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product for which the managed configurations settings applies to. * @return the request */ public List list(java.lang.String enterpriseId, java.lang.String productId) throws java.io.IOException { List result = new List(enterpriseId, productId); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ManagedConfigurationsSettingsListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/products/{productId}/managedConfigurationsSettings"; /** * Lists all the managed configurations settings for the specified app. Only the ID and the name * is set. * * Create a request for the method "managedconfigurationssettings.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product for which the managed configurations settings applies to. * @since 1.13 */ protected List(java.lang.String enterpriseId, java.lang.String productId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.ManagedConfigurationsSettingsListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.productId = com.google.api.client.util.Preconditions.checkNotNull(productId, "Required parameter productId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the product for which the managed configurations settings applies to. */ @com.google.api.client.util.Key private java.lang.String productId; /** The ID of the product for which the managed configurations settings applies to. */ public java.lang.String getProductId() { return productId; } /** The ID of the product for which the managed configurations settings applies to. */ public List setProductId(java.lang.String productId) { this.productId = productId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Permissions collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Permissions.List request = androidenterprise.permissions().list(parameters ...)} * </pre> * * @return the resource collection */ public Permissions permissions() { return new Permissions(); } /** * The "permissions" collection of methods. */ public class Permissions { /** * Retrieves details of an Android app permission for display to an enterprise admin. * * Create a request for the method "permissions.get". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param permissionId The ID of the permission. * @return the request */ public Get get(java.lang.String permissionId) throws java.io.IOException { Get result = new Get(permissionId); initialize(result); return result; } public class Get extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Permission> { private static final String REST_PATH = "permissions/{permissionId}"; /** * Retrieves details of an Android app permission for display to an enterprise admin. * * Create a request for the method "permissions.get". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param permissionId The ID of the permission. * @since 1.13 */ protected Get(java.lang.String permissionId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.Permission.class); this.permissionId = com.google.api.client.util.Preconditions.checkNotNull(permissionId, "Required parameter permissionId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUserIp(java.lang.String userIp) { return (Get) super.setUserIp(userIp); } /** The ID of the permission. */ @com.google.api.client.util.Key private java.lang.String permissionId; /** The ID of the permission. */ public java.lang.String getPermissionId() { return permissionId; } /** The ID of the permission. */ public Get setPermissionId(java.lang.String permissionId) { this.permissionId = permissionId; return this; } /** The BCP47 tag for the user's preferred language (e.g. "en-US", "de") */ @com.google.api.client.util.Key private java.lang.String language; /** The BCP47 tag for the user's preferred language (e.g. "en-US", "de") */ public java.lang.String getLanguage() { return language; } /** The BCP47 tag for the user's preferred language (e.g. "en-US", "de") */ public Get setLanguage(java.lang.String language) { this.language = language; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Products collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Products.List request = androidenterprise.products().list(parameters ...)} * </pre> * * @return the resource collection */ public Products products() { return new Products(); } /** * The "products" collection of methods. */ public class Products { /** * Approves the specified product and the relevant app permissions, if any. The maximum number of * products that you can approve per enterprise customer is 1,000. * * To learn how to use managed Google Play to design and create a store layout to display approved * products to your users, see Store Layout Design. * * Create a request for the method "products.approve". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Approve#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product. * @param content the {@link com.google.api.services.androidenterprise.model.ProductsApproveRequest} * @return the request */ public Approve approve(java.lang.String enterpriseId, java.lang.String productId, com.google.api.services.androidenterprise.model.ProductsApproveRequest content) throws java.io.IOException { Approve result = new Approve(enterpriseId, productId, content); initialize(result); return result; } public class Approve extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/products/{productId}/approve"; /** * Approves the specified product and the relevant app permissions, if any. The maximum number of * products that you can approve per enterprise customer is 1,000. * * To learn how to use managed Google Play to design and create a store layout to display approved * products to your users, see Store Layout Design. * * Create a request for the method "products.approve". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Approve#execute()} method to invoke the remote * operation. <p> {@link * Approve#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product. * @param content the {@link com.google.api.services.androidenterprise.model.ProductsApproveRequest} * @since 1.13 */ protected Approve(java.lang.String enterpriseId, java.lang.String productId, com.google.api.services.androidenterprise.model.ProductsApproveRequest content) { super(AndroidEnterprise.this, "POST", REST_PATH, content, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.productId = com.google.api.client.util.Preconditions.checkNotNull(productId, "Required parameter productId must be specified."); } @Override public Approve setAlt(java.lang.String alt) { return (Approve) super.setAlt(alt); } @Override public Approve setFields(java.lang.String fields) { return (Approve) super.setFields(fields); } @Override public Approve setKey(java.lang.String key) { return (Approve) super.setKey(key); } @Override public Approve setOauthToken(java.lang.String oauthToken) { return (Approve) super.setOauthToken(oauthToken); } @Override public Approve setPrettyPrint(java.lang.Boolean prettyPrint) { return (Approve) super.setPrettyPrint(prettyPrint); } @Override public Approve setQuotaUser(java.lang.String quotaUser) { return (Approve) super.setQuotaUser(quotaUser); } @Override public Approve setUserIp(java.lang.String userIp) { return (Approve) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Approve setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the product. */ @com.google.api.client.util.Key private java.lang.String productId; /** The ID of the product. */ public java.lang.String getProductId() { return productId; } /** The ID of the product. */ public Approve setProductId(java.lang.String productId) { this.productId = productId; return this; } @Override public Approve set(String parameterName, Object value) { return (Approve) super.set(parameterName, value); } } /** * Generates a URL that can be rendered in an iframe to display the permissions (if any) of a * product. An enterprise admin must view these permissions and accept them on behalf of their * organization in order to approve that product. * * Admins should accept the displayed permissions by interacting with a separate UI element in the * EMM console, which in turn should trigger the use of this URL as the approvalUrlInfo.approvalUrl * property in a Products.approve call to approve the product. This URL can only be used to display * permissions for up to 1 day. * * Create a request for the method "products.generateApprovalUrl". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link GenerateApprovalUrl#execute()} method to invoke the remote * operation. * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product. * @return the request */ public GenerateApprovalUrl generateApprovalUrl(java.lang.String enterpriseId, java.lang.String productId) throws java.io.IOException { GenerateApprovalUrl result = new GenerateApprovalUrl(enterpriseId, productId); initialize(result); return result; } public class GenerateApprovalUrl extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ProductsGenerateApprovalUrlResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/products/{productId}/generateApprovalUrl"; /** * Generates a URL that can be rendered in an iframe to display the permissions (if any) of a * product. An enterprise admin must view these permissions and accept them on behalf of their * organization in order to approve that product. * * Admins should accept the displayed permissions by interacting with a separate UI element in the * EMM console, which in turn should trigger the use of this URL as the * approvalUrlInfo.approvalUrl property in a Products.approve call to approve the product. This * URL can only be used to display permissions for up to 1 day. * * Create a request for the method "products.generateApprovalUrl". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link GenerateApprovalUrl#execute()} method to invoke the * remote operation. <p> {@link GenerateApprovalUrl#initialize(com.google.api.client.googleapis.se * rvices.AbstractGoogleClientRequest)} must be called to initialize this instance immediately * after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product. * @since 1.13 */ protected GenerateApprovalUrl(java.lang.String enterpriseId, java.lang.String productId) { super(AndroidEnterprise.this, "POST", REST_PATH, null, com.google.api.services.androidenterprise.model.ProductsGenerateApprovalUrlResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.productId = com.google.api.client.util.Preconditions.checkNotNull(productId, "Required parameter productId must be specified."); } @Override public GenerateApprovalUrl setAlt(java.lang.String alt) { return (GenerateApprovalUrl) super.setAlt(alt); } @Override public GenerateApprovalUrl setFields(java.lang.String fields) { return (GenerateApprovalUrl) super.setFields(fields); } @Override public GenerateApprovalUrl setKey(java.lang.String key) { return (GenerateApprovalUrl) super.setKey(key); } @Override public GenerateApprovalUrl setOauthToken(java.lang.String oauthToken) { return (GenerateApprovalUrl) super.setOauthToken(oauthToken); } @Override public GenerateApprovalUrl setPrettyPrint(java.lang.Boolean prettyPrint) { return (GenerateApprovalUrl) super.setPrettyPrint(prettyPrint); } @Override public GenerateApprovalUrl setQuotaUser(java.lang.String quotaUser) { return (GenerateApprovalUrl) super.setQuotaUser(quotaUser); } @Override public GenerateApprovalUrl setUserIp(java.lang.String userIp) { return (GenerateApprovalUrl) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public GenerateApprovalUrl setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the product. */ @com.google.api.client.util.Key private java.lang.String productId; /** The ID of the product. */ public java.lang.String getProductId() { return productId; } /** The ID of the product. */ public GenerateApprovalUrl setProductId(java.lang.String productId) { this.productId = productId; return this; } /** * The BCP 47 language code used for permission names and descriptions in the returned iframe, * for instance "en-US". */ @com.google.api.client.util.Key private java.lang.String languageCode; /** The BCP 47 language code used for permission names and descriptions in the returned iframe, for instance "en-US". */ public java.lang.String getLanguageCode() { return languageCode; } /** * The BCP 47 language code used for permission names and descriptions in the returned iframe, * for instance "en-US". */ public GenerateApprovalUrl setLanguageCode(java.lang.String languageCode) { this.languageCode = languageCode; return this; } @Override public GenerateApprovalUrl set(String parameterName, Object value) { return (GenerateApprovalUrl) super.set(parameterName, value); } } /** * Retrieves details of a product for display to an enterprise admin. * * Create a request for the method "products.get". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product, e.g. "app:com.google.android.gm". * @return the request */ public Get get(java.lang.String enterpriseId, java.lang.String productId) throws java.io.IOException { Get result = new Get(enterpriseId, productId); initialize(result); return result; } public class Get extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.Product> { private static final String REST_PATH = "enterprises/{enterpriseId}/products/{productId}"; /** * Retrieves details of a product for display to an enterprise admin. * * Create a request for the method "products.get". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product, e.g. "app:com.google.android.gm". * @since 1.13 */ protected Get(java.lang.String enterpriseId, java.lang.String productId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.Product.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.productId = com.google.api.client.util.Preconditions.checkNotNull(productId, "Required parameter productId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUserIp(java.lang.String userIp) { return (Get) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Get setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the product, e.g. "app:com.google.android.gm". */ @com.google.api.client.util.Key private java.lang.String productId; /** The ID of the product, e.g. "app:com.google.android.gm". */ public java.lang.String getProductId() { return productId; } /** The ID of the product, e.g. "app:com.google.android.gm". */ public Get setProductId(java.lang.String productId) { this.productId = productId; return this; } /** The BCP47 tag for the user's preferred language (e.g. "en-US", "de"). */ @com.google.api.client.util.Key private java.lang.String language; /** The BCP47 tag for the user's preferred language (e.g. "en-US", "de"). */ public java.lang.String getLanguage() { return language; } /** The BCP47 tag for the user's preferred language (e.g. "en-US", "de"). */ public Get setLanguage(java.lang.String language) { this.language = language; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Retrieves the schema that defines the configurable properties for this product. All products have * a schema, but this schema may be empty if no managed configurations have been defined. This * schema can be used to populate a UI that allows an admin to configure the product. To apply a * managed configuration based on the schema obtained using this API, see Managed Configurations * through Play. * * Create a request for the method "products.getAppRestrictionsSchema". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link GetAppRestrictionsSchema#execute()} method to invoke the * remote operation. * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product. * @return the request */ public GetAppRestrictionsSchema getAppRestrictionsSchema(java.lang.String enterpriseId, java.lang.String productId) throws java.io.IOException { GetAppRestrictionsSchema result = new GetAppRestrictionsSchema(enterpriseId, productId); initialize(result); return result; } public class GetAppRestrictionsSchema extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.AppRestrictionsSchema> { private static final String REST_PATH = "enterprises/{enterpriseId}/products/{productId}/appRestrictionsSchema"; /** * Retrieves the schema that defines the configurable properties for this product. All products * have a schema, but this schema may be empty if no managed configurations have been defined. * This schema can be used to populate a UI that allows an admin to configure the product. To * apply a managed configuration based on the schema obtained using this API, see Managed * Configurations through Play. * * Create a request for the method "products.getAppRestrictionsSchema". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link GetAppRestrictionsSchema#execute()} method to invoke * the remote operation. <p> {@link GetAppRestrictionsSchema#initialize(com.google.api.client.goog * leapis.services.AbstractGoogleClientRequest)} must be called to initialize this instance * immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product. * @since 1.13 */ protected GetAppRestrictionsSchema(java.lang.String enterpriseId, java.lang.String productId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.AppRestrictionsSchema.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.productId = com.google.api.client.util.Preconditions.checkNotNull(productId, "Required parameter productId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public GetAppRestrictionsSchema setAlt(java.lang.String alt) { return (GetAppRestrictionsSchema) super.setAlt(alt); } @Override public GetAppRestrictionsSchema setFields(java.lang.String fields) { return (GetAppRestrictionsSchema) super.setFields(fields); } @Override public GetAppRestrictionsSchema setKey(java.lang.String key) { return (GetAppRestrictionsSchema) super.setKey(key); } @Override public GetAppRestrictionsSchema setOauthToken(java.lang.String oauthToken) { return (GetAppRestrictionsSchema) super.setOauthToken(oauthToken); } @Override public GetAppRestrictionsSchema setPrettyPrint(java.lang.Boolean prettyPrint) { return (GetAppRestrictionsSchema) super.setPrettyPrint(prettyPrint); } @Override public GetAppRestrictionsSchema setQuotaUser(java.lang.String quotaUser) { return (GetAppRestrictionsSchema) super.setQuotaUser(quotaUser); } @Override public GetAppRestrictionsSchema setUserIp(java.lang.String userIp) { return (GetAppRestrictionsSchema) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public GetAppRestrictionsSchema setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the product. */ @com.google.api.client.util.Key private java.lang.String productId; /** The ID of the product. */ public java.lang.String getProductId() { return productId; } /** The ID of the product. */ public GetAppRestrictionsSchema setProductId(java.lang.String productId) { this.productId = productId; return this; } /** The BCP47 tag for the user's preferred language (e.g. "en-US", "de"). */ @com.google.api.client.util.Key private java.lang.String language; /** The BCP47 tag for the user's preferred language (e.g. "en-US", "de"). */ public java.lang.String getLanguage() { return language; } /** The BCP47 tag for the user's preferred language (e.g. "en-US", "de"). */ public GetAppRestrictionsSchema setLanguage(java.lang.String language) { this.language = language; return this; } @Override public GetAppRestrictionsSchema set(String parameterName, Object value) { return (GetAppRestrictionsSchema) super.set(parameterName, value); } } /** * Retrieves the Android app permissions required by this app. * * Create a request for the method "products.getPermissions". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link GetPermissions#execute()} method to invoke the remote * operation. * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product. * @return the request */ public GetPermissions getPermissions(java.lang.String enterpriseId, java.lang.String productId) throws java.io.IOException { GetPermissions result = new GetPermissions(enterpriseId, productId); initialize(result); return result; } public class GetPermissions extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ProductPermissions> { private static final String REST_PATH = "enterprises/{enterpriseId}/products/{productId}/permissions"; /** * Retrieves the Android app permissions required by this app. * * Create a request for the method "products.getPermissions". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link GetPermissions#execute()} method to invoke the remote * operation. <p> {@link GetPermissions#initialize(com.google.api.client.googleapis.services.Abstr * actGoogleClientRequest)} must be called to initialize this instance immediately after invoking * the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product. * @since 1.13 */ protected GetPermissions(java.lang.String enterpriseId, java.lang.String productId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.ProductPermissions.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.productId = com.google.api.client.util.Preconditions.checkNotNull(productId, "Required parameter productId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public GetPermissions setAlt(java.lang.String alt) { return (GetPermissions) super.setAlt(alt); } @Override public GetPermissions setFields(java.lang.String fields) { return (GetPermissions) super.setFields(fields); } @Override public GetPermissions setKey(java.lang.String key) { return (GetPermissions) super.setKey(key); } @Override public GetPermissions setOauthToken(java.lang.String oauthToken) { return (GetPermissions) super.setOauthToken(oauthToken); } @Override public GetPermissions setPrettyPrint(java.lang.Boolean prettyPrint) { return (GetPermissions) super.setPrettyPrint(prettyPrint); } @Override public GetPermissions setQuotaUser(java.lang.String quotaUser) { return (GetPermissions) super.setQuotaUser(quotaUser); } @Override public GetPermissions setUserIp(java.lang.String userIp) { return (GetPermissions) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public GetPermissions setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the product. */ @com.google.api.client.util.Key private java.lang.String productId; /** The ID of the product. */ public java.lang.String getProductId() { return productId; } /** The ID of the product. */ public GetPermissions setProductId(java.lang.String productId) { this.productId = productId; return this; } @Override public GetPermissions set(String parameterName, Object value) { return (GetPermissions) super.set(parameterName, value); } } /** * Finds approved products that match a query, or all approved products if there is no query. * * Create a request for the method "products.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @return the request */ public List list(java.lang.String enterpriseId) throws java.io.IOException { List result = new List(enterpriseId); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ProductsListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/products"; /** * Finds approved products that match a query, or all approved products if there is no query. * * Create a request for the method "products.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @since 1.13 */ protected List(java.lang.String enterpriseId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.ProductsListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** * Specifies whether to search among all products (false) or among only products that have * been approved (true). Only "true" is supported, and should be specified. */ @com.google.api.client.util.Key private java.lang.Boolean approved; /** Specifies whether to search among all products (false) or among only products that have been approved (true). Only "true" is supported, and should be specified. */ public java.lang.Boolean getApproved() { return approved; } /** * Specifies whether to search among all products (false) or among only products that have * been approved (true). Only "true" is supported, and should be specified. */ public List setApproved(java.lang.Boolean approved) { this.approved = approved; return this; } /** * The BCP47 tag for the user's preferred language (e.g. "en-US", "de"). Results are returned * in the language best matching the preferred language. */ @com.google.api.client.util.Key private java.lang.String language; /** The BCP47 tag for the user's preferred language (e.g. "en-US", "de"). Results are returned in the language best matching the preferred language. */ public java.lang.String getLanguage() { return language; } /** * The BCP47 tag for the user's preferred language (e.g. "en-US", "de"). Results are returned * in the language best matching the preferred language. */ public List setLanguage(java.lang.String language) { this.language = language; return this; } /** * Specifies the maximum number of products that can be returned per request. If not * specified, uses a default value of 100, which is also the maximum retrievable within a * single response. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** Specifies the maximum number of products that can be returned per request. If not specified, uses a default value of 100, which is also the maximum retrievable within a single response. */ public java.lang.Long getMaxResults() { return maxResults; } /** * Specifies the maximum number of products that can be returned per request. If not * specified, uses a default value of 100, which is also the maximum retrievable within a * single response. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** * The search query as typed in the Google Play store search box. If omitted, all approved * apps will be returned (using the pagination parameters), including apps that are not * available in the store (e.g. unpublished apps). */ @com.google.api.client.util.Key private java.lang.String query; /** The search query as typed in the Google Play store search box. If omitted, all approved apps will be returned (using the pagination parameters), including apps that are not available in the store (e.g. unpublished apps). */ public java.lang.String getQuery() { return query; } /** * The search query as typed in the Google Play store search box. If omitted, all approved * apps will be returned (using the pagination parameters), including apps that are not * available in the store (e.g. unpublished apps). */ public List setQuery(java.lang.String query) { this.query = query; return this; } /** * A pagination token is contained in a request's response when there are more products. The * token can be used in a subsequent request to obtain more products, and so forth. This * parameter cannot be used in the initial request. */ @com.google.api.client.util.Key private java.lang.String token; /** A pagination token is contained in a request's response when there are more products. The token can be used in a subsequent request to obtain more products, and so forth. This parameter cannot be used in the initial request. */ public java.lang.String getToken() { return token; } /** * A pagination token is contained in a request's response when there are more products. The * token can be used in a subsequent request to obtain more products, and so forth. This * parameter cannot be used in the initial request. */ public List setToken(java.lang.String token) { this.token = token; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Unapproves the specified product (and the relevant app permissions, if any) * * Create a request for the method "products.unapprove". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Unapprove#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product. * @return the request */ public Unapprove unapprove(java.lang.String enterpriseId, java.lang.String productId) throws java.io.IOException { Unapprove result = new Unapprove(enterpriseId, productId); initialize(result); return result; } public class Unapprove extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/products/{productId}/unapprove"; /** * Unapproves the specified product (and the relevant app permissions, if any) * * Create a request for the method "products.unapprove". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Unapprove#execute()} method to invoke the remote * operation. <p> {@link * Unapprove#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param productId The ID of the product. * @since 1.13 */ protected Unapprove(java.lang.String enterpriseId, java.lang.String productId) { super(AndroidEnterprise.this, "POST", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.productId = com.google.api.client.util.Preconditions.checkNotNull(productId, "Required parameter productId must be specified."); } @Override public Unapprove setAlt(java.lang.String alt) { return (Unapprove) super.setAlt(alt); } @Override public Unapprove setFields(java.lang.String fields) { return (Unapprove) super.setFields(fields); } @Override public Unapprove setKey(java.lang.String key) { return (Unapprove) super.setKey(key); } @Override public Unapprove setOauthToken(java.lang.String oauthToken) { return (Unapprove) super.setOauthToken(oauthToken); } @Override public Unapprove setPrettyPrint(java.lang.Boolean prettyPrint) { return (Unapprove) super.setPrettyPrint(prettyPrint); } @Override public Unapprove setQuotaUser(java.lang.String quotaUser) { return (Unapprove) super.setQuotaUser(quotaUser); } @Override public Unapprove setUserIp(java.lang.String userIp) { return (Unapprove) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Unapprove setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the product. */ @com.google.api.client.util.Key private java.lang.String productId; /** The ID of the product. */ public java.lang.String getProductId() { return productId; } /** The ID of the product. */ public Unapprove setProductId(java.lang.String productId) { this.productId = productId; return this; } @Override public Unapprove set(String parameterName, Object value) { return (Unapprove) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Serviceaccountkeys collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Serviceaccountkeys.List request = androidenterprise.serviceaccountkeys().list(parameters ...)} * </pre> * * @return the resource collection */ public Serviceaccountkeys serviceaccountkeys() { return new Serviceaccountkeys(); } /** * The "serviceaccountkeys" collection of methods. */ public class Serviceaccountkeys { /** * Removes and invalidates the specified credentials for the service account associated with this * enterprise. The calling service account must have been retrieved by calling * Enterprises.GetServiceAccount and must have been set as the enterprise service account by calling * Enterprises.SetAccount. * * Create a request for the method "serviceaccountkeys.delete". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param keyId The ID of the key. * @return the request */ public Delete delete(java.lang.String enterpriseId, java.lang.String keyId) throws java.io.IOException { Delete result = new Delete(enterpriseId, keyId); initialize(result); return result; } public class Delete extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/serviceAccountKeys/{keyId}"; /** * Removes and invalidates the specified credentials for the service account associated with this * enterprise. The calling service account must have been retrieved by calling * Enterprises.GetServiceAccount and must have been set as the enterprise service account by * calling Enterprises.SetAccount. * * Create a request for the method "serviceaccountkeys.delete". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Delete#execute()} method to invoke the remote * operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param keyId The ID of the key. * @since 1.13 */ protected Delete(java.lang.String enterpriseId, java.lang.String keyId) { super(AndroidEnterprise.this, "DELETE", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.keyId = com.google.api.client.util.Preconditions.checkNotNull(keyId, "Required parameter keyId must be specified."); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUserIp(java.lang.String userIp) { return (Delete) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Delete setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the key. */ @com.google.api.client.util.Key private java.lang.String keyId; /** The ID of the key. */ public java.lang.String getKeyId() { return keyId; } /** The ID of the key. */ public Delete setKeyId(java.lang.String keyId) { this.keyId = keyId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Generates new credentials for the service account associated with this enterprise. The calling * service account must have been retrieved by calling Enterprises.GetServiceAccount and must have * been set as the enterprise service account by calling Enterprises.SetAccount. * * Only the type of the key should be populated in the resource to be inserted. * * Create a request for the method "serviceaccountkeys.insert". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.ServiceAccountKey} * @return the request */ public Insert insert(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.ServiceAccountKey content) throws java.io.IOException { Insert result = new Insert(enterpriseId, content); initialize(result); return result; } public class Insert extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ServiceAccountKey> { private static final String REST_PATH = "enterprises/{enterpriseId}/serviceAccountKeys"; /** * Generates new credentials for the service account associated with this enterprise. The calling * service account must have been retrieved by calling Enterprises.GetServiceAccount and must have * been set as the enterprise service account by calling Enterprises.SetAccount. * * Only the type of the key should be populated in the resource to be inserted. * * Create a request for the method "serviceaccountkeys.insert". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Insert#execute()} method to invoke the remote * operation. <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.ServiceAccountKey} * @since 1.13 */ protected Insert(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.ServiceAccountKey content) { super(AndroidEnterprise.this, "POST", REST_PATH, content, com.google.api.services.androidenterprise.model.ServiceAccountKey.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); checkRequiredParameter(content, "content"); checkRequiredParameter(content.getType(), "ServiceAccountKey.getType()"); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUserIp(java.lang.String userIp) { return (Insert) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Insert setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } /** * Lists all active credentials for the service account associated with this enterprise. Only the ID * and key type are returned. The calling service account must have been retrieved by calling * Enterprises.GetServiceAccount and must have been set as the enterprise service account by calling * Enterprises.SetAccount. * * Create a request for the method "serviceaccountkeys.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @return the request */ public List list(java.lang.String enterpriseId) throws java.io.IOException { List result = new List(enterpriseId); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ServiceAccountKeysListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/serviceAccountKeys"; /** * Lists all active credentials for the service account associated with this enterprise. Only the * ID and key type are returned. The calling service account must have been retrieved by calling * Enterprises.GetServiceAccount and must have been set as the enterprise service account by * calling Enterprises.SetAccount. * * Create a request for the method "serviceaccountkeys.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @since 1.13 */ protected List(java.lang.String enterpriseId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.ServiceAccountKeysListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Storelayoutclusters collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Storelayoutclusters.List request = androidenterprise.storelayoutclusters().list(parameters ...)} * </pre> * * @return the resource collection */ public Storelayoutclusters storelayoutclusters() { return new Storelayoutclusters(); } /** * The "storelayoutclusters" collection of methods. */ public class Storelayoutclusters { /** * Deletes a cluster. * * Create a request for the method "storelayoutclusters.delete". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param clusterId The ID of the cluster. * @return the request */ public Delete delete(java.lang.String enterpriseId, java.lang.String pageId, java.lang.String clusterId) throws java.io.IOException { Delete result = new Delete(enterpriseId, pageId, clusterId); initialize(result); return result; } public class Delete extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout/pages/{pageId}/clusters/{clusterId}"; /** * Deletes a cluster. * * Create a request for the method "storelayoutclusters.delete". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Delete#execute()} method to invoke the remote * operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param clusterId The ID of the cluster. * @since 1.13 */ protected Delete(java.lang.String enterpriseId, java.lang.String pageId, java.lang.String clusterId) { super(AndroidEnterprise.this, "DELETE", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified."); this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified."); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUserIp(java.lang.String userIp) { return (Delete) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Delete setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the page. */ @com.google.api.client.util.Key private java.lang.String pageId; /** The ID of the page. */ public java.lang.String getPageId() { return pageId; } /** The ID of the page. */ public Delete setPageId(java.lang.String pageId) { this.pageId = pageId; return this; } /** The ID of the cluster. */ @com.google.api.client.util.Key private java.lang.String clusterId; /** The ID of the cluster. */ public java.lang.String getClusterId() { return clusterId; } /** The ID of the cluster. */ public Delete setClusterId(java.lang.String clusterId) { this.clusterId = clusterId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Retrieves details of a cluster. * * Create a request for the method "storelayoutclusters.get". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param clusterId The ID of the cluster. * @return the request */ public Get get(java.lang.String enterpriseId, java.lang.String pageId, java.lang.String clusterId) throws java.io.IOException { Get result = new Get(enterpriseId, pageId, clusterId); initialize(result); return result; } public class Get extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.StoreCluster> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout/pages/{pageId}/clusters/{clusterId}"; /** * Retrieves details of a cluster. * * Create a request for the method "storelayoutclusters.get". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param clusterId The ID of the cluster. * @since 1.13 */ protected Get(java.lang.String enterpriseId, java.lang.String pageId, java.lang.String clusterId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.StoreCluster.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified."); this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUserIp(java.lang.String userIp) { return (Get) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Get setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the page. */ @com.google.api.client.util.Key private java.lang.String pageId; /** The ID of the page. */ public java.lang.String getPageId() { return pageId; } /** The ID of the page. */ public Get setPageId(java.lang.String pageId) { this.pageId = pageId; return this; } /** The ID of the cluster. */ @com.google.api.client.util.Key private java.lang.String clusterId; /** The ID of the cluster. */ public java.lang.String getClusterId() { return clusterId; } /** The ID of the cluster. */ public Get setClusterId(java.lang.String clusterId) { this.clusterId = clusterId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Inserts a new cluster in a page. * * Create a request for the method "storelayoutclusters.insert". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param content the {@link com.google.api.services.androidenterprise.model.StoreCluster} * @return the request */ public Insert insert(java.lang.String enterpriseId, java.lang.String pageId, com.google.api.services.androidenterprise.model.StoreCluster content) throws java.io.IOException { Insert result = new Insert(enterpriseId, pageId, content); initialize(result); return result; } public class Insert extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.StoreCluster> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout/pages/{pageId}/clusters"; /** * Inserts a new cluster in a page. * * Create a request for the method "storelayoutclusters.insert". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Insert#execute()} method to invoke the remote * operation. <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param content the {@link com.google.api.services.androidenterprise.model.StoreCluster} * @since 1.13 */ protected Insert(java.lang.String enterpriseId, java.lang.String pageId, com.google.api.services.androidenterprise.model.StoreCluster content) { super(AndroidEnterprise.this, "POST", REST_PATH, content, com.google.api.services.androidenterprise.model.StoreCluster.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified."); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUserIp(java.lang.String userIp) { return (Insert) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Insert setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the page. */ @com.google.api.client.util.Key private java.lang.String pageId; /** The ID of the page. */ public java.lang.String getPageId() { return pageId; } /** The ID of the page. */ public Insert setPageId(java.lang.String pageId) { this.pageId = pageId; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } /** * Retrieves the details of all clusters on the specified page. * * Create a request for the method "storelayoutclusters.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @return the request */ public List list(java.lang.String enterpriseId, java.lang.String pageId) throws java.io.IOException { List result = new List(enterpriseId, pageId); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.StoreLayoutClustersListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout/pages/{pageId}/clusters"; /** * Retrieves the details of all clusters on the specified page. * * Create a request for the method "storelayoutclusters.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @since 1.13 */ protected List(java.lang.String enterpriseId, java.lang.String pageId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.StoreLayoutClustersListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the page. */ @com.google.api.client.util.Key private java.lang.String pageId; /** The ID of the page. */ public java.lang.String getPageId() { return pageId; } /** The ID of the page. */ public List setPageId(java.lang.String pageId) { this.pageId = pageId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates a cluster. This method supports patch semantics. * * Create a request for the method "storelayoutclusters.patch". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param clusterId The ID of the cluster. * @param content the {@link com.google.api.services.androidenterprise.model.StoreCluster} * @return the request */ public Patch patch(java.lang.String enterpriseId, java.lang.String pageId, java.lang.String clusterId, com.google.api.services.androidenterprise.model.StoreCluster content) throws java.io.IOException { Patch result = new Patch(enterpriseId, pageId, clusterId, content); initialize(result); return result; } public class Patch extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.StoreCluster> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout/pages/{pageId}/clusters/{clusterId}"; /** * Updates a cluster. This method supports patch semantics. * * Create a request for the method "storelayoutclusters.patch". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Patch#execute()} method to invoke the remote * operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param clusterId The ID of the cluster. * @param content the {@link com.google.api.services.androidenterprise.model.StoreCluster} * @since 1.13 */ protected Patch(java.lang.String enterpriseId, java.lang.String pageId, java.lang.String clusterId, com.google.api.services.androidenterprise.model.StoreCluster content) { super(AndroidEnterprise.this, "PATCH", REST_PATH, content, com.google.api.services.androidenterprise.model.StoreCluster.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified."); this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified."); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUserIp(java.lang.String userIp) { return (Patch) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Patch setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the page. */ @com.google.api.client.util.Key private java.lang.String pageId; /** The ID of the page. */ public java.lang.String getPageId() { return pageId; } /** The ID of the page. */ public Patch setPageId(java.lang.String pageId) { this.pageId = pageId; return this; } /** The ID of the cluster. */ @com.google.api.client.util.Key private java.lang.String clusterId; /** The ID of the cluster. */ public java.lang.String getClusterId() { return clusterId; } /** The ID of the cluster. */ public Patch setClusterId(java.lang.String clusterId) { this.clusterId = clusterId; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * Updates a cluster. * * Create a request for the method "storelayoutclusters.update". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param clusterId The ID of the cluster. * @param content the {@link com.google.api.services.androidenterprise.model.StoreCluster} * @return the request */ public Update update(java.lang.String enterpriseId, java.lang.String pageId, java.lang.String clusterId, com.google.api.services.androidenterprise.model.StoreCluster content) throws java.io.IOException { Update result = new Update(enterpriseId, pageId, clusterId, content); initialize(result); return result; } public class Update extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.StoreCluster> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout/pages/{pageId}/clusters/{clusterId}"; /** * Updates a cluster. * * Create a request for the method "storelayoutclusters.update". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Update#execute()} method to invoke the remote * operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param clusterId The ID of the cluster. * @param content the {@link com.google.api.services.androidenterprise.model.StoreCluster} * @since 1.13 */ protected Update(java.lang.String enterpriseId, java.lang.String pageId, java.lang.String clusterId, com.google.api.services.androidenterprise.model.StoreCluster content) { super(AndroidEnterprise.this, "PUT", REST_PATH, content, com.google.api.services.androidenterprise.model.StoreCluster.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified."); this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified."); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUserIp(java.lang.String userIp) { return (Update) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Update setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the page. */ @com.google.api.client.util.Key private java.lang.String pageId; /** The ID of the page. */ public java.lang.String getPageId() { return pageId; } /** The ID of the page. */ public Update setPageId(java.lang.String pageId) { this.pageId = pageId; return this; } /** The ID of the cluster. */ @com.google.api.client.util.Key private java.lang.String clusterId; /** The ID of the cluster. */ public java.lang.String getClusterId() { return clusterId; } /** The ID of the cluster. */ public Update setClusterId(java.lang.String clusterId) { this.clusterId = clusterId; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Storelayoutpages collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Storelayoutpages.List request = androidenterprise.storelayoutpages().list(parameters ...)} * </pre> * * @return the resource collection */ public Storelayoutpages storelayoutpages() { return new Storelayoutpages(); } /** * The "storelayoutpages" collection of methods. */ public class Storelayoutpages { /** * Deletes a store page. * * Create a request for the method "storelayoutpages.delete". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @return the request */ public Delete delete(java.lang.String enterpriseId, java.lang.String pageId) throws java.io.IOException { Delete result = new Delete(enterpriseId, pageId); initialize(result); return result; } public class Delete extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout/pages/{pageId}"; /** * Deletes a store page. * * Create a request for the method "storelayoutpages.delete". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Delete#execute()} method to invoke the remote * operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @since 1.13 */ protected Delete(java.lang.String enterpriseId, java.lang.String pageId) { super(AndroidEnterprise.this, "DELETE", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified."); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUserIp(java.lang.String userIp) { return (Delete) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Delete setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the page. */ @com.google.api.client.util.Key private java.lang.String pageId; /** The ID of the page. */ public java.lang.String getPageId() { return pageId; } /** The ID of the page. */ public Delete setPageId(java.lang.String pageId) { this.pageId = pageId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Retrieves details of a store page. * * Create a request for the method "storelayoutpages.get". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @return the request */ public Get get(java.lang.String enterpriseId, java.lang.String pageId) throws java.io.IOException { Get result = new Get(enterpriseId, pageId); initialize(result); return result; } public class Get extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.StorePage> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout/pages/{pageId}"; /** * Retrieves details of a store page. * * Create a request for the method "storelayoutpages.get". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @since 1.13 */ protected Get(java.lang.String enterpriseId, java.lang.String pageId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.StorePage.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUserIp(java.lang.String userIp) { return (Get) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Get setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the page. */ @com.google.api.client.util.Key private java.lang.String pageId; /** The ID of the page. */ public java.lang.String getPageId() { return pageId; } /** The ID of the page. */ public Get setPageId(java.lang.String pageId) { this.pageId = pageId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Inserts a new store page. * * Create a request for the method "storelayoutpages.insert". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.StorePage} * @return the request */ public Insert insert(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.StorePage content) throws java.io.IOException { Insert result = new Insert(enterpriseId, content); initialize(result); return result; } public class Insert extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.StorePage> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout/pages"; /** * Inserts a new store page. * * Create a request for the method "storelayoutpages.insert". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Insert#execute()} method to invoke the remote * operation. <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.StorePage} * @since 1.13 */ protected Insert(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.StorePage content) { super(AndroidEnterprise.this, "POST", REST_PATH, content, com.google.api.services.androidenterprise.model.StorePage.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUserIp(java.lang.String userIp) { return (Insert) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Insert setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } /** * Retrieves the details of all pages in the store. * * Create a request for the method "storelayoutpages.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @return the request */ public List list(java.lang.String enterpriseId) throws java.io.IOException { List result = new List(enterpriseId); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.StoreLayoutPagesListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout/pages"; /** * Retrieves the details of all pages in the store. * * Create a request for the method "storelayoutpages.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @since 1.13 */ protected List(java.lang.String enterpriseId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.StoreLayoutPagesListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates the content of a store page. This method supports patch semantics. * * Create a request for the method "storelayoutpages.patch". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param content the {@link com.google.api.services.androidenterprise.model.StorePage} * @return the request */ public Patch patch(java.lang.String enterpriseId, java.lang.String pageId, com.google.api.services.androidenterprise.model.StorePage content) throws java.io.IOException { Patch result = new Patch(enterpriseId, pageId, content); initialize(result); return result; } public class Patch extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.StorePage> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout/pages/{pageId}"; /** * Updates the content of a store page. This method supports patch semantics. * * Create a request for the method "storelayoutpages.patch". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Patch#execute()} method to invoke the remote * operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param content the {@link com.google.api.services.androidenterprise.model.StorePage} * @since 1.13 */ protected Patch(java.lang.String enterpriseId, java.lang.String pageId, com.google.api.services.androidenterprise.model.StorePage content) { super(AndroidEnterprise.this, "PATCH", REST_PATH, content, com.google.api.services.androidenterprise.model.StorePage.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified."); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUserIp(java.lang.String userIp) { return (Patch) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Patch setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the page. */ @com.google.api.client.util.Key private java.lang.String pageId; /** The ID of the page. */ public java.lang.String getPageId() { return pageId; } /** The ID of the page. */ public Patch setPageId(java.lang.String pageId) { this.pageId = pageId; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * Updates the content of a store page. * * Create a request for the method "storelayoutpages.update". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param content the {@link com.google.api.services.androidenterprise.model.StorePage} * @return the request */ public Update update(java.lang.String enterpriseId, java.lang.String pageId, com.google.api.services.androidenterprise.model.StorePage content) throws java.io.IOException { Update result = new Update(enterpriseId, pageId, content); initialize(result); return result; } public class Update extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.StorePage> { private static final String REST_PATH = "enterprises/{enterpriseId}/storeLayout/pages/{pageId}"; /** * Updates the content of a store page. * * Create a request for the method "storelayoutpages.update". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Update#execute()} method to invoke the remote * operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param pageId The ID of the page. * @param content the {@link com.google.api.services.androidenterprise.model.StorePage} * @since 1.13 */ protected Update(java.lang.String enterpriseId, java.lang.String pageId, com.google.api.services.androidenterprise.model.StorePage content) { super(AndroidEnterprise.this, "PUT", REST_PATH, content, com.google.api.services.androidenterprise.model.StorePage.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified."); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUserIp(java.lang.String userIp) { return (Update) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Update setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the page. */ @com.google.api.client.util.Key private java.lang.String pageId; /** The ID of the page. */ public java.lang.String getPageId() { return pageId; } /** The ID of the page. */ public Update setPageId(java.lang.String pageId) { this.pageId = pageId; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Users collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Users.List request = androidenterprise.users().list(parameters ...)} * </pre> * * @return the resource collection */ public Users users() { return new Users(); } /** * The "users" collection of methods. */ public class Users { /** * Deleted an EMM-managed user. * * Create a request for the method "users.delete". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @return the request */ public Delete delete(java.lang.String enterpriseId, java.lang.String userId) throws java.io.IOException { Delete result = new Delete(enterpriseId, userId); initialize(result); return result; } public class Delete extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}"; /** * Deleted an EMM-managed user. * * Create a request for the method "users.delete". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Delete#execute()} method to invoke the remote * operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @since 1.13 */ protected Delete(java.lang.String enterpriseId, java.lang.String userId) { super(AndroidEnterprise.this, "DELETE", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUserIp(java.lang.String userIp) { return (Delete) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Delete setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Delete setUserId(java.lang.String userId) { this.userId = userId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Generates an authentication token which the device policy client can use to provision the given * EMM-managed user account on a device. The generated token is single-use and expires after a few * minutes. * * You can provision a maximum of 10 devices per user. * * This call only works with EMM-managed accounts. * * Create a request for the method "users.generateAuthenticationToken". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link GenerateAuthenticationToken#execute()} method to invoke the * remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @return the request */ public GenerateAuthenticationToken generateAuthenticationToken(java.lang.String enterpriseId, java.lang.String userId) throws java.io.IOException { GenerateAuthenticationToken result = new GenerateAuthenticationToken(enterpriseId, userId); initialize(result); return result; } public class GenerateAuthenticationToken extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.AuthenticationToken> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/authenticationToken"; /** * Generates an authentication token which the device policy client can use to provision the given * EMM-managed user account on a device. The generated token is single-use and expires after a few * minutes. * * You can provision a maximum of 10 devices per user. * * This call only works with EMM-managed accounts. * * Create a request for the method "users.generateAuthenticationToken". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link GenerateAuthenticationToken#execute()} method to * invoke the remote operation. <p> {@link GenerateAuthenticationToken#initialize(com.google.api.c * lient.googleapis.services.AbstractGoogleClientRequest)} must be called to initialize this * instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @since 1.13 */ protected GenerateAuthenticationToken(java.lang.String enterpriseId, java.lang.String userId) { super(AndroidEnterprise.this, "POST", REST_PATH, null, com.google.api.services.androidenterprise.model.AuthenticationToken.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); } @Override public GenerateAuthenticationToken setAlt(java.lang.String alt) { return (GenerateAuthenticationToken) super.setAlt(alt); } @Override public GenerateAuthenticationToken setFields(java.lang.String fields) { return (GenerateAuthenticationToken) super.setFields(fields); } @Override public GenerateAuthenticationToken setKey(java.lang.String key) { return (GenerateAuthenticationToken) super.setKey(key); } @Override public GenerateAuthenticationToken setOauthToken(java.lang.String oauthToken) { return (GenerateAuthenticationToken) super.setOauthToken(oauthToken); } @Override public GenerateAuthenticationToken setPrettyPrint(java.lang.Boolean prettyPrint) { return (GenerateAuthenticationToken) super.setPrettyPrint(prettyPrint); } @Override public GenerateAuthenticationToken setQuotaUser(java.lang.String quotaUser) { return (GenerateAuthenticationToken) super.setQuotaUser(quotaUser); } @Override public GenerateAuthenticationToken setUserIp(java.lang.String userIp) { return (GenerateAuthenticationToken) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public GenerateAuthenticationToken setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public GenerateAuthenticationToken setUserId(java.lang.String userId) { this.userId = userId; return this; } @Override public GenerateAuthenticationToken set(String parameterName, Object value) { return (GenerateAuthenticationToken) super.set(parameterName, value); } } /** * Generates a token (activation code) to allow this user to configure their managed account in the * Android Setup Wizard. Revokes any previously generated token. * * This call only works with Google managed accounts. * * Create a request for the method "users.generateToken". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link GenerateToken#execute()} method to invoke the remote * operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @return the request */ public GenerateToken generateToken(java.lang.String enterpriseId, java.lang.String userId) throws java.io.IOException { GenerateToken result = new GenerateToken(enterpriseId, userId); initialize(result); return result; } public class GenerateToken extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.UserToken> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/token"; /** * Generates a token (activation code) to allow this user to configure their managed account in * the Android Setup Wizard. Revokes any previously generated token. * * This call only works with Google managed accounts. * * Create a request for the method "users.generateToken". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link GenerateToken#execute()} method to invoke the remote * operation. <p> {@link GenerateToken#initialize(com.google.api.client.googleapis.services.Abstra * ctGoogleClientRequest)} must be called to initialize this instance immediately after invoking * the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @since 1.13 */ protected GenerateToken(java.lang.String enterpriseId, java.lang.String userId) { super(AndroidEnterprise.this, "POST", REST_PATH, null, com.google.api.services.androidenterprise.model.UserToken.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); } @Override public GenerateToken setAlt(java.lang.String alt) { return (GenerateToken) super.setAlt(alt); } @Override public GenerateToken setFields(java.lang.String fields) { return (GenerateToken) super.setFields(fields); } @Override public GenerateToken setKey(java.lang.String key) { return (GenerateToken) super.setKey(key); } @Override public GenerateToken setOauthToken(java.lang.String oauthToken) { return (GenerateToken) super.setOauthToken(oauthToken); } @Override public GenerateToken setPrettyPrint(java.lang.Boolean prettyPrint) { return (GenerateToken) super.setPrettyPrint(prettyPrint); } @Override public GenerateToken setQuotaUser(java.lang.String quotaUser) { return (GenerateToken) super.setQuotaUser(quotaUser); } @Override public GenerateToken setUserIp(java.lang.String userIp) { return (GenerateToken) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public GenerateToken setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public GenerateToken setUserId(java.lang.String userId) { this.userId = userId; return this; } @Override public GenerateToken set(String parameterName, Object value) { return (GenerateToken) super.set(parameterName, value); } } /** * Retrieves a user's details. * * Create a request for the method "users.get". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @return the request */ public Get get(java.lang.String enterpriseId, java.lang.String userId) throws java.io.IOException { Get result = new Get(enterpriseId, userId); initialize(result); return result; } public class Get extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.User> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}"; /** * Retrieves a user's details. * * Create a request for the method "users.get". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @since 1.13 */ protected Get(java.lang.String enterpriseId, java.lang.String userId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.User.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUserIp(java.lang.String userIp) { return (Get) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Get setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Get setUserId(java.lang.String userId) { this.userId = userId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Retrieves the set of products a user is entitled to access. * * Create a request for the method "users.getAvailableProductSet". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link GetAvailableProductSet#execute()} method to invoke the * remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @return the request */ public GetAvailableProductSet getAvailableProductSet(java.lang.String enterpriseId, java.lang.String userId) throws java.io.IOException { GetAvailableProductSet result = new GetAvailableProductSet(enterpriseId, userId); initialize(result); return result; } public class GetAvailableProductSet extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ProductSet> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/availableProductSet"; /** * Retrieves the set of products a user is entitled to access. * * Create a request for the method "users.getAvailableProductSet". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link GetAvailableProductSet#execute()} method to invoke the * remote operation. <p> {@link GetAvailableProductSet#initialize(com.google.api.client.googleapis * .services.AbstractGoogleClientRequest)} must be called to initialize this instance immediately * after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @since 1.13 */ protected GetAvailableProductSet(java.lang.String enterpriseId, java.lang.String userId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.ProductSet.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public GetAvailableProductSet setAlt(java.lang.String alt) { return (GetAvailableProductSet) super.setAlt(alt); } @Override public GetAvailableProductSet setFields(java.lang.String fields) { return (GetAvailableProductSet) super.setFields(fields); } @Override public GetAvailableProductSet setKey(java.lang.String key) { return (GetAvailableProductSet) super.setKey(key); } @Override public GetAvailableProductSet setOauthToken(java.lang.String oauthToken) { return (GetAvailableProductSet) super.setOauthToken(oauthToken); } @Override public GetAvailableProductSet setPrettyPrint(java.lang.Boolean prettyPrint) { return (GetAvailableProductSet) super.setPrettyPrint(prettyPrint); } @Override public GetAvailableProductSet setQuotaUser(java.lang.String quotaUser) { return (GetAvailableProductSet) super.setQuotaUser(quotaUser); } @Override public GetAvailableProductSet setUserIp(java.lang.String userIp) { return (GetAvailableProductSet) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public GetAvailableProductSet setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public GetAvailableProductSet setUserId(java.lang.String userId) { this.userId = userId; return this; } @Override public GetAvailableProductSet set(String parameterName, Object value) { return (GetAvailableProductSet) super.set(parameterName, value); } } /** * Creates a new EMM-managed user. * * The Users resource passed in the body of the request should include an accountIdentifier and an * accountType. If a corresponding user already exists with the same account identifier, the user * will be updated with the resource. In this case only the displayName field can be changed. * * Create a request for the method "users.insert". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.User} * @return the request */ public Insert insert(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.User content) throws java.io.IOException { Insert result = new Insert(enterpriseId, content); initialize(result); return result; } public class Insert extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.User> { private static final String REST_PATH = "enterprises/{enterpriseId}/users"; /** * Creates a new EMM-managed user. * * The Users resource passed in the body of the request should include an accountIdentifier and an * accountType. If a corresponding user already exists with the same account identifier, the user * will be updated with the resource. In this case only the displayName field can be changed. * * Create a request for the method "users.insert". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Insert#execute()} method to invoke the remote * operation. <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.User} * @since 1.13 */ protected Insert(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.User content) { super(AndroidEnterprise.this, "POST", REST_PATH, content, com.google.api.services.androidenterprise.model.User.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); checkRequiredParameter(content, "content"); checkRequiredParameter(content.getAccountIdentifier(), "User.getAccountIdentifier()"); checkRequiredParameter(content, "content"); checkRequiredParameter(content.getAccountType(), "User.getAccountType()"); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUserIp(java.lang.String userIp) { return (Insert) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Insert setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } /** * Looks up a user by primary email address. This is only supported for Google-managed users. Lookup * of the id is not needed for EMM-managed users because the id is already returned in the result of * the Users.insert call. * * Create a request for the method "users.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param email The exact primary email address of the user to look up. * @return the request */ public List list(java.lang.String enterpriseId, java.lang.String email) throws java.io.IOException { List result = new List(enterpriseId, email); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.UsersListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/users"; /** * Looks up a user by primary email address. This is only supported for Google-managed users. * Lookup of the id is not needed for EMM-managed users because the id is already returned in the * result of the Users.insert call. * * Create a request for the method "users.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param email The exact primary email address of the user to look up. * @since 1.13 */ protected List(java.lang.String enterpriseId, java.lang.String email) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.UsersListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.email = com.google.api.client.util.Preconditions.checkNotNull(email, "Required parameter email must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The exact primary email address of the user to look up. */ @com.google.api.client.util.Key private java.lang.String email; /** The exact primary email address of the user to look up. */ public java.lang.String getEmail() { return email; } /** The exact primary email address of the user to look up. */ public List setEmail(java.lang.String email) { this.email = email; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates the details of an EMM-managed user. * * Can be used with EMM-managed users only (not Google managed users). Pass the new details in the * Users resource in the request body. Only the displayName field can be changed. Other fields must * either be unset or have the currently active value. This method supports patch semantics. * * Create a request for the method "users.patch". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param content the {@link com.google.api.services.androidenterprise.model.User} * @return the request */ public Patch patch(java.lang.String enterpriseId, java.lang.String userId, com.google.api.services.androidenterprise.model.User content) throws java.io.IOException { Patch result = new Patch(enterpriseId, userId, content); initialize(result); return result; } public class Patch extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.User> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}"; /** * Updates the details of an EMM-managed user. * * Can be used with EMM-managed users only (not Google managed users). Pass the new details in the * Users resource in the request body. Only the displayName field can be changed. Other fields * must either be unset or have the currently active value. This method supports patch semantics. * * Create a request for the method "users.patch". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Patch#execute()} method to invoke the remote * operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param content the {@link com.google.api.services.androidenterprise.model.User} * @since 1.13 */ protected Patch(java.lang.String enterpriseId, java.lang.String userId, com.google.api.services.androidenterprise.model.User content) { super(AndroidEnterprise.this, "PATCH", REST_PATH, content, com.google.api.services.androidenterprise.model.User.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUserIp(java.lang.String userIp) { return (Patch) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Patch setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Patch setUserId(java.lang.String userId) { this.userId = userId; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * Revokes access to all devices currently provisioned to the user. The user will no longer be able * to use the managed Play store on any of their managed devices. * * This call only works with EMM-managed accounts. * * Create a request for the method "users.revokeDeviceAccess". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link RevokeDeviceAccess#execute()} method to invoke the remote * operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @return the request */ public RevokeDeviceAccess revokeDeviceAccess(java.lang.String enterpriseId, java.lang.String userId) throws java.io.IOException { RevokeDeviceAccess result = new RevokeDeviceAccess(enterpriseId, userId); initialize(result); return result; } public class RevokeDeviceAccess extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/deviceAccess"; /** * Revokes access to all devices currently provisioned to the user. The user will no longer be * able to use the managed Play store on any of their managed devices. * * This call only works with EMM-managed accounts. * * Create a request for the method "users.revokeDeviceAccess". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link RevokeDeviceAccess#execute()} method to invoke the * remote operation. <p> {@link RevokeDeviceAccess#initialize(com.google.api.client.googleapis.ser * vices.AbstractGoogleClientRequest)} must be called to initialize this instance immediately * after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @since 1.13 */ protected RevokeDeviceAccess(java.lang.String enterpriseId, java.lang.String userId) { super(AndroidEnterprise.this, "DELETE", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); } @Override public RevokeDeviceAccess setAlt(java.lang.String alt) { return (RevokeDeviceAccess) super.setAlt(alt); } @Override public RevokeDeviceAccess setFields(java.lang.String fields) { return (RevokeDeviceAccess) super.setFields(fields); } @Override public RevokeDeviceAccess setKey(java.lang.String key) { return (RevokeDeviceAccess) super.setKey(key); } @Override public RevokeDeviceAccess setOauthToken(java.lang.String oauthToken) { return (RevokeDeviceAccess) super.setOauthToken(oauthToken); } @Override public RevokeDeviceAccess setPrettyPrint(java.lang.Boolean prettyPrint) { return (RevokeDeviceAccess) super.setPrettyPrint(prettyPrint); } @Override public RevokeDeviceAccess setQuotaUser(java.lang.String quotaUser) { return (RevokeDeviceAccess) super.setQuotaUser(quotaUser); } @Override public RevokeDeviceAccess setUserIp(java.lang.String userIp) { return (RevokeDeviceAccess) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public RevokeDeviceAccess setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public RevokeDeviceAccess setUserId(java.lang.String userId) { this.userId = userId; return this; } @Override public RevokeDeviceAccess set(String parameterName, Object value) { return (RevokeDeviceAccess) super.set(parameterName, value); } } /** * Revokes a previously generated token (activation code) for the user. * * Create a request for the method "users.revokeToken". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link RevokeToken#execute()} method to invoke the remote * operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @return the request */ public RevokeToken revokeToken(java.lang.String enterpriseId, java.lang.String userId) throws java.io.IOException { RevokeToken result = new RevokeToken(enterpriseId, userId); initialize(result); return result; } public class RevokeToken extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/token"; /** * Revokes a previously generated token (activation code) for the user. * * Create a request for the method "users.revokeToken". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link RevokeToken#execute()} method to invoke the remote * operation. <p> {@link * RevokeToken#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @since 1.13 */ protected RevokeToken(java.lang.String enterpriseId, java.lang.String userId) { super(AndroidEnterprise.this, "DELETE", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); } @Override public RevokeToken setAlt(java.lang.String alt) { return (RevokeToken) super.setAlt(alt); } @Override public RevokeToken setFields(java.lang.String fields) { return (RevokeToken) super.setFields(fields); } @Override public RevokeToken setKey(java.lang.String key) { return (RevokeToken) super.setKey(key); } @Override public RevokeToken setOauthToken(java.lang.String oauthToken) { return (RevokeToken) super.setOauthToken(oauthToken); } @Override public RevokeToken setPrettyPrint(java.lang.Boolean prettyPrint) { return (RevokeToken) super.setPrettyPrint(prettyPrint); } @Override public RevokeToken setQuotaUser(java.lang.String quotaUser) { return (RevokeToken) super.setQuotaUser(quotaUser); } @Override public RevokeToken setUserIp(java.lang.String userIp) { return (RevokeToken) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public RevokeToken setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public RevokeToken setUserId(java.lang.String userId) { this.userId = userId; return this; } @Override public RevokeToken set(String parameterName, Object value) { return (RevokeToken) super.set(parameterName, value); } } /** * Modifies the set of products that a user is entitled to access (referred to as whitelisted * products). Only products that are approved or products that were previously approved (products * with revoked approval) can be whitelisted. * * Create a request for the method "users.setAvailableProductSet". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link SetAvailableProductSet#execute()} method to invoke the * remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param content the {@link com.google.api.services.androidenterprise.model.ProductSet} * @return the request */ public SetAvailableProductSet setAvailableProductSet(java.lang.String enterpriseId, java.lang.String userId, com.google.api.services.androidenterprise.model.ProductSet content) throws java.io.IOException { SetAvailableProductSet result = new SetAvailableProductSet(enterpriseId, userId, content); initialize(result); return result; } public class SetAvailableProductSet extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.ProductSet> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}/availableProductSet"; /** * Modifies the set of products that a user is entitled to access (referred to as whitelisted * products). Only products that are approved or products that were previously approved (products * with revoked approval) can be whitelisted. * * Create a request for the method "users.setAvailableProductSet". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link SetAvailableProductSet#execute()} method to invoke the * remote operation. <p> {@link SetAvailableProductSet#initialize(com.google.api.client.googleapis * .services.AbstractGoogleClientRequest)} must be called to initialize this instance immediately * after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param content the {@link com.google.api.services.androidenterprise.model.ProductSet} * @since 1.13 */ protected SetAvailableProductSet(java.lang.String enterpriseId, java.lang.String userId, com.google.api.services.androidenterprise.model.ProductSet content) { super(AndroidEnterprise.this, "PUT", REST_PATH, content, com.google.api.services.androidenterprise.model.ProductSet.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); } @Override public SetAvailableProductSet setAlt(java.lang.String alt) { return (SetAvailableProductSet) super.setAlt(alt); } @Override public SetAvailableProductSet setFields(java.lang.String fields) { return (SetAvailableProductSet) super.setFields(fields); } @Override public SetAvailableProductSet setKey(java.lang.String key) { return (SetAvailableProductSet) super.setKey(key); } @Override public SetAvailableProductSet setOauthToken(java.lang.String oauthToken) { return (SetAvailableProductSet) super.setOauthToken(oauthToken); } @Override public SetAvailableProductSet setPrettyPrint(java.lang.Boolean prettyPrint) { return (SetAvailableProductSet) super.setPrettyPrint(prettyPrint); } @Override public SetAvailableProductSet setQuotaUser(java.lang.String quotaUser) { return (SetAvailableProductSet) super.setQuotaUser(quotaUser); } @Override public SetAvailableProductSet setUserIp(java.lang.String userIp) { return (SetAvailableProductSet) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public SetAvailableProductSet setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public SetAvailableProductSet setUserId(java.lang.String userId) { this.userId = userId; return this; } @Override public SetAvailableProductSet set(String parameterName, Object value) { return (SetAvailableProductSet) super.set(parameterName, value); } } /** * Updates the details of an EMM-managed user. * * Can be used with EMM-managed users only (not Google managed users). Pass the new details in the * Users resource in the request body. Only the displayName field can be changed. Other fields must * either be unset or have the currently active value. * * Create a request for the method "users.update". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param content the {@link com.google.api.services.androidenterprise.model.User} * @return the request */ public Update update(java.lang.String enterpriseId, java.lang.String userId, com.google.api.services.androidenterprise.model.User content) throws java.io.IOException { Update result = new Update(enterpriseId, userId, content); initialize(result); return result; } public class Update extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.User> { private static final String REST_PATH = "enterprises/{enterpriseId}/users/{userId}"; /** * Updates the details of an EMM-managed user. * * Can be used with EMM-managed users only (not Google managed users). Pass the new details in the * Users resource in the request body. Only the displayName field can be changed. Other fields * must either be unset or have the currently active value. * * Create a request for the method "users.update". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Update#execute()} method to invoke the remote * operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param userId The ID of the user. * @param content the {@link com.google.api.services.androidenterprise.model.User} * @since 1.13 */ protected Update(java.lang.String enterpriseId, java.lang.String userId, com.google.api.services.androidenterprise.model.User content) { super(AndroidEnterprise.this, "PUT", REST_PATH, content, com.google.api.services.androidenterprise.model.User.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified."); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUserIp(java.lang.String userIp) { return (Update) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Update setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the user. */ @com.google.api.client.util.Key private java.lang.String userId; /** The ID of the user. */ public java.lang.String getUserId() { return userId; } /** The ID of the user. */ public Update setUserId(java.lang.String userId) { this.userId = userId; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Webapps collection. * * <p>The typical use is:</p> * <pre> * {@code AndroidEnterprise androidenterprise = new AndroidEnterprise(...);} * {@code AndroidEnterprise.Webapps.List request = androidenterprise.webapps().list(parameters ...)} * </pre> * * @return the resource collection */ public Webapps webapps() { return new Webapps(); } /** * The "webapps" collection of methods. */ public class Webapps { /** * Deletes an existing web app. * * Create a request for the method "webapps.delete". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param webAppId The ID of the web app. * @return the request */ public Delete delete(java.lang.String enterpriseId, java.lang.String webAppId) throws java.io.IOException { Delete result = new Delete(enterpriseId, webAppId); initialize(result); return result; } public class Delete extends AndroidEnterpriseRequest<Void> { private static final String REST_PATH = "enterprises/{enterpriseId}/webApps/{webAppId}"; /** * Deletes an existing web app. * * Create a request for the method "webapps.delete". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Delete#execute()} method to invoke the remote * operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param webAppId The ID of the web app. * @since 1.13 */ protected Delete(java.lang.String enterpriseId, java.lang.String webAppId) { super(AndroidEnterprise.this, "DELETE", REST_PATH, null, Void.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.webAppId = com.google.api.client.util.Preconditions.checkNotNull(webAppId, "Required parameter webAppId must be specified."); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUserIp(java.lang.String userIp) { return (Delete) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Delete setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the web app. */ @com.google.api.client.util.Key private java.lang.String webAppId; /** The ID of the web app. */ public java.lang.String getWebAppId() { return webAppId; } /** The ID of the web app. */ public Delete setWebAppId(java.lang.String webAppId) { this.webAppId = webAppId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Gets an existing web app. * * Create a request for the method "webapps.get". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param webAppId The ID of the web app. * @return the request */ public Get get(java.lang.String enterpriseId, java.lang.String webAppId) throws java.io.IOException { Get result = new Get(enterpriseId, webAppId); initialize(result); return result; } public class Get extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.WebApp> { private static final String REST_PATH = "enterprises/{enterpriseId}/webApps/{webAppId}"; /** * Gets an existing web app. * * Create a request for the method "webapps.get". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param webAppId The ID of the web app. * @since 1.13 */ protected Get(java.lang.String enterpriseId, java.lang.String webAppId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.WebApp.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.webAppId = com.google.api.client.util.Preconditions.checkNotNull(webAppId, "Required parameter webAppId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUserIp(java.lang.String userIp) { return (Get) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Get setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the web app. */ @com.google.api.client.util.Key private java.lang.String webAppId; /** The ID of the web app. */ public java.lang.String getWebAppId() { return webAppId; } /** The ID of the web app. */ public Get setWebAppId(java.lang.String webAppId) { this.webAppId = webAppId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Creates a new web app for the enterprise. * * Create a request for the method "webapps.insert". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.WebApp} * @return the request */ public Insert insert(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.WebApp content) throws java.io.IOException { Insert result = new Insert(enterpriseId, content); initialize(result); return result; } public class Insert extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.WebApp> { private static final String REST_PATH = "enterprises/{enterpriseId}/webApps"; /** * Creates a new web app for the enterprise. * * Create a request for the method "webapps.insert". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Insert#execute()} method to invoke the remote * operation. <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param content the {@link com.google.api.services.androidenterprise.model.WebApp} * @since 1.13 */ protected Insert(java.lang.String enterpriseId, com.google.api.services.androidenterprise.model.WebApp content) { super(AndroidEnterprise.this, "POST", REST_PATH, content, com.google.api.services.androidenterprise.model.WebApp.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUserIp(java.lang.String userIp) { return (Insert) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Insert setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } /** * Retrieves the details of all web apps for a given enterprise. * * Create a request for the method "webapps.list". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @return the request */ public List list(java.lang.String enterpriseId) throws java.io.IOException { List result = new List(enterpriseId); initialize(result); return result; } public class List extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.WebAppsListResponse> { private static final String REST_PATH = "enterprises/{enterpriseId}/webApps"; /** * Retrieves the details of all web apps for a given enterprise. * * Create a request for the method "webapps.list". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @since 1.13 */ protected List(java.lang.String enterpriseId) { super(AndroidEnterprise.this, "GET", REST_PATH, null, com.google.api.services.androidenterprise.model.WebAppsListResponse.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUserIp(java.lang.String userIp) { return (List) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public List setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates an existing web app. This method supports patch semantics. * * Create a request for the method "webapps.patch". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param webAppId The ID of the web app. * @param content the {@link com.google.api.services.androidenterprise.model.WebApp} * @return the request */ public Patch patch(java.lang.String enterpriseId, java.lang.String webAppId, com.google.api.services.androidenterprise.model.WebApp content) throws java.io.IOException { Patch result = new Patch(enterpriseId, webAppId, content); initialize(result); return result; } public class Patch extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.WebApp> { private static final String REST_PATH = "enterprises/{enterpriseId}/webApps/{webAppId}"; /** * Updates an existing web app. This method supports patch semantics. * * Create a request for the method "webapps.patch". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Patch#execute()} method to invoke the remote * operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param webAppId The ID of the web app. * @param content the {@link com.google.api.services.androidenterprise.model.WebApp} * @since 1.13 */ protected Patch(java.lang.String enterpriseId, java.lang.String webAppId, com.google.api.services.androidenterprise.model.WebApp content) { super(AndroidEnterprise.this, "PATCH", REST_PATH, content, com.google.api.services.androidenterprise.model.WebApp.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.webAppId = com.google.api.client.util.Preconditions.checkNotNull(webAppId, "Required parameter webAppId must be specified."); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUserIp(java.lang.String userIp) { return (Patch) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Patch setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the web app. */ @com.google.api.client.util.Key private java.lang.String webAppId; /** The ID of the web app. */ public java.lang.String getWebAppId() { return webAppId; } /** The ID of the web app. */ public Patch setWebAppId(java.lang.String webAppId) { this.webAppId = webAppId; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * Updates an existing web app. * * Create a request for the method "webapps.update". * * This request holds the parameters needed by the androidenterprise server. After setting any * optional parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param enterpriseId The ID of the enterprise. * @param webAppId The ID of the web app. * @param content the {@link com.google.api.services.androidenterprise.model.WebApp} * @return the request */ public Update update(java.lang.String enterpriseId, java.lang.String webAppId, com.google.api.services.androidenterprise.model.WebApp content) throws java.io.IOException { Update result = new Update(enterpriseId, webAppId, content); initialize(result); return result; } public class Update extends AndroidEnterpriseRequest<com.google.api.services.androidenterprise.model.WebApp> { private static final String REST_PATH = "enterprises/{enterpriseId}/webApps/{webAppId}"; /** * Updates an existing web app. * * Create a request for the method "webapps.update". * * This request holds the parameters needed by the the androidenterprise server. After setting * any optional parameters, call the {@link Update#execute()} method to invoke the remote * operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param enterpriseId The ID of the enterprise. * @param webAppId The ID of the web app. * @param content the {@link com.google.api.services.androidenterprise.model.WebApp} * @since 1.13 */ protected Update(java.lang.String enterpriseId, java.lang.String webAppId, com.google.api.services.androidenterprise.model.WebApp content) { super(AndroidEnterprise.this, "PUT", REST_PATH, content, com.google.api.services.androidenterprise.model.WebApp.class); this.enterpriseId = com.google.api.client.util.Preconditions.checkNotNull(enterpriseId, "Required parameter enterpriseId must be specified."); this.webAppId = com.google.api.client.util.Preconditions.checkNotNull(webAppId, "Required parameter webAppId must be specified."); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUserIp(java.lang.String userIp) { return (Update) super.setUserIp(userIp); } /** The ID of the enterprise. */ @com.google.api.client.util.Key private java.lang.String enterpriseId; /** The ID of the enterprise. */ public java.lang.String getEnterpriseId() { return enterpriseId; } /** The ID of the enterprise. */ public Update setEnterpriseId(java.lang.String enterpriseId) { this.enterpriseId = enterpriseId; return this; } /** The ID of the web app. */ @com.google.api.client.util.Key private java.lang.String webAppId; /** The ID of the web app. */ public java.lang.String getWebAppId() { return webAppId; } /** The ID of the web app. */ public Update setWebAppId(java.lang.String webAppId) { this.webAppId = webAppId; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * Builder for {@link AndroidEnterprise}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.3.0 */ public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { /** * Returns an instance of a new builder. * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { super( transport, jsonFactory, DEFAULT_ROOT_URL, DEFAULT_SERVICE_PATH, httpRequestInitializer, false); setBatchPath(DEFAULT_BATCH_PATH); } /** Builds a new instance of {@link AndroidEnterprise}. */ @Override public AndroidEnterprise build() { return new AndroidEnterprise(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setBatchPath(String batchPath) { return (Builder) super.setBatchPath(batchPath); } @Override public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } /** * Set the {@link AndroidEnterpriseRequestInitializer}. * * @since 1.12 */ public Builder setAndroidEnterpriseRequestInitializer( AndroidEnterpriseRequestInitializer androidenterpriseRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(androidenterpriseRequestInitializer); } @Override public Builder setGoogleClientRequestInitializer( com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } } }
googleapis/google-api-java-client-services
clients/google-api-services-androidenterprise/v1/1.27.0/com/google/api/services/androidenterprise/AndroidEnterprise.java
Java
apache-2.0
446,458
package com.android.internal.telephony.cat; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ @com.francetelecom.rd.stubs.annotation.ClassDone(0) public class Duration implements android.os.Parcelable { // Classes public static enum TimeUnit { // Enum Constants MINUTE(0) , SECOND(0) , TENTH_SECOND(0) ; // Fields // Constructors private TimeUnit(int arg1){ } // Methods public int value(){ return 0; } } // Fields public int timeInterval; public Duration.TimeUnit timeUnit; public static final android.os.Parcelable.Creator<Duration> CREATOR = null; // Constructors public Duration(int arg1, Duration.TimeUnit arg2){ } private Duration(android.os.Parcel arg1){ } // Methods public void writeToParcel(android.os.Parcel arg1, int arg2){ } public int describeContents(){ return 0; } }
Orange-OpenSource/matos-profiles
matos-android/src/main/java/com/android/internal/telephony/cat/Duration.java
Java
apache-2.0
1,492
package org.apache.lucene.demo.facet; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.lucene.analysis.core.WhitespaceAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.facet.FacetResult; import org.apache.lucene.facet.Facets; import org.apache.lucene.facet.FacetsCollector; import org.apache.lucene.facet.FacetsConfig; import org.apache.lucene.facet.taxonomy.FloatAssociationFacetField; import org.apache.lucene.facet.taxonomy.IntAssociationFacetField; import org.apache.lucene.facet.taxonomy.TaxonomyFacetSumFloatAssociations; import org.apache.lucene.facet.taxonomy.TaxonomyFacetSumIntAssociations; import org.apache.lucene.facet.taxonomy.TaxonomyReader; import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader; import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; /** Shows example usage of category associations. */ public class AssociationsFacetsExample { private final Directory indexDir = new RAMDirectory(); private final Directory taxoDir = new RAMDirectory(); private final FacetsConfig config; /** Empty constructor */ public AssociationsFacetsExample() { config = new FacetsConfig(); config.setMultiValued("tags", true); config.setIndexFieldName("tags", "$tags"); config.setMultiValued("genre", true); config.setIndexFieldName("genre", "$genre"); } /** Build the example index. */ private void index() throws IOException { IndexWriterConfig iwc = new IndexWriterConfig(FacetExamples.EXAMPLES_VER, new WhitespaceAnalyzer(FacetExamples.EXAMPLES_VER)); IndexWriter indexWriter = new IndexWriter(indexDir, iwc); // Writes facet ords to a separate directory from the main index DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir); Document doc = new Document(); // 3 occurrences for tag 'lucene' doc.add(new IntAssociationFacetField(3, "tags", "lucene")); // 87% confidence level of genre 'computing' doc.add(new FloatAssociationFacetField(0.87f, "genre", "computing")); indexWriter.addDocument(config.build(taxoWriter, doc)); doc = new Document(); // 1 occurrence for tag 'lucene' doc.add(new IntAssociationFacetField(1, "tags", "lucene")); // 2 occurrence for tag 'solr' doc.add(new IntAssociationFacetField(2, "tags", "solr")); // 75% confidence level of genre 'computing' doc.add(new FloatAssociationFacetField(0.75f, "genre", "computing")); // 34% confidence level of genre 'software' doc.add(new FloatAssociationFacetField(0.34f, "genre", "software")); indexWriter.addDocument(config.build(taxoWriter, doc)); indexWriter.close(); taxoWriter.close(); } /** User runs a query and aggregates facets by summing their association values. */ private List<FacetResult> sumAssociations() throws IOException { DirectoryReader indexReader = DirectoryReader.open(indexDir); IndexSearcher searcher = new IndexSearcher(indexReader); TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoDir); FacetsCollector fc = new FacetsCollector(); // MatchAllDocsQuery is for "browsing" (counts facets // for all non-deleted docs in the index); normally // you'd use a "normal" query: FacetsCollector.search(searcher, new MatchAllDocsQuery(), 10, fc); Facets tags = new TaxonomyFacetSumIntAssociations("$tags", taxoReader, config, fc); Facets genre = new TaxonomyFacetSumFloatAssociations("$genre", taxoReader, config, fc); // Retrieve results List<FacetResult> results = new ArrayList<FacetResult>(); results.add(tags.getTopChildren(10, "tags")); results.add(genre.getTopChildren(10, "genre")); indexReader.close(); taxoReader.close(); return results; } /** Runs summing association example. */ public List<FacetResult> runSumAssociations() throws IOException { index(); return sumAssociations(); } /** Runs the sum int/float associations examples and prints the results. */ public static void main(String[] args) throws Exception { System.out.println("Sum associations example:"); System.out.println("-------------------------"); List<FacetResult> results = new AssociationsFacetsExample().runSumAssociations(); System.out.println("tags: " + results.get(0)); System.out.println("genre: " + results.get(1)); } }
fogbeam/Heceta_solr
lucene/demo/src/java/org/apache/lucene/demo/facet/AssociationsFacetsExample.java
Java
apache-2.0
5,609
/* * Copyright 2015 Stackify * * 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.stackify.api.common.concurrent; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; /** * BackgroundService JUnit Test * @author Eric Martin */ public class BackgroundServiceTest { /** * testStart */ @Test public void testLifecycle() { TestBackgroundService service = Mockito.spy(new TestBackgroundService()); Assert.assertFalse(service.isRunning()); service.start(); Assert.assertTrue(service.isRunning()); Mockito.verify(service).startUp(); try { Thread.sleep(500); } catch (InterruptedException e) { } Mockito.verify(service).runOneIteration(); Mockito.verify(service).getNextScheduleDelayMilliseconds(); service.stop(); Mockito.verify(service).shutDown(); Assert.assertFalse(service.isRunning()); } /** * TestBackgroundService */ private static class TestBackgroundService extends BackgroundService { /** * @see com.stackify.api.common.concurrent.BackgroundService#startUp() */ @Override protected void startUp() { } /** * @see com.stackify.api.common.concurrent.BackgroundService#runOneIteration() */ @Override protected void runOneIteration() { } /** * @see com.stackify.api.common.concurrent.BackgroundService#getNextScheduleDelayMilliseconds() */ @Override protected long getNextScheduleDelayMilliseconds() { return 1000; } /** * @see com.stackify.api.common.concurrent.BackgroundService#shutDown() */ @Override protected void shutDown() { } } }
stackify/stackify-api-java
src/test/java/com/stackify/api/common/concurrent/BackgroundServiceTest.java
Java
apache-2.0
2,114
package com.YC2010.jason.myclass.Reminder.helpers; /* * Copyright (C) 2015 Paul Burke * * 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 android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; /** * Interface to listen for a move or dismissal event from a {@link ItemTouchHelper.Callback}. * * @author Paul Burke (ipaulpro) */ public interface ItemTouchHelperAdapter { /** * Called when an item has been dismissed by a swipe.<br/> * <br/> * Implementations should call {@link RecyclerView.Adapter#notifyItemRemoved(int)} after * adjusting the underlying data to reflect this removal. * * @param position The position of the item dismissed. * @see RecyclerView#getAdapterPositionFor(RecyclerView.ViewHolder) * @see RecyclerView.ViewHolder#getAdapterPosition() */ void onItemDismiss(int position); }
qpzm0192/MyClass
app/src/main/java/com/YC2010/jason/myclass/Reminder/helpers/ItemTouchHelperAdapter.java
Java
apache-2.0
1,420
package net.jarlehansen.proto2javame.invalid.proto; /** * * @author [email protected] Jarle Hansen * */ public enum InvalidProtoFilesConstants { ; static final String VALID_OUTPUT_FOLDER = "--java_out=src/test/generated"; private static final String PROTO_FOLDER = "src/test/resources/invalid_proto/"; static final String INVALID_PACKAGE = PROTO_FOLDER + "invalid_package.proto"; static final int INVALID_PACKAGE_LINE_NUM = 3; static final String INVALID_MESSAGE_START = PROTO_FOLDER + "invalid_message_start.proto"; static final int INVALID_MESSAGE_START_LINE_NUM = 6; static final String INVALID_FIELD = PROTO_FOLDER + "invalid_field.proto"; static final int INVALID_FIELD_LINE_NUM = 7; static final String INVALID_MESSAGE_END = PROTO_FOLDER + "invalid_message_end.proto"; static final int INVALID_MESSAGE_END_LINE_NUM = 8; static final String INVALID_FIELD_ID = PROTO_FOLDER + "invalid_field_id.proto"; static final String INVALID_ENUM_ID = PROTO_FOLDER + "invalid_enum_id.proto"; }
nemecec/protobuf-javame
proto2javame/src/test/java/net/jarlehansen/proto2javame/invalid/proto/InvalidProtoFilesConstants.java
Java
apache-2.0
1,052
/* * Copyright 2020 Global Biodiversity Information Facility (GBIF) * * 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.gbif.api.model.registry.eml; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.StringJoiner; public class SamplingDescription implements Serializable { private static final long serialVersionUID = -9075523119279155795L; private String studyExtent; private String sampling; private String qualityControl; private List<String> methodSteps = new ArrayList<>(); public SamplingDescription() { } public SamplingDescription(String studyExtent, String sampling, String qualityControl, List<String> methodSteps) { this.studyExtent = studyExtent; this.sampling = sampling; this.qualityControl = qualityControl; this.methodSteps = methodSteps; } public List<String> getMethodSteps() { return methodSteps; } public void setMethodSteps(List<String> methodSteps) { this.methodSteps = methodSteps; } public void addMethodStep(String methodStep) { this.methodSteps.add(methodStep); } public String getQualityControl() { return qualityControl; } public void setQualityControl(String qualityControl) { this.qualityControl = qualityControl; } public String getSampling() { return sampling; } public void setSampling(String sampling) { this.sampling = sampling; } public String getStudyExtent() { return studyExtent; } public void setStudyExtent(String studyExtent) { this.studyExtent = studyExtent; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SamplingDescription that = (SamplingDescription) o; return Objects.equals(studyExtent, that.studyExtent) && Objects.equals(sampling, that.sampling) && Objects.equals(qualityControl, that.qualityControl) && Objects.equals(methodSteps, that.methodSteps); } @Override public int hashCode() { return Objects.hash(studyExtent, sampling, qualityControl, methodSteps); } @Override public String toString() { return new StringJoiner(", ", SamplingDescription.class.getSimpleName() + "[", "]") .add("studyExtent='" + studyExtent + "'") .add("sampling='" + sampling + "'") .add("qualityControl='" + qualityControl + "'") .add("methodSteps=" + methodSteps) .toString(); } }
gbif/gbif-api
src/main/java/org/gbif/api/model/registry/eml/SamplingDescription.java
Java
apache-2.0
3,036
package com.twu.biblioteca; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class MyProfileOptionTest { Customer customer = mock(Customer.class); Library library = mock(Library.class); MyProfileOption subject = new MyProfileOption(library); final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); @Before public void setUpStreams() { System.setOut(new PrintStream(outContent)); } @After public void cleanUpStreams() { System.setOut(null); } @Test public void showsProfile(){ when(library.isLoggedIn()).thenReturn(true); when(library.getCurrentUser()).thenReturn(customer); when(customer.showDetails()).thenReturn("test"); subject.showProfile(); assertThat(outContent.toString(), containsString("test")); } @Test public void doesNotShowProfile(){ when(library.isLoggedIn()).thenReturn(false); subject.showProfile(); assertThat(outContent.toString(), containsString("You must login to see your profile.")); } }
anikarni/twu-biblioteca-anike
test/com/twu/biblioteca/MyProfileOptionTest.java
Java
apache-2.0
1,365
package com.josearmas; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { // write your code here BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n=0; int resultado = 0; for (int i = 0; i <10; i++) { System.out.print("Escribe un número: "); int numero = Integer.parseInt(br.readLine()); resultado = resultado+numero; } System.out.println("La suma de los 10 números es: "+resultado); } }
ALJ00/ud2-elementos-programa
08_suma_10/ejercicio_8 - Suma_10/src/com/josearmas/Main.java
Java
apache-2.0
668
@org.springframework.lang.NonNullApi package com._4dconcept.springframework.data.marklogic.core.convert;
stoussaint/spring-data-marklogic
src/main/java/com/_4dconcept/springframework/data/marklogic/core/convert/package-info.java
Java
apache-2.0
104
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.iacuc.actions.notifyiacuc; import org.kuali.kra.iacuc.IacucProtocol; import org.kuali.kra.iacuc.notification.IacucProtocolNotificationRenderer; import java.util.Map; /** * Renders additional fields for the Notify IRB notification. */ public class NotifyIacucNotificationRenderer extends IacucProtocolNotificationRenderer { private String actionComments; /** * Constructs a Notify IRB notification renderer. * @param protocol * @param actionComments */ public NotifyIacucNotificationRenderer(IacucProtocol protocol, String actionComments) { super(protocol); this.actionComments = actionComments; } public String getActionComments() { return actionComments; } public void setActionComments(String actionComments) { this.actionComments = actionComments; } @Override public Map<String, String> getDefaultReplacementParameters() { Map<String, String> params = super.getDefaultReplacementParameters(); params.put("{ACTION_COMMENTS}", getSafeMessage("{ACTION_COMMENTS}", actionComments)); return params; } }
blackcathacker/kc.preclean
coeus-code/src/main/java/org/kuali/kra/iacuc/actions/notifyiacuc/NotifyIacucNotificationRenderer.java
Java
apache-2.0
1,795
/* * Copyright 2015-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.ide.intellij.model; import com.facebook.buck.ide.intellij.IjDependencyListBuilder; import com.facebook.buck.ide.intellij.Util; import com.facebook.buck.ide.intellij.model.folders.IjFolder; import com.facebook.buck.io.file.MorePaths; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.util.immutables.BuckStyleImmutable; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.nio.file.Path; import java.util.Map; import java.util.Optional; import org.immutables.value.Value; /** Represents a single IntelliJ module. */ @Value.Immutable @BuckStyleImmutable abstract class AbstractIjModule implements IjProjectElement { @Override @Value.Derived public String getName() { return Util.intelliJModuleNameFromPath(MorePaths.pathWithUnixSeparators(getModuleBasePath())); } @Override public abstract ImmutableSet<BuildTarget> getTargets(); /** * @return path to the top-most directory the module is responsible for. This is also where the * corresponding .iml file is located. */ public abstract Path getModuleBasePath(); /** @return paths to various directories the module is responsible for. */ public abstract ImmutableList<IjFolder> getFolders(); /** * @return map of {@link BuildTarget}s the module depends on and information on whether it's a * test-only dependency or not. */ public abstract ImmutableMap<BuildTarget, DependencyType> getDependencies(); public abstract Optional<IjModuleAndroidFacet> getAndroidFacet(); /** @return a set of classpaths that the module requires to index correctly. */ public abstract ImmutableSet<Path> getExtraClassPathDependencies(); /** @return a set of module paths that the module requires to index correctly. */ public abstract ImmutableSet<Path> getExtraModuleDependencies(); /** @return Folders which contain the generated source code. */ public abstract ImmutableList<IjFolder> getGeneratedSourceCodeFolders(); public abstract Optional<String> getLanguageLevel(); public abstract IjModuleType getModuleType(); public abstract Optional<Path> getMetaInfDirectory(); public abstract Optional<Path> getCompilerOutputPath(); /** @return path where the XML describing the module to IntelliJ will be written to. */ @Value.Derived public Path getModuleImlFilePath() { return getModuleBasePath().resolve(getName() + ".iml"); } @Value.Check protected void allRulesAreChildrenOfBasePath() { Path moduleBasePath = getModuleBasePath(); for (BuildTarget target : getTargets()) { Path targetBasePath = target.getBasePath(); Preconditions.checkArgument( targetBasePath.startsWith(moduleBasePath), "A module cannot be composed of targets which are outside of its base path."); } } @Value.Check protected void checkDependencyConsistency() { for (Map.Entry<BuildTarget, DependencyType> entry : getDependencies().entrySet()) { BuildTarget depBuildTarget = entry.getKey(); DependencyType dependencyType = entry.getValue(); boolean isSelfDependency = getTargets().contains(depBuildTarget); if (dependencyType.equals(DependencyType.COMPILED_SHADOW)) { Preconditions.checkArgument( isSelfDependency, "Target %s is a COMPILED_SHADOW dependency of module %s and therefore should be part" + "of its target set.", depBuildTarget, getName()); } else { Preconditions.checkArgument( !isSelfDependency, "Target %s is a regular dependency of module %s and therefore should not be part of " + "its target set.", depBuildTarget, getName()); } } } @Override public void addAsDependency( DependencyType dependencyType, IjDependencyListBuilder dependencyListBuilder) { Preconditions.checkArgument(!dependencyType.equals(DependencyType.COMPILED_SHADOW)); IjDependencyListBuilder.Scope scope = IjDependencyListBuilder.Scope.COMPILE; if (dependencyType.equals(DependencyType.TEST)) { scope = IjDependencyListBuilder.Scope.TEST; } else if (dependencyType.equals(DependencyType.RUNTIME)) { scope = IjDependencyListBuilder.Scope.RUNTIME; } dependencyListBuilder.addModule(getName(), scope, false /* exported */); } }
shybovycha/buck
src/com/facebook/buck/ide/intellij/model/AbstractIjModule.java
Java
apache-2.0
5,106
package io.innofang.jsoupdemo; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.v7.widget.RecyclerView; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; /** * Author: Inno Fang * Time: 2017/6/4 10:51 * Description: */ public class BaseSimpleViewHolder extends RecyclerView.ViewHolder { private SparseArray<View> mViews; private View mItemView; public BaseSimpleViewHolder(View itemView) { super(itemView); mItemView = itemView; mViews = new SparseArray<>(); } @SuppressWarnings("unchecked") public static <T extends BaseSimpleViewHolder> T getViewHolder(Context context, ViewGroup parent, @LayoutRes int layoutId) { return (T) new BaseSimpleViewHolder(LayoutInflater.from(context).inflate(layoutId, parent, false)); } @SuppressWarnings("unchecked") public <T extends View> T getView(@IdRes int id) { View child = mViews.get(id); if (null == child) { child = itemView.findViewById(id); mViews.put(id, child); } return (T) child; } public View getItemView() { return mItemView; } public void setText(@IdRes int id, String text) { if (getView(id) instanceof TextView) { ((TextView) getView(id)).setText(text); } } public void setTextColor(@IdRes int id, @ColorInt int color) { if (getView(id) instanceof TextView) { ((TextView) getView(id)).setTextColor(color); } } public void setImageResource(@IdRes int id, @DrawableRes int resId) { if (getView(id) instanceof ImageView) { ((ImageView) getView(id)).setImageResource(resId); } } public void setImageDrawable(@IdRes int id, Drawable drawable) { if (getView(id) instanceof ImageView) { ((ImageView) getView(id)).setImageDrawable(drawable); } } public void setBackgroundColor(@IdRes int id, @ColorInt int color) { getView(id).setBackgroundColor(color); } public void setVisible(@IdRes int id, boolean visible) { getView(id).setVisibility(visible ? View.VISIBLE : View.GONE); } public void setOnClickListener(int viewId, View.OnClickListener listener) { getView(viewId).setOnClickListener(listener); } public void setOnTouchListener(int viewId, View.OnTouchListener listener) { getView(viewId).setOnTouchListener(listener); } public void setOnLongClickListener(int viewId, View.OnLongClickListener listener) { getView(viewId).setOnLongClickListener(listener); } }
InnoFang/Android-Code-Demos
JSoupDemo/app/src/main/java/io/innofang/jsoupdemo/BaseSimpleViewHolder.java
Java
apache-2.0
2,967
package com.gfirem.elrosacruz.utils; import android.app.Activity; import android.app.ProgressDialog; import android.graphics.Color; import android.graphics.Point; import android.location.Location; import android.os.AsyncTask; import android.os.Handler; import android.os.SystemClock; import android.util.Log; import android.view.animation.LinearInterpolator; import com.gfirem.elrosacruz.MainActivity; import com.gfirem.elrosacruz.entity.MapTypes; import com.gfirem.elrosacruz.entity.Placemark; import com.gfirem.elrosacruz.map.LatLongLoadedListner; import com.gfirem.elrosacruz.map.MapDirection; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.CancelableCallback; import com.google.android.gms.maps.Projection; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polygon; import com.google.android.gms.maps.model.PolygonOptions; import com.google.android.gms.maps.model.PolylineOptions; import org.w3c.dom.Document; import java.util.ArrayList; public class MapHelper { private GoogleMap googleMap; private final static String LOG_TAG = "MapHelper"; private boolean moveCameraToLocation = true; private byte zoomLevel = 12; private float drawRoutePath_pathWidth = 3.0f; private int drawRoutePath_pathColor = Color.RED; private int Polygon_strokeColor = Color.RED; private int Polygon_fillColor = Color.BLUE; private CancelableCallback mCancelableCallback; private int currentMarkerPosition; public MapHelper(GoogleMap googleMap) { this.googleMap = googleMap; } /** * Add a marker to Map * * @param latitude : Latitude * @param longitude : Longitude * @param title : The message to be shown */ public Marker addMarker(double latitude, double longitude, String title, String snippet, boolean playAnimation) { MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(latitude, longitude)).title(title) .snippet(snippet); if (moveCameraToLocation) { CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)) .zoom(zoomLevel).build(); googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } if (playAnimation) { CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)) .bearing(45).tilt(90).zoom(googleMap.getCameraPosition().zoom).build(); googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } return googleMap.addMarker(markerOptions); } /** * Create a marker * * @param latitude : Latitude * @param longitude : Longitude * @param title : The message to be shown * @param snippet : The snippet to be shown * @return Marker : Returns a newly created Marker */ public Marker createMarker(double latitude, double longitude, String title, String snippet) { MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(latitude, longitude)).title(title) .snippet(snippet); return googleMap.addMarker(markerOptions); } /** * @param latitude : Latitude * @param longitude : Longitude */ public void zoomToLocation(double latitude, double longitude) { CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)) .zoom(zoomLevel).build(); googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } /** * Add a marker to the map * * @param latitude : Latitude * @param longitude : Longitude * @param title : The message to be shown * @param snippet : The snippet to be shown * @param moveCameraToLocation : Move the camera to the location * @param playAnimation : Play animated move to location * @return Marker : Returns a newly created Marker */ public Marker addMarker(double latitude, double longitude, String title, String snippet, boolean moveCameraToLocation, boolean playAnimation) { this.moveCameraToLocation = moveCameraToLocation; return addMarker(latitude, longitude, title, snippet, playAnimation); } /** * Add a marker to the map * * @param latitude : Latitude * @param longitude : Longitude * @param title : The message to be shown * @param snippet : The snippet to be shown * @param moveCameraToLocation : Move the camera to the location * @param playAnimation : Play animated move to location * @param zoomLevel : The level of zoom need to be applied * @return Marker : Returns a newly created Marker */ public Marker addMarker(double latitude, double longitude, String title, String snippet, boolean moveCameraToLocation, boolean playAnimation, byte zoomLevel) { this.zoomLevel = zoomLevel; this.moveCameraToLocation = moveCameraToLocation; return addMarker(latitude, latitude, title, snippet, playAnimation); } /** * Add a marker to the map * * @param latitude : Latitude * @param longitude : Longitude * @param title : The message to be shown * @param snippet : The snippet to be shown * @param moveCameraToLocation : Move the camera to the location * @param playAnimation : Play animated move to location * @param zoomLevel : The level of zoom need to be applied * @param MarkerColors : Set the colors from MarkerColors Class * @return Marker : Returns a newly created Marker */ public Marker addMarker(double latitude, double longitude, String title, String snippet, boolean moveCameraToLocation, boolean playAnimation, byte zoomLevel, byte MarkerColors) { this.zoomLevel = zoomLevel; this.moveCameraToLocation = moveCameraToLocation; return addMarker(latitude, latitude, title, snippet, playAnimation); } /** * Set type of maps from NORMAL, HYBRID, SATELLITE or TERRAIN * * @param MapType : Check the MapType class */ public void setMapType(byte MapType) { switch (MapType) { case MapTypes.NORMAL: googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); break; case MapTypes.HYBRID: googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); break; case MapTypes.SATELLITE: googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); break; case MapTypes.TERRAIN: googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); break; default: googleMap.setMapType(GoogleMap.MAP_TYPE_NONE); break; } } /** * Set if you want your current location to be highlighted * * @param enabled : Enable Current Location */ public void setCurrentLocation(boolean enabled) { googleMap.setMyLocationEnabled(enabled); } /** * To enable the zoom controls (+/- buttons) * * @param enabled : Enable Zoom Controls */ public void setZoomControlsEnabled(boolean enabled) { googleMap.getUiSettings().setZoomControlsEnabled(enabled); } /** * To enable Zoom Gestures * * @param enabled : Enable Zoom Gestures */ public void setZoomGesturesEnabled(boolean enabled) { googleMap.getUiSettings().setZoomGesturesEnabled(enabled); } /** * To enable Compass * * @param enabled : Enable Compass */ public void setCompassEnabled(boolean enabled) { googleMap.getUiSettings().setCompassEnabled(enabled); } /** * To enable Location Button * * @param enabled : Enable Location Button */ public void setMyLocationButtonEnabled(boolean enabled) { googleMap.getUiSettings().setMyLocationButtonEnabled(enabled); } /** * To enable Rotate Gestures * * @param enabled : Enable Rotate Gestures */ public void setRotateGesturesEnabled(boolean enabled) { googleMap.getUiSettings().setRotateGesturesEnabled(enabled); } private void setCameraToLatLong(LatLng... args) { LatLngBounds.Builder b = new LatLngBounds.Builder(); for (LatLng m : args) { b.include(m); } LatLngBounds bounds = b.build(); CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 25, 25, 5); googleMap.animateCamera(cu); } /** * To draw a route path from a start point to end point * * @param activity : To show progress dialog when retrieving the route * @param LatLng1 : The LatLng of start position * @param LatLng2 : The LatLng of end position * @param moveCameraToPosition : Move the camera accordingly to the path */ public void drawRoutePath(final Activity activity, final LatLng LatLng1, final LatLng LatLng2, final boolean moveCameraToPosition) { class DrawRoutePath extends AsyncTask<String, Void, Void> { private PolylineOptions mPolylineOptions; private ProgressDialog mProgressDialog; private MapDirection mMapDirection; private Document mDocument; @Override protected void onPreExecute() { if (activity != null) mProgressDialog = ProgressDialog.show(activity, "Fetching Direction", "Please Wait..."); super.onPreExecute(); } @Override protected Void doInBackground(String... arg0) { try { mMapDirection = new MapDirection(); mDocument = mMapDirection.getXMLFromLatLong(LatLng1, LatLng2, MapDirection.DRIVING); } catch (Exception e) { Log.e(LOG_TAG, "DrawRoutePath " + e.getMessage()); } return null; } @Override protected void onPostExecute(Void result) { Log.d(LOG_TAG, "mDocument " + mDocument); ArrayList<LatLng> mLatLongList = mMapDirection.getLatLongDirectionsList(mDocument); mPolylineOptions = new PolylineOptions().width(drawRoutePath_pathWidth).color(drawRoutePath_pathColor); for (int i = 0; i < mLatLongList.size(); i++) { mPolylineOptions.add(mLatLongList.get(i)); } if (moveCameraToPosition) setCameraToLatLong(LatLng1, LatLng2); if (activity != null) mProgressDialog.cancel(); googleMap.addPolyline(mPolylineOptions); super.onPostExecute(result); } } new DrawRoutePath().execute(""); } /** * Draw a circular path around a LatLng * * @param LatLng : The start LatLng * @param radius : The radius in meters to draw the circle around * @param moveCameraToPosition : Move the camera accordingly to the path * @return Circle: The Circle created is returned */ public Circle drawCircularRegion(LatLng LatLng, int radius, boolean moveCameraToPosition) { CircleOptions circleOptions = new CircleOptions().center(LatLng).radius(radius); Circle circle = googleMap.addCircle(circleOptions); if (moveCameraToPosition) setCameraToLatLong(LatLng, getNewLatLongFromDistance(LatLng, radius)); return circle; } /** * Draw a polygon to the LatLngs Provided * * @param moveCameraToPosition : Move the camera accordingly to the path * @param LatLngs : The array of LatLngs to draw the polygon * @return Polygon: The Polygon created is returned */ public Polygon drawPolygonRegion(boolean moveCameraToPosition, LatLng... LatLngs) { PolygonOptions mPolygonOptions = new PolygonOptions(); for (LatLng latlng : LatLngs) mPolygonOptions.add(latlng); mPolygonOptions.strokeColor(Polygon_strokeColor); mPolygonOptions.fillColor(Polygon_fillColor); if (moveCameraToPosition) zoomToFitLatLongs(LatLngs); return googleMap.addPolygon(mPolygonOptions); } /** * To zoom the camera to the best possible position so the camera can view * all the markers * * @param markers : The array of markers to zoom to */ public void zoomToFitMarkers(Marker... markers) { LatLngBounds.Builder b = new LatLngBounds.Builder(); for (Marker m : markers) { b.include(m.getPosition()); } LatLngBounds bounds = b.build(); CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 25, 25, 5); googleMap.animateCamera(cu); } /** * To zoom the camera to the best possible position so the camera can view * all the LatLng's * * @param latlng : The array of LatLng's to zoom to */ public void zoomToFitLatLongs(LatLng... latlng) { LatLngBounds.Builder bounds = new LatLngBounds.Builder(); for (LatLng l : latlng) { bounds.include(l); } int padding = (int) Math.min((DisplayUtil.getRatio(MainActivity.getContext()) * 160), (DisplayUtil.getDisplayWidth(MainActivity.getContext()) - 40) / 2); //CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds.build(), 25, 25, 5); CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds.build(), padding); googleMap.animateCamera(cu); } /** * To zoom the camera to the best possible position so the camera can view * all the LatLng's * */ public void zoomToFitLatLongs(LatLng center, LatLng[] nearest_places) { LatLngBounds.Builder b = new LatLngBounds.Builder(); b.include(center); for (LatLng l : nearest_places) { b.include(l); } LatLngBounds bounds = b.build(); // CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 25, 25, 5); CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 250); googleMap.animateCamera(cu); } public void zoomToFitLatLongs(ArrayList<LatLng> latlng) { LatLngBounds.Builder b = new LatLngBounds.Builder(); for (LatLng l : latlng) { b.include(l); } LatLngBounds bounds = b.build(); // CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 25, 25, 5); CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 250); googleMap.animateCamera(cu); } public ArrayList<LatLng> extractLocations(ArrayList<Placemark> places) { ArrayList<LatLng> result = new ArrayList<LatLng>(); for (Placemark item : places) { result.add(item.getCoordinates()); } return result; } /** * To get distance between tow LatLongs in kilometers * * @param latLng1 : The start point LatLng * @param latLng2 : The end point LatLng * @return double : distance in meters */ public static double getDistanceBetweenLatLongs_Kilometers(LatLng latLng1, LatLng latLng2) { double theta = latLng1.longitude - latLng2.longitude; double dist = Math.sin((latLng1.latitude * Math.PI / 180.0)) * Math.sin((latLng2.latitude * Math.PI / 180.0)) + Math.cos((latLng1.latitude * Math.PI / 180.0)) * Math.cos((latLng2.latitude * Math.PI / 180.0)) * Math.cos((theta * Math.PI / 180.0)); dist = Math.acos(dist); dist = (dist * 180.0 / Math.PI); dist = dist * 60 * 1.1515; dist = dist * 1.609344; // in Kilometers return (dist); } /** * To get a new LatLng from an existing LatLng and distance * * @param latLng : The start point * @param distance : The distance in meters * @return LatLng : The new LatLng deduced */ public LatLng getNewLatLongFromDistance(LatLng latLng, float distance) { distance = distance / 1000;// in meters double lat1 = Math.toRadians(latLng.latitude); double lon1 = Math.toRadians(latLng.longitude); double lat2 = Math.asin(Math.sin(lat1) * Math.cos(distance / 6378.1) + Math.cos(lat1) * Math.sin(distance / 6378.1) * Math.cos(1.57)); double lon2 = lon1 + Math.atan2(Math.sin(1.57) * Math.sin(distance / 6378.1) * Math.cos(lat1), Math.cos(distance / 6378.1) - Math.sin(lat1) * Math.sin(lat2)); lat2 = Math.toDegrees(lat2); lon2 = Math.toDegrees(lon2); return new LatLng(lat2, lon2); } /** * Get the list of LatLng's from start point to end point to draw a route or * path * * @param startPoint : The LatLng of start point * @param endpoint : The LatLng of end point * @param mLatLongLoadedListner : Listner once the LatLng is loaded */ public void getLatLongList(final LatLng startPoint, final LatLng endpoint, final LatLongLoadedListner mLatLongLoadedListner) { class LatLongRetriever extends AsyncTask<String, Void, Void> { private MapDirection mMapDirection; private Document mDocument; @Override protected Void doInBackground(String... arg0) { try { mMapDirection = new MapDirection(); mDocument = mMapDirection.getXMLFromLatLong(startPoint, endpoint, MapDirection.DRIVING); } catch (Exception e) { Log.e(LOG_TAG, "DrawRoutePath " + e.getMessage()); } return null; } @Override protected void onPostExecute(Void result) { mLatLongLoadedListner.LatLongs(mMapDirection.getLatLongDirectionsList(mDocument)); super.onPostExecute(result); } } new LatLongRetriever().execute(""); } /** * To play an animation of the route path drawn throug LatLng's * * @param markers : The markers to which lat long is provided * @param secondsDelay: The time delay for animation from one point to anothert in * milliseconds * @param drawMarkers : If the markers are to be drawn or not */ public void PlayRouteAnimation(final Marker[] markers, final int secondsDelay, boolean drawMarkers) { if (markers == null) throw new RuntimeException("latlngs values are null"); else Log.d(LOG_TAG, "latlngs " + markers.length); currentMarkerPosition = 0; PolylineOptions mPolylineOptions = new PolylineOptions().width(drawRoutePath_pathWidth) .color(drawRoutePath_pathColor); for (int i = 0; i < markers.length; i++) { mPolylineOptions.add(markers[i].getPosition()); if (drawMarkers) markers[i] = addMarker(markers[i].getPosition().latitude, markers[i].getPosition().longitude, markers[i].getTitle(), markers[i].getSnippet(), false); } googleMap.addPolyline(mPolylineOptions); CameraPosition cameraPosition = new CameraPosition.Builder().target(markers[0].getPosition()).bearing(45) .tilt(90).zoom(15).build(); mCancelableCallback = new CancelableCallback() { @Override public void onCancel() { } @Override public void onFinish() { Log.d(LOG_TAG, "onFinish currentPt " + currentMarkerPosition); if (++currentMarkerPosition < markers.length) { CameraPosition cameraPosition = new CameraPosition.Builder() .target(markers[currentMarkerPosition].getPosition()).tilt(90) .bearing(getNewBearing(markers[(currentMarkerPosition - 1)].getPosition(), markers[(currentMarkerPosition)].getPosition())) .zoom(15).build(); markers[currentMarkerPosition].showInfoWindow(); markers[currentMarkerPosition - 1].hideInfoWindow(); googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), secondsDelay, mCancelableCallback); animateMarker(markers[currentMarkerPosition - 1], markers[currentMarkerPosition].getPosition(), true); // markers[currentMarkerPosition-1].setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); } } }; googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), mCancelableCallback); } private float getNewBearing(LatLng l1, LatLng l2) { Location loc1 = new Location(""); loc1.setLatitude(l1.latitude); loc1.setLongitude(l1.longitude); Location loc2 = new Location(""); loc2.setLatitude(l2.latitude); loc2.setLongitude(l2.longitude); return loc1.bearingTo(loc2); } private void animateMarker(final Marker marker, final LatLng toPosition, final boolean hideMarker) { final Handler handler = new Handler(); final long start = SystemClock.uptimeMillis(); Projection proj = googleMap.getProjection(); Point startPoint = proj.toScreenLocation(marker.getPosition()); final LatLng startLatLng = proj.fromScreenLocation(startPoint); final long duration = 500; final LinearInterpolator interpolator = new LinearInterpolator(); handler.post(new Runnable() { @Override public void run() { long elapsed = SystemClock.uptimeMillis() - start; float t = interpolator.getInterpolation((float) elapsed / duration); double lng = t * toPosition.longitude + (1 - t) * startLatLng.longitude; double lat = t * toPosition.latitude + (1 - t) * startLatLng.latitude; marker.setPosition(new LatLng(lat, lng)); if (t < 1.0) { handler.postDelayed(this, 16); } else { if (hideMarker) { marker.setVisible(false); } else { marker.setVisible(true); } } } }); } }
gfirem/ElRosaCruz
branches/development/android/sources/ElRosaCruz/app/src/main/java/com/gfirem/elrosacruz/utils/MapHelper.java
Java
apache-2.0
23,598
// // Copyright 2011 Kuali Foundation, Inc. Licensed under the // Educational Community 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.opensource.org/licenses/ecl2.php // // 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.kuali.continuity.admin.service; import org.kuali.continuity.domain.UIImageEnum; import org.kuali.continuity.domain.UIImageTypeEnum; public interface CustomImageUploadService { void uploadImage(int systemDomainId, UIImageEnum uiImageKey, UIImageTypeEnum uiImageType, byte[] image); void deleteImage(int systemDomainId, UIImageEnum uiImageKey); }
Ariah-Group/Continuity
src/main/java/org/kuali/continuity/admin/service/CustomImageUploadService.java
Java
apache-2.0
995
package org.gradle.test.performance.mediummonolithicjavaproject.p447; public class Production8942 { private String property0; public String getProperty0() { return property0; } public void setProperty0(String value) { property0 = value; } private String property1; public String getProperty1() { return property1; } public void setProperty1(String value) { property1 = value; } private String property2; public String getProperty2() { return property2; } public void setProperty2(String value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
oehme/analysing-gradle-performance
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p447/Production8942.java
Java
apache-2.0
1,891
/* * Copyright 2009-2013 by The Regents of the University of California * 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 from * * 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 edu.uci.ics.asterix.common.config; import java.util.Map; public class AsterixTransactionProperties extends AbstractAsterixProperties { private static final String TXN_LOG_BUFFER_NUMPAGES_KEY = "txn.log.buffer.numpages"; private static int TXN_LOG_BUFFER_NUMPAGES_DEFAULT = 8; private static final String TXN_LOG_BUFFER_PAGESIZE_KEY = "txn.log.buffer.pagesize"; private static final int TXN_LOG_BUFFER_PAGESIZE_DEFAULT = (128 << 10); // 128KB private static final String TXN_LOG_PARTITIONSIZE_KEY = "txn.log.partitionsize"; private static final long TXN_LOG_PARTITIONSIZE_DEFAULT = ((long) 2 << 30); // 2GB private static final String TXN_LOG_CHECKPOINT_LSNTHRESHOLD_KEY = "txn.log.checkpoint.lsnthreshold"; private static final int TXN_LOG_CHECKPOINT_LSNTHRESHOLD_DEFAULT = (64 << 20); // 64M private static final String TXN_LOG_CHECKPOINT_POLLFREQUENCY_KEY = "txn.log.checkpoint.pollfrequency"; private static int TXN_LOG_CHECKPOINT_POLLFREQUENCY_DEFAULT = 120; // 120s private static final String TXN_LOG_CHECKPOINT_HISTORY_KEY = "txn.log.checkpoint.history"; private static int TXN_LOG_CHECKPOINT_HISTORY_DEFAULT = 0; private static final String TXN_LOCK_ESCALATIONTHRESHOLD_KEY = "txn.lock.escalationthreshold"; private static int TXN_LOCK_ESCALATIONTHRESHOLD_DEFAULT = 1000; private static final String TXN_LOCK_SHRINKTIMER_KEY = "txn.lock.shrinktimer"; private static int TXN_LOCK_SHRINKTIMER_DEFAULT = 5000; // 5s private static final String TXN_LOCK_TIMEOUT_WAITTHRESHOLD_KEY = "txn.lock.timeout.waitthreshold"; private static final int TXN_LOCK_TIMEOUT_WAITTHRESHOLD_DEFAULT = 60000; // 60s private static final String TXN_LOCK_TIMEOUT_SWEEPTHRESHOLD_KEY = "txn.lock.timeout.sweepthreshold"; private static final int TXN_LOCK_TIMEOUT_SWEEPTHRESHOLD_DEFAULT = 10000; // 10s public AsterixTransactionProperties(AsterixPropertiesAccessor accessor) { super(accessor); } public String getLogDirectory(String nodeId) { return accessor.getTransactionLogDirs().get(nodeId); } public Map<String, String> getLogDirectories() { return accessor.getTransactionLogDirs(); } public int getLogBufferNumPages() { return accessor.getProperty(TXN_LOG_BUFFER_NUMPAGES_KEY, TXN_LOG_BUFFER_NUMPAGES_DEFAULT, PropertyInterpreters.getIntegerPropertyInterpreter()); } public int getLogBufferPageSize() { return accessor.getProperty(TXN_LOG_BUFFER_PAGESIZE_KEY, TXN_LOG_BUFFER_PAGESIZE_DEFAULT, PropertyInterpreters.getIntegerPropertyInterpreter()); } public long getLogPartitionSize() { return accessor.getProperty(TXN_LOG_PARTITIONSIZE_KEY, TXN_LOG_PARTITIONSIZE_DEFAULT, PropertyInterpreters.getLongPropertyInterpreter()); } public int getCheckpointLSNThreshold() { return accessor.getProperty(TXN_LOG_CHECKPOINT_LSNTHRESHOLD_KEY, TXN_LOG_CHECKPOINT_LSNTHRESHOLD_DEFAULT, PropertyInterpreters.getIntegerPropertyInterpreter()); } public int getCheckpointPollFrequency() { return accessor.getProperty(TXN_LOG_CHECKPOINT_POLLFREQUENCY_KEY, TXN_LOG_CHECKPOINT_POLLFREQUENCY_DEFAULT, PropertyInterpreters.getIntegerPropertyInterpreter()); } public int getCheckpointHistory() { return accessor.getProperty(TXN_LOG_CHECKPOINT_HISTORY_KEY, TXN_LOG_CHECKPOINT_HISTORY_DEFAULT, PropertyInterpreters.getIntegerPropertyInterpreter()); } public int getEntityToDatasetLockEscalationThreshold() { return accessor.getProperty(TXN_LOCK_ESCALATIONTHRESHOLD_KEY, TXN_LOCK_ESCALATIONTHRESHOLD_DEFAULT, PropertyInterpreters.getIntegerPropertyInterpreter()); } public int getLockManagerShrinkTimer() { return accessor.getProperty(TXN_LOCK_SHRINKTIMER_KEY, TXN_LOCK_SHRINKTIMER_DEFAULT, PropertyInterpreters.getIntegerPropertyInterpreter()); } public int getTimeoutWaitThreshold() { return accessor.getProperty(TXN_LOCK_TIMEOUT_WAITTHRESHOLD_KEY, TXN_LOCK_TIMEOUT_WAITTHRESHOLD_DEFAULT, PropertyInterpreters.getIntegerPropertyInterpreter()); } public int getTimeoutSweepThreshold() { return accessor.getProperty(TXN_LOCK_TIMEOUT_SWEEPTHRESHOLD_KEY, TXN_LOCK_TIMEOUT_SWEEPTHRESHOLD_DEFAULT, PropertyInterpreters.getIntegerPropertyInterpreter()); } }
sjaco002/incubator-asterixdb
asterix-common/src/main/java/edu/uci/ics/asterix/common/config/AsterixTransactionProperties.java
Java
apache-2.0
5,130
/* * Copyright (C) 2009-2014 Johan Nilsson <http://markupartist.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.markupartist.sthlmtraveling.ui.view; import android.content.Context; import android.os.Handler; import android.os.Message; import androidx.appcompat.widget.AppCompatAutoCompleteTextView; import android.util.AttributeSet; import android.view.View; import android.widget.ProgressBar; /** * Created by johan on 27/10/14. */ public class DelayAutoCompleteTextView extends AppCompatAutoCompleteTextView { private static final int MESSAGE_TEXT_CHANGED = 100; private static final int DEFAULT_AUTO_COMPLETE_DELAY = 600; private int mAutoCompleteDelay = DEFAULT_AUTO_COMPLETE_DELAY; private ProgressBar mLoadingIndicator; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { DelayAutoCompleteTextView.super.performFiltering((CharSequence) msg.obj, msg.arg1); } }; public DelayAutoCompleteTextView(Context context, AttributeSet attrs) { super(context, attrs); } public void setProgressBar(final ProgressBar progressBar) { mLoadingIndicator = progressBar; } public void setFilterDelay(final int autoCompleteDelay) { mAutoCompleteDelay = autoCompleteDelay; } @Override protected void performFiltering(CharSequence text, int keyCode) { if (mLoadingIndicator != null) { mLoadingIndicator.setVisibility(View.VISIBLE); } mHandler.removeMessages(MESSAGE_TEXT_CHANGED); mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_TEXT_CHANGED, text), mAutoCompleteDelay); } @Override public void onFilterComplete(int count) { if (mLoadingIndicator != null) { mLoadingIndicator.setVisibility(View.GONE); } super.onFilterComplete(count); } }
johannilsson/sthlmtraveling
sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/ui/view/DelayAutoCompleteTextView.java
Java
apache-2.0
2,438
/* * 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.jmeter; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.jmeter.junit.JMeterTestCase; import org.apache.jmeter.util.JMeterUtils; /** * Check the eclipse and Maven version definitions against build.properties */ public class JMeterVersionTest extends JMeterTestCase { // Convert between eclipse jar name and build.properties name private static Map<String, String> JAR_TO_BUILD_PROP = new HashMap<String, String>(); static { JAR_TO_BUILD_PROP.put("bsf", "apache-bsf"); JAR_TO_BUILD_PROP.put("bsh", "beanshell"); JAR_TO_BUILD_PROP.put("geronimo-jms_1.1_spec", "jms"); JAR_TO_BUILD_PROP.put("htmllexer", "htmlparser"); // two jars same version JAR_TO_BUILD_PROP.put("httpmime", "httpclient"); // two jars same version JAR_TO_BUILD_PROP.put("mail", "javamail"); JAR_TO_BUILD_PROP.put("oro", "jakarta-oro"); JAR_TO_BUILD_PROP.put("xercesImpl", "xerces"); JAR_TO_BUILD_PROP.put("xpp3_min", "xpp3"); } private static final File JMETER_HOME = new File(JMeterUtils.getJMeterHome()); public JMeterVersionTest() { super(); } public JMeterVersionTest(String arg0) { super(arg0); } private final Map<String, String> versions = new HashMap<String, String>(); private final Set<String> propNames = new HashSet<String>(); private File getFileFromHome(String relativeFile) { return new File(JMETER_HOME, relativeFile); } @Override protected void setUp() throws Exception { final Properties buildProp = new Properties(); final FileInputStream bp = new FileInputStream(getFileFromHome("build.properties")); buildProp.load(bp); bp.close(); for (Entry<Object, Object> entry : buildProp.entrySet()) { final String key = (String) entry.getKey(); if (key.endsWith(".version")) { final String value = (String) entry.getValue(); final String jarprop = key.replace(".version",""); final String old = versions.put(jarprop, value); propNames.add(jarprop); if (old != null) { fail("Already have entry for "+key); } } } // remove docs-only jars propNames.remove("velocity"); propNames.remove("commons-lang"); } public void testEclipse() throws Exception { final BufferedReader eclipse = new BufferedReader( new FileReader(getFileFromHome("eclipse.classpath"))); // assume default charset is OK here // <classpathentry kind="lib" path="lib/geronimo-jms_1.1_spec-1.1.1.jar"/> // <classpathentry kind="lib" path="lib/activation-1.1.1.jar"/> // <classpathentry kind="lib" path="lib/jtidy-r938.jar"/> final Pattern p = Pattern.compile("\\s+<classpathentry kind=\"lib\" path=\"lib/(?:api/)?(.+)-([^-]+)\\.jar\"/>"); String line; while((line=eclipse.readLine()) != null){ final Matcher m = p.matcher(line); if (m.matches()) { String jar = m.group(1); String version = m.group(2); if (jar.endsWith("-jdk15on")) { // special handling jar=jar.replace("-jdk15on",""); } else if (jar.equals("commons-jexl") && version.startsWith("2")) { // special handling jar="commons-jexl2"; } else { String tmp = JAR_TO_BUILD_PROP.get(jar); if (tmp != null) { jar = tmp; } } final String expected = versions.get(jar); propNames.remove(jar); if (expected == null) { fail("Versions list does not contain: " + jar); } else { if (!version.equals(expected)) { assertEquals(jar,version,expected); } } } } eclipse.close(); if (propNames.size() > 0) { fail("Should have no names left: "+Arrays.toString(propNames.toArray()) + ". Check eclipse.classpath"); } } public void testMaven() throws Exception { final BufferedReader maven = new BufferedReader( new FileReader(getFileFromHome("res/maven/ApacheJMeter_parent.pom"))); // assume default charset is OK here // <apache-bsf.version>2.4.0</apache-bsf.version> final Pattern p = Pattern.compile("\\s+<([^\\.]+)\\.version>([^<]+)<.*"); String line; while((line=maven.readLine()) != null){ final Matcher m = p.matcher(line); if (m.matches()) { String jar = m.group(1); String version = m.group(2); String expected = versions.get(jar); propNames.remove(jar); if (expected == null) { fail("Versions list does not contain: " + jar); } else { if (!version.equals(expected)) { assertEquals(jar,expected,version); } } } } maven.close(); if (propNames.size() > 0) { fail("Should have no names left: "+Arrays.toString(propNames.toArray()) + ". Check ApacheJMeter_parent.pom"); } } }
botelhojp/apache-jmeter-2.10
test/src/org/apache/jmeter/JMeterVersionTest.java
Java
apache-2.0
6,740
/** * 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.pulsar.common.policies.data; import java.util.List; import java.util.Map; import java.util.Objects; import com.google.common.base.MoreObjects; import com.google.common.collect.Lists; import com.google.common.collect.Maps; public class Policies { public final AuthPolicies auth_policies = new AuthPolicies(); public List<String> replication_clusters = Lists.newArrayList(); public BundlesData bundles = defaultBundle(); public Map<BacklogQuota.BacklogQuotaType, BacklogQuota> backlog_quota_map = Maps.newHashMap(); public Map<String, DispatchRate> clusterDispatchRate = Maps.newHashMap(); public PersistencePolicies persistence = null; // If set, it will override the broker settings for enabling deduplication public Boolean deduplicationEnabled = null; public Map<String, Integer> latency_stats_sample_rate = Maps.newHashMap(); public int message_ttl_in_seconds = 0; public RetentionPolicies retention_policies = null; public boolean deleted = false; public String antiAffinityGroup; public static final String FIRST_BOUNDARY = "0x00000000"; public static final String LAST_BOUNDARY = "0xffffffff"; public boolean encryption_required = false; public SubscriptionAuthMode subscription_auth_mode = SubscriptionAuthMode.None; public int max_producers_per_topic = 0; public int max_consumers_per_topic = 0; public int max_consumers_per_subscription = 0; @Override public boolean equals(Object obj) { if (obj instanceof Policies) { Policies other = (Policies) obj; return Objects.equals(auth_policies, other.auth_policies) && Objects.equals(replication_clusters, other.replication_clusters) && Objects.equals(backlog_quota_map, other.backlog_quota_map) && Objects.equals(clusterDispatchRate, other.clusterDispatchRate) && Objects.equals(deduplicationEnabled, other.deduplicationEnabled) && Objects.equals(persistence, other.persistence) && Objects.equals(bundles, other.bundles) && Objects.equals(latency_stats_sample_rate, other.latency_stats_sample_rate) && message_ttl_in_seconds == other.message_ttl_in_seconds && Objects.equals(retention_policies, other.retention_policies) && Objects.equals(encryption_required, other.encryption_required) && Objects.equals(subscription_auth_mode, other.subscription_auth_mode) && Objects.equals(antiAffinityGroup, other.antiAffinityGroup) && max_producers_per_topic == other.max_producers_per_topic && max_consumers_per_topic == other.max_consumers_per_topic && max_consumers_per_subscription == other.max_consumers_per_subscription; } return false; } public static BundlesData defaultBundle() { BundlesData bundle = new BundlesData(1); List<String> boundaries = Lists.newArrayList(); boundaries.add(FIRST_BOUNDARY); boundaries.add(LAST_BOUNDARY); bundle.setBoundaries(boundaries); return bundle; } @Override public String toString() { return MoreObjects.toStringHelper(this).add("auth_policies", auth_policies) .add("replication_clusters", replication_clusters).add("bundles", bundles) .add("backlog_quota_map", backlog_quota_map).add("persistence", persistence) .add("deduplicationEnabled", deduplicationEnabled) .add("clusterDispatchRate", clusterDispatchRate) .add("latency_stats_sample_rate", latency_stats_sample_rate) .add("antiAffinityGroup", antiAffinityGroup) .add("message_ttl_in_seconds", message_ttl_in_seconds).add("retention_policies", retention_policies) .add("deleted", deleted) .add("encryption_required", encryption_required) .add("subscription_auth_mode", subscription_auth_mode) .add("max_producers_per_topic", max_producers_per_topic) .add("max_consumers_per_topic", max_consumers_per_topic) .add("max_consumers_per_subscription", max_consumers_per_topic).toString(); } }
sschepens/pulsar
pulsar-common/src/main/java/org/apache/pulsar/common/policies/data/Policies.java
Java
apache-2.0
5,175
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.java.util.common; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.io.ByteSource; import com.google.common.io.Files; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.StandardCopyOption; import java.util.Arrays; import java.util.Collection; import java.util.UUID; public class FileUtils { /** * Useful for retry functionality that doesn't want to stop Throwables, but does want to retry on Exceptions */ public static final Predicate<Throwable> IS_EXCEPTION = new Predicate<Throwable>() { @Override public boolean apply(Throwable input) { return input instanceof Exception; } }; /** * Copy input byte source to outFile. If outFile exists, it is attempted to be deleted. * * @param byteSource Supplier for an input stream that is to be copied. The resulting stream is closed each iteration * @param outFile Where the file should be written to. * @param shouldRetry Predicate indicating if an error is recoverable and should be retried. * @param maxAttempts The maximum number of assumed recoverable attempts to try before completely failing. * * @throws RuntimeException wrapping the inner exception on failure. */ public static FileCopyResult retryCopy( final ByteSource byteSource, final File outFile, final Predicate<Throwable> shouldRetry, final int maxAttempts ) { try { StreamUtils.retryCopy( byteSource, Files.asByteSink(outFile), shouldRetry, maxAttempts ); return new FileCopyResult(outFile); } catch (Exception e) { throw Throwables.propagate(e); } } /** * Keeps results of a file copy, including children and total size of the resultant files. * This class is NOT thread safe. * Child size is eagerly calculated and any modifications to the file after the child is added are not accounted for. * As such, this result should be considered immutable, even though it has no way to force that property on the files. */ public static class FileCopyResult { private final Collection<File> files = Lists.newArrayList(); private long size = 0L; public Collection<File> getFiles() { return ImmutableList.copyOf(files); } // Only works for immutable children contents public long size() { return size; } public FileCopyResult(File... files) { this(files == null ? ImmutableList.<File>of() : Arrays.asList(files)); } public FileCopyResult(Collection<File> files) { this.addSizedFiles(files); } protected void addSizedFiles(Collection<File> files) { if (files == null || files.isEmpty()) { return; } long size = 0L; for (File file : files) { size += file.length(); } this.files.addAll(files); this.size += size; } public void addFiles(Collection<File> files) { this.addSizedFiles(files); } public void addFile(File file) { this.addFiles(ImmutableList.of(file)); } } /** * Fully maps a file read-only in to memory as per * {@link FileChannel#map(FileChannel.MapMode, long, long)}. * * <p>Files are mapped from offset 0 to its length. * * <p>This only works for files <= {@link Integer#MAX_VALUE} bytes. * * <p>Similar to {@link Files#map(File)}, but returns {@link MappedByteBufferHandler}, that makes it easier to unmap * the buffer within try-with-resources pattern: * <pre>{@code * try (MappedByteBufferHandler fileMappingHandler = FileUtils.map(file)) { * ByteBuffer fileMapping = fileMappingHandler.get(); * // use mapped buffer * }}</pre> * * @param file the file to map * * @return a {@link MappedByteBufferHandler}, wrapping a read-only buffer reflecting {@code file} * * @throws FileNotFoundException if the {@code file} does not exist * @throws IOException if an I/O error occurs * @see FileChannel#map(FileChannel.MapMode, long, long) */ public static MappedByteBufferHandler map(File file) throws IOException { MappedByteBuffer mappedByteBuffer = Files.map(file); return new MappedByteBufferHandler(mappedByteBuffer); } /** * Write to a file atomically, by first writing to a temporary file in the same directory and then moving it to * the target location. This function attempts to clean up its temporary files when possible, but they may stick * around (for example, if the JVM crashes partway through executing the function). In any case, the target file * should be unharmed. * * The OutputStream passed to the consumer is uncloseable; calling close on it will do nothing. This is to ensure * that the stream stays open so we can fsync it here before closing. Hopefully, this doesn't cause any problems * for callers. * * This method is not just thread-safe, but is also safe to use from multiple processes on the same machine. */ public static void writeAtomically(final File file, OutputStreamConsumer f) throws IOException { writeAtomically(file, file.getParentFile(), f); } private static void writeAtomically(final File file, final File tmpDir, OutputStreamConsumer f) throws IOException { final File tmpFile = new File(tmpDir, StringUtils.format(".%s.%s", file.getName(), UUID.randomUUID())); try { try (final FileOutputStream out = new FileOutputStream(tmpFile)) { // Pass f an uncloseable stream so we can fsync before closing. f.accept(uncloseable(out)); // fsync to avoid write-then-rename-then-crash causing empty files on some filesystems. out.getChannel().force(true); } // No exception thrown; do the move. java.nio.file.Files.move( tmpFile.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING ); } finally { tmpFile.delete(); } } private static OutputStream uncloseable(final OutputStream out) throws IOException { return new FilterOutputStream(out) { @Override public void close() throws IOException { // Do nothing. } }; } public interface OutputStreamConsumer { void accept(OutputStream outputStream) throws IOException; } }
metamx/druid
java-util/src/main/java/io/druid/java/util/common/FileUtils.java
Java
apache-2.0
7,547
package pt.ist.rest.exception.core.invalidkey; import pt.ist.rest.exception.CoreException; /** * Excepção que indica que o saldo do cliente é negativo. */ public class InvalidCreditException extends CoreException { private int saldo; private static final long serialVersionUID = 1L; public InvalidCreditException() { // Existe para ser serializavel } public InvalidCreditException(int saldo) { this.saldo = saldo; } @Override public String getMessage() { return "O crédito é negativo ao actualizar: " + saldo + " ."; } }
Andre-Pires/SoftwareEngineering
rest/src/main/java/pt/ist/rest/exception/core/invalidkey/InvalidCreditException.java
Java
apache-2.0
604
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * FileErrorReason.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.admanager.axis.v202102; public class FileErrorReason implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected FileErrorReason(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _MISSING_CONTENTS = "MISSING_CONTENTS"; public static final java.lang.String _SIZE_TOO_LARGE = "SIZE_TOO_LARGE"; public static final java.lang.String _UNKNOWN = "UNKNOWN"; public static final FileErrorReason MISSING_CONTENTS = new FileErrorReason(_MISSING_CONTENTS); public static final FileErrorReason SIZE_TOO_LARGE = new FileErrorReason(_SIZE_TOO_LARGE); public static final FileErrorReason UNKNOWN = new FileErrorReason(_UNKNOWN); public java.lang.String getValue() { return _value_;} public static FileErrorReason fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { FileErrorReason enumeration = (FileErrorReason) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static FileErrorReason fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(FileErrorReason.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "FileError.Reason")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
googleads/googleads-java-lib
modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202102/FileErrorReason.java
Java
apache-2.0
3,540
package com.cai.test; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>anonymous complex typeµÄ Java Àà¡£ * * <p>ÒÔÏÂģʽƬ¶ÎÖ¸¶¨°üº¬ÔÚ´ËÀàÖеÄÔ¤ÆÚÄÚÈÝ¡£ * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="strXML" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "strXML" }) @XmlRootElement(name = "receiptPO") public class ReceiptPO { protected String strXML; /** * »ñÈ¡strXMLÊôÐÔµÄÖµ¡£ * * @return * possible object is * {@link String } * */ public String getStrXML() { return strXML; } /** * ÉèÖÃstrXMLÊôÐÔµÄÖµ¡£ * * @param value * allowed object is * {@link String } * */ public void setStrXML(String value) { this.strXML = value; } }
wangshijun101/JavaSenior
J2EE/src/main/java/com/cai/test/ReceiptPO.java
Java
apache-2.0
1,282
/* * Copyright 2017 The Mifos Initiative. * * 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.mifos.portfolio.api.v1.client; import io.mifos.core.api.annotation.ThrowsException; import io.mifos.core.api.util.CustomFeignClientsConfiguration; import io.mifos.portfolio.api.v1.domain.Payment; import io.mifos.portfolio.api.v1.domain.*; import io.mifos.portfolio.api.v1.validation.ValidSortColumn; import io.mifos.portfolio.api.v1.validation.ValidSortDirection; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.math.BigDecimal; import java.util.List; import java.util.Set; /** * @author Myrle Krantz */ @SuppressWarnings("unused") @FeignClient(value = "portfolio-v1", path = "/portfolio/v1", configuration = CustomFeignClientsConfiguration.class) public interface PortfolioManager { @RequestMapping( value = "/patterns/", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) List<Pattern> getAllPatterns(); @RequestMapping( value = "/products/", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) ProductPage getProducts( @RequestParam(value = "includeDisabled", required = false) final Boolean includeDisabled, @RequestParam(value = "term", required = false) final String term, @RequestParam(value = "pageIndex") final Integer pageIndex, @RequestParam(value = "size") final Integer size, @RequestParam(value = "sortColumn", required = false) @ValidSortColumn(value = {"lastModifiedOn", "identifier", "name"}) final String sortColumn, @RequestParam(value = "sortDirection", required = false) @ValidSortDirection final String sortDirection); @RequestMapping( value = "/products", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) @ThrowsException(status = HttpStatus.CONFLICT, exception = ProductAlreadyExistsException.class) void createProduct(final Product product); @RequestMapping( value = "/products/{productidentifier}", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) Product getProduct(@PathVariable("productidentifier") final String productIdentifier); @RequestMapping( value = "/products/{productidentifier}", method = RequestMethod.PUT, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ThrowsException(status = HttpStatus.CONFLICT, exception = ProductInUseException.class) void changeProduct( @PathVariable("productidentifier") final String productIdentifier, final Product product); @RequestMapping( value = "/products/{productidentifier}", method = RequestMethod.DELETE, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) @ThrowsException(status = HttpStatus.CONFLICT, exception = ProductInUseException.class) void deleteProduct( @PathVariable("productidentifier") final String productIdentifier); @RequestMapping( value = "/products/{productidentifier}/incompleteaccountassignments", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) Set<AccountAssignment> getIncompleteAccountAssignments( @PathVariable("productidentifier") final String productIdentifier); @RequestMapping( value = "/products/{productidentifier}/enabled", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ThrowsException(status = HttpStatus.CONFLICT, exception = ProductDefinitionIncomplete.class) void enableProduct( @PathVariable("productidentifier") final String productIdentifier, final Boolean enabled); @RequestMapping( value = "/products/{productidentifier}/enabled", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) Boolean getProductEnabled(@PathVariable("productidentifier") final String productIdentifier); @RequestMapping( value = "/products/{productidentifier}/balancesegmentsets/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ThrowsException(status = HttpStatus.CONFLICT, exception = ProductInUseException.class) void createBalanceSegmentSet( @PathVariable("productidentifier") final String productIdentifier, final BalanceSegmentSet balanceSegmentSet); @RequestMapping( value = "/products/{productidentifier}/balancesegmentsets/", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) @ThrowsException(status = HttpStatus.CONFLICT, exception = ProductInUseException.class) List<BalanceSegmentSet> getAllBalanceSegmentSets( @PathVariable("productidentifier") final String productIdentifier); @RequestMapping( value = "/products/{productidentifier}/balancesegmentsets/{balancesegmentsetidentifier}", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) BalanceSegmentSet getBalanceSegmentSet( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("balancesegmentsetidentifier") final String balanceSegmentSetIdentifier); @RequestMapping( value = "/products/{productidentifier}/balancesegmentsets/{balancesegmentsetidentifier}", method = RequestMethod.PUT, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ThrowsException(status = HttpStatus.CONFLICT, exception = ProductInUseException.class) void changeBalanceSegmentSet( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("balancesegmentsetidentifier") final String balanceSegmentSetIdentifier, BalanceSegmentSet balanceSegmentSet); @RequestMapping( value = "/products/{productidentifier}/balancesegmentsets/{balancesegmentsetidentifier}", method = RequestMethod.DELETE, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) @ThrowsException(status = HttpStatus.CONFLICT, exception = ProductInUseException.class) void deleteBalanceSegmentSet( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("balancesegmentsetidentifier") final String balanceSegmentSetIdentifier); @RequestMapping( value = "/products/{productidentifier}/tasks/", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) List<TaskDefinition> getAllTaskDefinitionsForProduct( @PathVariable("productidentifier") final String productIdentifier); @RequestMapping( value = "/products/{productidentifier}/tasks/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) @ThrowsException(status = HttpStatus.CONFLICT, exception = ProductInUseException.class) void createTaskDefinition( @PathVariable("productidentifier") final String productIdentifier, final TaskDefinition taskDefinition); @RequestMapping( value = "/products/{productidentifier}/tasks/{taskidentifier}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) TaskDefinition getTaskDefinition( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("taskidentifier") final String taskDefinitionIdentifier); @RequestMapping( value = "/products/{productidentifier}/tasks/{taskidentifier}", method = RequestMethod.PUT, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ThrowsException(status = HttpStatus.CONFLICT, exception = ProductInUseException.class) void changeTaskDefinition( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("taskidentifier") final String taskDefinitionIdentifier, final TaskDefinition taskDefinition); @RequestMapping( value = "/products/{productidentifier}/tasks/{taskidentifier}", method = RequestMethod.DELETE, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ThrowsException(status = HttpStatus.CONFLICT, exception = ProductInUseException.class) void deleteTaskDefinition( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("taskidentifier") final String taskDefinitionIdentifier); @RequestMapping( value = "/products/{productidentifier}/charges/", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) List<ChargeDefinition> getAllChargeDefinitionsForProduct( @PathVariable("productidentifier") final String productIdentifier); @RequestMapping( value = "/products/{productidentifier}/charges/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) void createChargeDefinition( @PathVariable("productidentifier") final String productIdentifier, final ChargeDefinition taskDefinition); @RequestMapping( value = "/products/{productidentifier}/charges/{chargedefinitionidentifier}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) ChargeDefinition getChargeDefinition( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("chargedefinitionidentifier") final String chargeDefinitionIdentifier); @RequestMapping( value = "/products/{productidentifier}/charges/{chargedefinitionidentifier}", method = RequestMethod.PUT, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) void changeChargeDefinition( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("chargedefinitionidentifier") final String chargeDefinitionIdentifier, final ChargeDefinition chargeDefinition); @RequestMapping( value = "/products/{productidentifier}/charges/{chargedefinitionidentifier}", method = RequestMethod.DELETE, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) void deleteChargeDefinition( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("chargedefinitionidentifier") final String chargeDefinitionIdentifier); @RequestMapping( value = "/products/{productidentifier}/cases/", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) CasePage getAllCasesForProduct( @PathVariable("productidentifier") final String productIdentifier, @RequestParam(value = "includeClosed", required = false) final Boolean includeClosed, @RequestParam("pageIndex") final Integer pageIndex, @RequestParam("size") final Integer size); @RequestMapping( value = "/products/{productidentifier}/cases/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) @ThrowsException(status = HttpStatus.CONFLICT, exception = CaseAlreadyExistsException.class) void createCase( @PathVariable("productidentifier") final String productIdentifier, final Case caseInstance); @RequestMapping( value = "/products/{productidentifier}/cases/{caseidentifier}", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) Case getCase( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("caseidentifier") final String caseIdentifier); @RequestMapping( value = "/products/{productidentifier}/cases/{caseidentifier}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) void changeCase( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("caseidentifier") final String caseIdentifier, final Case caseInstance); @RequestMapping( value = "/products/{productidentifier}/cases/{caseidentifier}/actions/", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) Set<String> getActionsForCase( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("caseidentifier") final String caseIdentifier); @RequestMapping( value = "/products/{productidentifier}/cases/{caseidentifier}/actions/{actionidentifier}/costcomponents", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) Payment getCostComponentsForAction( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("caseidentifier") final String caseIdentifier, @PathVariable("actionidentifier") final String actionIdentifier, @RequestParam(value="touchingaccounts", required = false, defaultValue = "") final Set<String> forAccountDesignators, @RequestParam(value="forpaymentsize", required = false, defaultValue = "") final BigDecimal forPaymentSize); @RequestMapping( value = "/products/{productidentifier}/cases/{caseidentifier}/actions/{actionidentifier}/costcomponents", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) Payment getCostComponentsForAction( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("caseidentifier") final String caseIdentifier, @PathVariable("actionidentifier") final String actionIdentifier, @RequestParam(value="touchingaccounts", required = false, defaultValue = "") final Set<String> forAccountDesignators, @RequestParam(value="forpaymentsize", required = false, defaultValue = "") final BigDecimal forPaymentSize, @RequestParam(value="fordatetime", required = false, defaultValue = "") final String forDateTime); @RequestMapping( value = "/products/{productidentifier}/cases/{caseidentifier}/actions/{actionidentifier}/costcomponents", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) Payment getCostComponentsForAction( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("caseidentifier") final String caseIdentifier, @PathVariable("actionidentifier") final String actionIdentifier, @RequestParam(value="touchingaccounts", required = false, defaultValue = "") final Set<String> forAccountDesignators); @RequestMapping( value = "/products/{productidentifier}/cases/{caseidentifier}/actions/{actionidentifier}/costcomponents", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) Payment getCostComponentsForAction( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("caseidentifier") final String caseIdentifier, @PathVariable("actionidentifier") final String actionIdentifier); @RequestMapping( value = "/products/{productidentifier}/cases/{caseidentifier}/commands/{actionidentifier}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) @ThrowsException(status = HttpStatus.CONFLICT, exception = TaskOutstanding.class) void executeCaseCommand( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("caseidentifier") final String caseIdentifier, @PathVariable("actionidentifier") final String actionIdentifier, final Command command); @RequestMapping( value = "/products/{productidentifier}/cases/{caseidentifier}/tasks/", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) List<TaskInstance> getAllTasksForCase( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("caseidentifier") final String caseIdentifier, @RequestParam(value = "includeExecuted", required = false) final Boolean includeExecuted); @RequestMapping( value = "/products/{productidentifier}/cases/{caseidentifier}/tasks/{taskidentifier}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) TaskInstance getTaskForCase( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("caseidentifier") final String caseIdentifier, @PathVariable("taskidentifier") final String taskIdentifier); @RequestMapping( value = "/products/{productidentifier}/cases/{caseidentifier}/tasks/{taskidentifier}", method = RequestMethod.PUT, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) void changeTaskForCase( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("caseidentifier") final String caseIdentifier, @PathVariable("taskidentifier") final String taskIdentifier, final TaskInstance instance); @RequestMapping( value = "/products/{productidentifier}/cases/{caseidentifier}/tasks/{taskidentifier}/executed", method = RequestMethod.PUT, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) @ThrowsException(status = HttpStatus.CONFLICT, exception = TaskExecutionBySameUserAsCaseCreation.class) void markTaskExecution( @PathVariable("productidentifier") final String productIdentifier, @PathVariable("caseidentifier") final String caseIdentifier, @PathVariable("taskidentifier") final String taskIdentifier, final Boolean executed); @RequestMapping( value = "/cases/", method = RequestMethod.GET, produces = MediaType.ALL_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) CasePage getAllCases( @RequestParam("pageIndex") final Integer pageIndex, @RequestParam("size") final Integer size); }
mifosio/portfolio
api/src/main/java/io/mifos/portfolio/api/v1/client/PortfolioManager.java
Java
apache-2.0
19,737
/* * Copyright 2014 Carsten Rambow, elomagic. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.elomagic.carafile.share; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.util.Date; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * */ public final class JsonUtil { private JsonUtil() { } /** * Creates a {@link Gson} instance inclduing (de)serializer for class {@link Date}. * * @return */ public static Gson createGsonInstance() { GsonBuilder gb = new GsonBuilder(); gb.registerTypeAdapter(Date.class, new DateDeserializer()); gb.registerTypeAdapter(Date.class, new DateSerializer()); return gb.create(); } public static MetaData readFromReader(final Reader reader) { return read(reader, MetaData.class); } public static <T> T read(final Reader reader, Class<T> clazz) { Gson gson = createGsonInstance(); return gson.fromJson(reader, clazz); } public static InputStream write(final Object o, final Charset charset) { Gson gson = createGsonInstance(); String s = gson.toJson(o); return new ByteArrayInputStream(s.getBytes(charset)); } public static void write(final Object o, final Writer writer) { Gson gson = createGsonInstance(); gson.toJson(o, writer); } public static String write(final Object o) { Gson gson = createGsonInstance(); return gson.toJson(o); } }
elomagic/carafile
filesharing-client/src/main/java/de/elomagic/carafile/share/JsonUtil.java
Java
apache-2.0
2,123
/** * 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.tajo.engine.planner.global; import org.apache.tajo.ExecutionBlockId; import org.apache.tajo.QueryId; import org.apache.tajo.engine.planner.LogicalPlan; import org.apache.tajo.engine.planner.PlannerUtil; import org.apache.tajo.engine.planner.enforce.Enforcer; import org.apache.tajo.engine.planner.graph.SimpleDirectedGraph; import org.apache.tajo.engine.query.QueryContext; import org.apache.tajo.ipc.TajoWorkerProtocol; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; public class MasterPlan { private final QueryId queryId; private final QueryContext context; private final LogicalPlan plan; private ExecutionBlock root; private AtomicInteger nextId = new AtomicInteger(0); private ExecutionBlock terminalBlock; private Map<ExecutionBlockId, ExecutionBlock> execBlockMap = new HashMap<ExecutionBlockId, ExecutionBlock>(); private SimpleDirectedGraph<ExecutionBlockId, DataChannel> execBlockGraph = new SimpleDirectedGraph<ExecutionBlockId, DataChannel>(); public ExecutionBlockId newExecutionBlockId() { return new ExecutionBlockId(queryId, nextId.incrementAndGet()); } public boolean isTerminal(ExecutionBlock execBlock) { return terminalBlock.getId().equals(execBlock.getId()); } public ExecutionBlock getTerminalBlock() { return terminalBlock; } public ExecutionBlock createTerminalBlock() { terminalBlock = newExecutionBlock(); return terminalBlock; } public MasterPlan(QueryId queryId, QueryContext context, LogicalPlan plan) { this.queryId = queryId; this.context = context; this.plan = plan; } public QueryId getQueryId() { return this.queryId; } public QueryContext getContext() { return this.context; } public LogicalPlan getLogicalPlan() { return this.plan; } public void setTerminal(ExecutionBlock root) { this.root = root; this.terminalBlock = root; } public ExecutionBlock getRoot() { return this.root; } public ExecutionBlock newExecutionBlock() { ExecutionBlock newExecBlock = new ExecutionBlock(newExecutionBlockId()); execBlockMap.put(newExecBlock.getId(), newExecBlock); return newExecBlock; } public boolean containsExecBlock(ExecutionBlockId execBlockId) { return execBlockMap.containsKey(execBlockId); } public ExecutionBlock getExecBlock(ExecutionBlockId execBlockId) { return execBlockMap.get(execBlockId); } public void addConnect(DataChannel dataChannel) { execBlockGraph.addEdge(dataChannel.getSrcId(), dataChannel.getTargetId(), dataChannel); } public void addConnect(ExecutionBlock src, ExecutionBlock target, TajoWorkerProtocol.ShuffleType type) { addConnect(src.getId(), target.getId(), type); } public void addConnect(ExecutionBlockId src, ExecutionBlockId target, TajoWorkerProtocol.ShuffleType type) { addConnect(new DataChannel(src, target, type)); } public boolean isConnected(ExecutionBlock src, ExecutionBlock target) { return isConnected(src.getId(), target.getId()); } public boolean isConnected(ExecutionBlockId src, ExecutionBlockId target) { return execBlockGraph.hasEdge(src, target); } public boolean isReverseConnected(ExecutionBlock target, ExecutionBlock src) { return execBlockGraph.hasReversedEdge(target.getId(), src.getId()); } public boolean isReverseConnected(ExecutionBlockId target, ExecutionBlockId src) { return execBlockGraph.hasReversedEdge(target, src); } public DataChannel getChannel(ExecutionBlock src, ExecutionBlock target) { return execBlockGraph.getEdge(src.getId(), target.getId()); } public DataChannel getChannel(ExecutionBlockId src, ExecutionBlockId target) { return execBlockGraph.getEdge(src, target); } public List<DataChannel> getOutgoingChannels(ExecutionBlockId src) { return execBlockGraph.getOutgoingEdges(src); } public boolean isRoot(ExecutionBlock execBlock) { if (!execBlock.getId().equals(terminalBlock.getId())) { return execBlockGraph.getParent(execBlock.getId(), 0).equals(terminalBlock.getId()); } else { return false; } } public boolean isLeaf(ExecutionBlock execBlock) { return execBlockGraph.isLeaf(execBlock.getId()); } public boolean isLeaf(ExecutionBlockId id) { return execBlockGraph.isLeaf(id); } public List<DataChannel> getIncomingChannels(ExecutionBlockId target) { return execBlockGraph.getIncomingEdges(target); } public void disconnect(ExecutionBlock src, ExecutionBlock target) { disconnect(src.getId(), target.getId()); } public void disconnect(ExecutionBlockId src, ExecutionBlockId target) { execBlockGraph.removeEdge(src, target); } public ExecutionBlock getParent(ExecutionBlock executionBlock) { return execBlockMap.get(execBlockGraph.getParent(executionBlock.getId(), 0)); } public List<ExecutionBlock> getChilds(ExecutionBlock execBlock) { return getChilds(execBlock.getId()); } public List<ExecutionBlock> getChilds(ExecutionBlockId id) { List<ExecutionBlock> childBlocks = new ArrayList<ExecutionBlock>(); for (ExecutionBlockId cid : execBlockGraph.getChilds(id)) { childBlocks.add(execBlockMap.get(cid)); } return childBlocks; } public int getChildCount(ExecutionBlockId blockId) { return execBlockGraph.getChildCount(blockId); } public ExecutionBlock getChild(ExecutionBlockId execBlockId, int idx) { return execBlockMap.get(execBlockGraph.getChild(execBlockId, idx)); } public ExecutionBlock getChild(ExecutionBlock executionBlock, int idx) { return getChild(executionBlock.getId(), idx); } @Override public String toString() { StringBuilder sb = new StringBuilder(); ExecutionBlockCursor cursor = new ExecutionBlockCursor(this); sb.append("-------------------------------------------------------------------------------\n"); sb.append("Execution Block Graph (TERMINAL - " + getTerminalBlock() + ")\n"); sb.append("-------------------------------------------------------------------------------\n"); sb.append(execBlockGraph.toStringGraph(getRoot().getId())); sb.append("-------------------------------------------------------------------------------\n"); ExecutionBlockCursor executionOrderCursor = new ExecutionBlockCursor(this, true); sb.append("Order of Execution\n"); sb.append("-------------------------------------------------------------------------------"); int order = 1; while (executionOrderCursor.hasNext()) { ExecutionBlock currentEB = executionOrderCursor.nextBlock(); sb.append("\n").append(order).append(": ").append(currentEB.getId()); order++; } sb.append("\n-------------------------------------------------------------------------------\n"); while(cursor.hasNext()) { ExecutionBlock block = cursor.nextBlock(); boolean terminal = false; sb.append("\n"); sb.append("=======================================================\n"); sb.append("Block Id: " + block.getId()); if (isTerminal(block)) { sb.append(" [TERMINAL]"); terminal = true; } else if (isRoot(block)) { sb.append(" [ROOT]"); } else if (isLeaf(block)) { sb.append(" [LEAF]"); } else { sb.append(" [INTERMEDIATE]"); } sb.append("\n"); sb.append("=======================================================\n"); if (terminal) { continue; } if (!isLeaf(block)) { sb.append("\n[Incoming]\n"); for (DataChannel channel : getIncomingChannels(block.getId())) { sb.append(channel); if (block.getUnionScanMap().containsKey(channel.getSrcId())) { sb.append(", union delegated scan: ").append(block.getUnionScanMap().get(channel.getSrcId())); } sb.append("\n"); } } if (!isRoot(block)) { sb.append("\n[Outgoing]\n"); for (DataChannel channel : getOutgoingChannels(block.getId())) { sb.append(channel); sb.append("\n"); } } if (block.getEnforcer().getProperties().size() > 0) { sb.append("\n[Enforcers]\n"); int i = 0; for (TajoWorkerProtocol.EnforceProperty enforce : block.getEnforcer().getProperties()) { sb.append(" ").append(i++).append(": "); sb.append(Enforcer.toString(enforce)); sb.append("\n"); } } sb.append("\n").append(PlannerUtil.buildExplainString(block.getPlan())); } return sb.toString(); } }
yeeunshim/tajo_test
tajo-core/src/main/java/org/apache/tajo/engine/planner/global/MasterPlan.java
Java
apache-2.0
9,498
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.enterprise.cloudsearch.sharepoint; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.logging.Level; import java.util.logging.Logger; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.xml.ws.Holder; /** * InvocationHandler that can wrap WebService instances and log input/output * values. This is more helpful than manual logging because it checks the * mode of a parameter and only prints it when appropriate. The mode of a * parameter defines when it is sent, so this logging method accurately * represents the exchange of information. */ class LoggingWSHandler implements InvocationHandler { private static final Logger log = Logger.getLogger(LoggingWSHandler.class.getName()); private final Object wrapped; public LoggingWSHandler(Object wrapped) { this.wrapped = wrapped; } public static <T> T create(Class<T> webServiceInterface, T wrapped) { InvocationHandler invokeHandler = new LoggingWSHandler(wrapped); Object oInstance = Proxy.newProxyInstance( LoggingWSHandler.class.getClassLoader(), new Class<?>[] {webServiceInterface}, invokeHandler); @SuppressWarnings("unchecked") T tInstance = (T) oInstance; return tInstance; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final Level logLevel = Level.FINE; String inArgs = null; if (log.isLoggable(logLevel)) { WebMethod webMethod = method.getAnnotation(WebMethod.class); if (webMethod != null) { inArgs = formArgumentString(method, args, WebParam.Mode.IN); log.log(logLevel, "WS Request {0}: {1}", new Object[] {webMethod.operationName(), inArgs}); } } Object ret; long startMillis = System.currentTimeMillis(); try { ret = method.invoke(wrapped, args); } catch (IllegalAccessException ex) { throw new RuntimeException("Misconfigured LoggingWSHandler", ex); } catch (IllegalArgumentException ex) { throw new RuntimeException("Misconfigured LoggingWSHandler", ex); } catch (InvocationTargetException ex) { throw ex.getCause(); } if (log.isLoggable(logLevel)) { WebMethod webMethod = method.getAnnotation(WebMethod.class); if (webMethod != null) { String outArgs = formArgumentString(method, args, WebParam.Mode.OUT); log.log(logLevel, "WS Response {0}: {1}", new Object[] {webMethod.operationName(), outArgs}); log.log(logLevel, "Duration: WS Request {0} - {1} : {2,number,#} ms", new Object[] {webMethod.operationName(), inArgs, System.currentTimeMillis() - startMillis}); } } return ret; } private String formArgumentString(Method method, Object[] args, WebParam.Mode mode) { StringBuilder argsBuffer = new StringBuilder(); Annotation[][] annotates = method.getParameterAnnotations(); if (annotates.length != 0 && annotates.length != args.length) { throw new AssertionError(); } for (int i = 0; i < annotates.length; i++) { for (Annotation annotate : annotates[i]) { if (!(annotate instanceof WebParam)) { break; } WebParam webParam = (WebParam) annotate; if (webParam.mode() == mode || webParam.mode() == WebParam.Mode.INOUT) { argsBuffer.append(", ").append(webParam.name()).append("="); if (webParam.mode() == WebParam.Mode.IN) { argsBuffer.append("" + args[i]); } else { Holder<?> holder = (Holder<?>) args[i]; argsBuffer.append( holder == null ? "<null holder>" : "" + holder.value); } } } } return argsBuffer.length() > 1 ? argsBuffer.substring(2) : ""; } }
google-cloudsearch/sharepoint-connector
src/main/java/com/google/enterprise/cloudsearch/sharepoint/LoggingWSHandler.java
Java
apache-2.0
4,566
/******************************************************************************* * Copyright 2012 EMBL-EBI, Hinxton outstation * * 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 uk.ac.ebi.embl.api.entry.qualifier; import org.apache.commons.lang.builder.CompareToBuilder; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import uk.ac.ebi.embl.api.storage.CachedFileDataManager; import uk.ac.ebi.embl.api.storage.DataManager; import uk.ac.ebi.embl.api.storage.DataRow; import uk.ac.ebi.embl.api.storage.DataSet; import uk.ac.ebi.embl.api.validation.*; import uk.ac.ebi.embl.api.validation.check.CheckFileManager; import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; public class Qualifier implements HasOrigin, Serializable, Comparable<Qualifier> { private static final long serialVersionUID = -3946561979283315312L; public static final String ORGANISM_QUALIFIER_NAME = "organism"; public static final String TRANSLATION_QUALIFIER_NAME = "translation"; public static final String PROTEIN_ID_QUALIFIER_NAME = "protein_id"; public static final String CODON_QUALIFIER_NAME = "codon"; public static final String TRANSL_EXCEPT_QUALIFIER_NAME = "transl_except"; public static final String TRANSL_TABLE_QUALIFIER_NAME = "transl_table"; public static final String EXCEPTION_QUALIFIER_NAME = "exception"; public static final String PSEUDO_QUALIFIER_NAME = "pseudo"; public static final String PSEUDOGENE_QUALIFIER_NAME = "pseudogene"; public static final String PARTIAL_QUALIFIER_NAME = "partial"; public static final String CODON_START_QUALIFIER_NAME = "codon_start"; public static final String CITATION_QUALIFIER_NAME = "citation"; public static final String FOCUS_QUALIFIER_NAME = "focus"; public static final String TRANSGENIC_QUALIFIER_NAME = "transgenic"; public static final String DB_XREF_QUALIFIER_NAME = "db_xref"; public static final String MOL_TYPE_QUALIFIER_NAME = "mol_type"; public static final String GENE_QUALIFIER_NAME = "gene"; public static final String GENE_SYNONYM_NAME = "gene_synonym"; public static final String LOCUS_TAG_QUALIFIER_NAME = "locus_tag"; public static final String RIBOSOMAL_SLIPPAGE_QUALIFIER_NAME = "ribosomal_slippage"; public static final String ESTIMATED_LENGTH_QUALIFIER_NAME = "estimated_length"; public static final String NOTE_QUALIFIER_NAME = "note"; public static final String MOBILE_ELEMENT_NAME = "mobile_element"; public static final String LABEL_QUALIFIER_NAME = "label"; public static final String REPLACE_QUALIFIER_NAME = "replace"; public static final String COMPARE_QUALIFIER_NAME = "compare"; public static final String COLLECTION_DATE_QUALIFIER_NAME = "collection_date"; public static final String ANTICODON_QUALIFIER_NAME = "anticodon"; public static final String RPT_UNIT_RANGE_QUALIFIER_NAME = "rpt_unit_range"; public static final String TAG_PEPTIDE_QUALIFIER_NAME = "tag_peptide"; public static final String PROVIRAL_QUALIFIER_NAME = "proviral"; public static final String ORGANELLE_QUALIFIER_NAME = "organelle"; public static final String PLASMID_QUALIFIER_NAME = "plasmid"; public static final String PRODUCT_QUALIFIER_NAME = "product"; public static final String ISOLATE_QUALIFIER_NAME = "isolate"; public static final String ISOLATION_SOURCE_QUALIFIER_NAME = "isolation_source"; public static final String CLONE_QUALIFIER_NAME = "clone"; public static final String MAP_QUALIFIER_NAME = "map"; public static final String STRAIN_QUALIFIER_NAME = "strain"; public static final String CHROMOSOME_QUALIFIER_NAME = "chromosome"; public static final String SEGMENT_QUALIFIER_NAME = "segment"; public static final String EC_NUMBER_QUALIFIER_NAME = "EC_number"; public static final String OLD_LOCUS_TAG = "old_locus_tag"; public static final String PCR_PRIMERS_QUALIFIER_NAME = "PCR_primers"; public static final String LAT_LON_QUALIFIER_NAME = "lat_lon"; public static final String SATELLITE_QUALIFIER_NAME = "satellite"; public static final String NCRNA_CLASS_QUALIFIER_NAME = "ncRNA_class"; public static final String GAP_TYPE_QUALIFIER_NAME = "gap_type"; public static final String LINKAGE_EVIDENCE_QUALIFIER_NAME = "linkage_evidence"; public static final String NUMBER_QUALIFIER_NAME = "number"; public static final String EXPERIMENT_QUALIFIER_NAME = "experiment"; public static final String TYPE_MATERIAL_QUALIFIER_NAME = "type_material"; public static final String GERMLINE_QUALIFIER_NAME = "germline"; public static final String MACRONUCLEAR_QUALIFIER_NAME = "macronuclear"; public static final String REARRANGED_QUALIFIER_NAME = "rearranged"; public static final String ENVIRONMENTAL_SAMPLE_QUALIFIER_NAME = "environmental_sample"; public static final String HOST_QUALIFIER_NAME = "host"; public static final String OPERON_QUALIFIER_NAME = "operon"; public static final String COUNTRY_QUALIFIER_NAME = "country"; public static final String REGULATORY_CLASS_QUALIFIER_NAME = "regulatory_class"; public static final String ALTITUDE_QUALIFIER_NAME = "altitude"; public static final String ARTIFICIAL_LOCATION = "artificial_location"; public static final String TRANS_SPLICING = "trans_splicing"; public static final String RIBOSOMAL_SLIPPAGE = "ribosomal_slippage"; public static final String METAGENOME_SOURCE_QUALIFIER_NAME = "metagenome_source"; public static final String SUBMITTER_SEQID_QUALIFIER_NAME = "submitter_seqid"; public static final String SEROVAR_QUALIFIER_NAME = "serovar"; public static final String SEROTYPE_QUALIFIER_NAME = "serotype"; public static final String CIRCULAR_RNA_QUALIFIER_NAME = "circular_RNA"; public static final String SUB_SPECIES = "sub_species"; private static final HashSet<String> QUOTED_QUALS = new HashSet<String>(); private static final HashMap<String, Integer> ORDER_QUALS = new HashMap<String, Integer>(); private static final Integer DEFAULT_ORDER_QUALS = Integer.MAX_VALUE; static { DataManager dataManager = new CachedFileDataManager(); CheckFileManager tsvFileManager = new CheckFileManager(); DataSet dataSet = dataManager.getDataSet( tsvFileManager.filePath( GlobalDataSetFile.FEATURE_QUALIFIER_VALUES.getFileName(), false)); if (dataSet != null) { for (DataRow row : dataSet.getRows()) { String name = row.getString(0); String order = row.getString(5); String quoted = row.getString(3); if (quoted.equals("Y")) { QUOTED_QUALS.add(name); } ORDER_QUALS.put(name, Integer.parseInt(order)); } } } private Origin origin; private String id; private String name; private String value; protected Qualifier(String name, String value) { this.name = name; this.value = value; } protected Qualifier(String name) { this(name, null); } public Origin getOrigin() { return origin; } public void setOrigin(Origin origin) { this.origin = origin; } public boolean isValueQuoted() { return QUOTED_QUALS.contains(name); } public String getId() { return id; } public void setId(Object id) { if (id != null) { this.id = id.toString(); } else { this.id = null; } } public String getName() { return name; } public String getValue() { return this.value; } public String getValueRemoveTabs() { String returnedValue = null; if (this.value != null) { returnedValue = this.value.replaceAll("\\r\\n|\\r|\\n", ""); returnedValue = returnedValue.replaceAll("\\t", " "); } return returnedValue; } public boolean isValue() { if (value == null || value.trim().isEmpty()) return false; else return true; } public void setValue(String value) { this.value = value; } public void setName(String name) { this.name = name; } protected void throwValueException() throws ValidationException { throw new ValidationException( ValidationMessage.error("Qualifier", getName(), getValue()).append(origin)); } @Override public int hashCode() { final HashCodeBuilder builder = new HashCodeBuilder(); builder.append(this.id); builder.append(this.name); builder.append(this.value); return builder.toHashCode(); } @Override public boolean equals(Object obj) { if (obj != null && obj instanceof Qualifier) { final Qualifier other = (Qualifier) obj; final EqualsBuilder builder = new EqualsBuilder(); builder.append(this.id, other.id); builder.append(this.name, other.name); builder.append(this.value, other.value); return builder.isEquals(); } else { return false; } } public int compareTo(Qualifier o) { // The natural order of the qualifiers is the order in // which they should appear in the flat file. if (this.equals(o)) { return 0; } final CompareToBuilder builder = new CompareToBuilder(); Integer thisOrder = ORDER_QUALS.get(this.name); if (thisOrder == null) { thisOrder = DEFAULT_ORDER_QUALS; } Integer otherOrder = ORDER_QUALS.get(o.name); if (otherOrder == null) { otherOrder = DEFAULT_ORDER_QUALS; } builder.append(thisOrder, otherOrder); return builder.toComparison(); } @Override public String toString() { final ToStringBuilder builder = new ToStringBuilder(this); builder.append("id", id); builder.append("name", name); builder.append("value", value); return builder.toString(); } }
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/api/entry/qualifier/Qualifier.java
Java
apache-2.0
10,268
package org.springframework.samples.petportal.portlet; import java.util.Properties; import javax.portlet.ActionResponse; import org.springframework.samples.petportal.domain.PetSite; import org.springframework.samples.petportal.validation.PetSiteValidator; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; /** * This Controller simply populates the model with the current map * of 'petSites' and then forwards to the view from which a user can * add to or delete from the sites. The HandlerMapping maps to this * Controller when in EDIT mode while no valid 'action' parameter * is set. See 'WEB-INF/context/petsites-portlet.xml' for details. * * @author Mark Fisher * @author Juergen Hoeller */ @Controller @RequestMapping("EDIT") @SessionAttributes("site") public class PetSitesEditController { private Properties petSites; public void setPetSites(Properties petSites) { this.petSites = petSites; } @ModelAttribute("petSites") public Properties getPetSites() { return this.petSites; } @RequestMapping // default (action=list) public String showPetSites() { return "petSitesEdit"; } @RequestMapping(params = "action=add") // render phase public String showSiteForm(ModelMap model) { // Used for the initial form as well as for redisplaying with errors. if (!model.containsKey("site")) { model.addAttribute("site", new PetSite()); } return "petSitesAdd"; } @RequestMapping(params = "action=add") // action phase public void populateSite( @ModelAttribute("site") PetSite petSite, BindingResult result, SessionStatus status, ActionResponse response) { new PetSiteValidator().validate(petSite, result); if (!result.hasErrors()) { this.petSites.put(petSite.getName(), petSite.getUrl()); status.setComplete(); response.setRenderParameter("action", "list"); } } @RequestMapping(params = "action=delete") public void removeSite(@RequestParam("site") String site, ActionResponse response) { this.petSites.remove(site); response.setRenderParameter("action", "list"); } }
mattxia/spring-2.5-analysis
samples/petportal/src/org/springframework/samples/petportal/portlet/PetSitesEditController.java
Java
apache-2.0
2,451
package edu.pitt.apollo.apollotranslator.setters; import edu.pitt.apollo.apollotranslator.ApolloTranslationEngine; import edu.pitt.apollo.apollotranslator.exception.ApolloSetterException; import edu.pitt.apollo.apollotranslator.types.translator.SetterReturnObject; import edu.pitt.apollo.types.v4_0_2.ConditionalProbabilityDistribution; import edu.pitt.apollo.types.v4_0_2.DrugTreatmentEfficacyForSimulatorConfiguration; import java.util.ArrayList; import java.util.List; /** * * Author: Nick Millett * Email: [email protected] * Date: Aug 19, 2014 * Time: 10:13:06 AM * Class: DrugTreatmentEfficacyForSimulatorConfigurationSetter */ public class DrugTreatmentEfficacyForSimulatorConfigurationSetter extends TreatmentEfficacySetter<DrugTreatmentEfficacyForSimulatorConfiguration> { private static final String AVERAGE_DRUG_EFFICACY = "averageDrugEfficacy"; private static final String DRUG_EFFICACY_CONDITIONED_ON_AGE_RANGE = "drugEfficacyConditionedOnAgeRange"; private static final String DRUG_EFFICACY_CONDITIONED_ON_DISEASE_OUTCOME = "drugEfficacyConditionedOnCurrentDiseaseOutcome"; public DrugTreatmentEfficacyForSimulatorConfigurationSetter() { } public DrugTreatmentEfficacyForSimulatorConfigurationSetter(String type, String section, ApolloTranslationEngine apolloTranslationEngine) { super(type, section, apolloTranslationEngine); } private List<SetterReturnObject> setAverageDrugTreatmentEfficacy(double efficacy) throws ApolloSetterException { return setValue(AVERAGE_DRUG_EFFICACY, Double.toString(efficacy), section); } public List<SetterReturnObject> setDrugTreatmentEfficacyByAgeRange(ConditionalProbabilityDistribution dist) throws ApolloSetterException { ConditionalProbabilityDistributionSetter setter = new ConditionalProbabilityDistributionSetter(apolloTranslationEngine, type + "." + DRUG_EFFICACY_CONDITIONED_ON_AGE_RANGE, section); return setter.set(dist); } public List<SetterReturnObject> setDrugTreatmentEfficacyConditionedOnOcurrentDiseaseOutcome(ConditionalProbabilityDistribution dist) throws ApolloSetterException { ConditionalProbabilityDistributionSetter setter = new ConditionalProbabilityDistributionSetter(apolloTranslationEngine, type + "." + DRUG_EFFICACY_CONDITIONED_ON_DISEASE_OUTCOME, section); return setter.set(dist); } @Override public List<SetterReturnObject> set(DrugTreatmentEfficacyForSimulatorConfiguration efficacy) throws ApolloSetterException { List<SetterReturnObject> result = new ArrayList<SetterReturnObject>(); result.addAll(setTreatmentEfficacy(efficacy)); result.addAll(setAverageDrugTreatmentEfficacy(efficacy.getAverageDrugEfficacy())); if (efficacy.getDrugEfficacyConditionedOnAgeRange() != null) { result.addAll(setDrugTreatmentEfficacyByAgeRange(efficacy.getDrugEfficacyConditionedOnAgeRange())); } if (efficacy.getDrugEfficaciesConditionedOnCurrentDiseaseOutcome() != null) { result.addAll(setDrugTreatmentEfficacyConditionedOnOcurrentDiseaseOutcome(efficacy.getDrugEfficaciesConditionedOnCurrentDiseaseOutcome())); } return result; } }
ApolloDev/apollo
apollo-translator/src/main/java/edu/pitt/apollo/apollotranslator/setters/DrugTreatmentEfficacyForSimulatorConfigurationSetter.java
Java
apache-2.0
3,114
package core.framework.internal.async; import core.framework.internal.log.ActionLog; import core.framework.internal.log.LogManager; import core.framework.internal.log.Trace; import core.framework.util.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.concurrent.Callable; /** * @author neo */ public class ExecutorTask<T> implements Callable<T> { private static final Logger LOGGER = LoggerFactory.getLogger(ExecutorTask.class); final String actionId; private final String action; private final LogManager logManager; private final Callable<T> task; private final Instant startTime; private final long maxProcessTimeInNano; private String rootAction; private String refId; private String correlationId; private Trace trace; ExecutorTask(Callable<T> task, LogManager logManager, TaskContext context) { this.task = task; this.logManager = logManager; actionId = context.actionId; action = context.action; startTime = context.startTime; maxProcessTimeInNano = context.maxProcessTimeInNano; ActionLog parentActionLog = context.parentActionLog; if (parentActionLog != null) { // only keep info needed by call(), so parentActionLog can be GCed sooner List<String> parentActionContext = parentActionLog.context.get("root_action"); rootAction = parentActionContext != null ? parentActionContext.get(0) : parentActionLog.action; correlationId = parentActionLog.correlationId(); refId = parentActionLog.id; trace = parentActionLog.trace; } } @Override public T call() throws Exception { try { ActionLog actionLog = logManager.begin("=== task execution begin ===", actionId); actionLog.action(action()); actionLog.maxProcessTime(maxProcessTimeInNano); // here it doesn't log task class, is due to task usually is lambda or method reference, it's expensive to inspect, refer to ControllerInspector if (rootAction != null) { // if rootAction != null, then all parent info are available actionLog.context("root_action", rootAction); LOGGER.debug("correlationId={}", correlationId); actionLog.correlationIds = List.of(correlationId); LOGGER.debug("refId={}", refId); actionLog.refIds = List.of(refId); if (trace == Trace.CASCADE) actionLog.trace = Trace.CASCADE; } LOGGER.debug("taskClass={}", CallableTask.taskClass(task).getName()); Duration delay = Duration.between(startTime, actionLog.date); LOGGER.debug("taskDelay={}", delay); actionLog.stats.put("task_delay", (double) delay.toNanos()); actionLog.context.put("thread", List.of(Thread.currentThread().getName())); return task.call(); } catch (Throwable e) { logManager.logError(e); throw new TaskException(Strings.format("task failed, action={}, id={}, error={}", action, actionId, e.getMessage()), e); } finally { logManager.end("=== task execution end ==="); } } String action() { return rootAction == null ? "task:" + action : rootAction + ":task:" + action; } // used to print all canceled tasks during shutdown @Override public String toString() { return action() + ":" + actionId; } static class TaskContext { String actionId; String action; Instant startTime; ActionLog parentActionLog; long maxProcessTimeInNano; } }
neowu/core-ng-project
core-ng/src/main/java/core/framework/internal/async/ExecutorTask.java
Java
apache-2.0
3,779
package functionality; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; public class Transmitter implements ITransmitter { private BufferedReader in; private PrintWriter out; @Override public void connected(BufferedReader in, PrintWriter out){ this.in = in; this.out = out; try { System.out.println(in.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* (non-Javadoc) * @see functionality.ITransmitter#RM20(java.lang.String, java.lang.String, java.lang.String) */ @Override public String RM20(String txt1, String txt2, String txt3) throws IOException{ out.println("RM20 8" + " \"" + txt1 + "\" \"" + txt2 + "\" \"" + txt3 + "\"" ); String reply = in.readLine(); String error = "ES"; String cancel = "q"; if (reply.equalsIgnoreCase("RM20 B")){ String input = in.readLine(); if (input.equalsIgnoreCase("RM20 C")){ return cancel; } return input.substring(8,(input.length()-1)); // Skal muligvis være 6 } else { return error; } } /* (non-Javadoc) * @see functionality.ITransmitter#P111(java.lang.String) */ @Override public boolean P111(String txt) throws IOException{ out.println("P111 \"" + txt + "\""); if (in.readLine().equalsIgnoreCase("P111 A")){ return true; } else { return false; } } /* (non-Javadoc) * @see functionality.ITransmitter#S() */ @Override public String S() throws IOException{ out.println("S"); String reply = in.readLine(); return reply.substring(9,(reply.length()-3)); } /* (non-Javadoc) * @see functionality.ITransmitter#T() */ @Override public String T() throws IOException{ out.println("T"); String reply = in.readLine(); return reply.substring(9,(reply.length()-3)); } /* (non-Javadoc) * @see functionality.ITransmitter#D() */ @Override public boolean D(String txt) throws IOException{ boolean output = false; if (txt.length() < 8 ){ out.println("D \"" + txt + "\""); if (in.readLine().equalsIgnoreCase("D A")){ output = true; } } else{ output = false; } return output; } /* (non-Javadoc) * @see functionality.ITransmitter#DW() */ @Override public boolean DW() throws IOException{ out.println("DW"); if (in.readLine().equalsIgnoreCase("DW A")){ return true; } else { return false; } } @Override public boolean startST(boolean status) throws IOException{ if (status) out.println("ST 1"); else out.println("ST 0"); if (in.readLine().equalsIgnoreCase("ST A")) return true; else return false; } @Override public String listenST() throws IOException{ out.println("ST"); in.readLine(); String reply = in.readLine(); return reply.substring(9,(reply.length()-3)); } }
SoftTech2018/06_del2
06_del2/WCU/functionality/Transmitter.java
Java
apache-2.0
2,804
package com.diag.deringer.androidthingsperipheralio; // Copyright 2017 by the Digital Aggregates Corporation, Arvada Colorado USA. // Licensed under the terms of the Apache License version 2.0. // https://codelabs.developers.google.com/codelabs/androidthings-peripherals/#0 // mailto:[email protected] // https://github.com/coverclock/com-diag-deringer import java.io.IOException; import android.app.Activity; import android.os.Bundle; import com.google.android.things.pio.PeripheralManagerService; import com.google.android.things.pio.Gpio; import com.google.android.things.pio.GpioCallback; import android.util.Log; public class HomeActivity extends Activity { private static final String TAG = "HomeActivity"; private static final String BUTTON_A = "BCM21"; private static final String BUTTON_B = "BCM20"; private static final String BUTTON_C = "BCM16"; private static final String LED_RED = "BCM6"; // GPIO connection to button input. private Gpio mButtonGpio; // GPIO connection to LED output. private Gpio mLedGpio; private GpioCallback mCallback = new GpioCallback() { @Override public boolean onGpioEdge(Gpio gpio) { try { boolean buttonValue = gpio.getValue(); Log.i(TAG, "GPIO changed, button " + buttonValue); mLedGpio.setValue(buttonValue); } catch (IOException e) { Log.w(TAG, "Error reading GPIO"); } // Return true to keep callback active. return true; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PeripheralManagerService service = new PeripheralManagerService(); Log.d(TAG, "Available GPIO: " + service.getGpioList()); try { // Create GPIO connections. mButtonGpio = service.openGpio(BUTTON_A); mLedGpio = service.openGpio(LED_RED); // Configure as an input, trigger events on every change. mButtonGpio.setDirection(Gpio.DIRECTION_IN); mButtonGpio.setEdgeTriggerType(Gpio.EDGE_BOTH); // Value is true with the pin is LOW. mButtonGpio.setActiveType(Gpio.ACTIVE_LOW); // Configure as an output. mLedGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW); // Register the event callback. mButtonGpio.registerGpioCallback(mCallback); } catch (IOException e) { Log.w(TAG, "Error opening GPIO", e); } } @Override protected void onDestroy() { super.onDestroy(); // Close the button. if (mButtonGpio != null) { mButtonGpio.unregisterGpioCallback(mCallback); try { mButtonGpio.close(); } catch (IOException e) { Log.w(TAG,"Error closing GPIO", e); } } //Close the LED. if (mLedGpio != null) { try { mLedGpio.close(); } catch (IOException e) { Log.e(TAG,"Error closing GPIO", e); } } } }
coverclock/com-diag-deringer
AndroidThingsPeripheralIO/app/src/main/java/com/diag/deringer/androidthingsperipheralio/HomeActivity.java
Java
apache-2.0
3,192
package com.example.coolweather2.service; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.os.IBinder; import android.os.SystemClock; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.coolweather2.gson.Weather; import com.example.coolweather2.util.HttpUtil; import com.example.coolweather2.util.Utility; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by Administrator on 2016/12/17. */ public class AutoUpdateService extends Service { private static final String TAG = "AutoUpdateService"; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate: 我被执行了!!!"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand: 我也执行了!!!"); updateWeather(); updateBingPic(); AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE); int time = 8 * 60 * 60 * 1000; // 8小时的毫秒数 // SystemClock.elapsedRealtime为系统开机到现在所走的毫秒数 // System.currentTimeMillis为1970/1/1零点到现在所走的毫秒数 long triggerAtTime = SystemClock.elapsedRealtime() + time; Intent i = new Intent(this,AutoUpdateService.class); PendingIntent pi = PendingIntent.getService(this,0,i,0); manager.cancel(pi); // 这句话有什么用? // 之前是用的AlarmManager.ELAPSED_REALTIME导致不能后台更新数据 manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi); return super.onStartCommand(intent, flags, startId); } /** * 更新天气信息 */ private void updateWeather() { Log.d( TAG,"AutoUpdateService中的updateWeather执行了!!!"); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String weatherString = sp.getString("weather_response",null); if(weatherString != null){ Weather weather = Utility.handleWeatherResponse(weatherString); String weatherId = weather.basic.weatherId; String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=bc0418b57b2d4918819d3974ac1285d9"; HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { String responseText = response.body().string(); Weather weather = Utility.handleWeatherResponse(responseText); if( weather != null && "ok".equals(weather.status) ){ SharedPreferences.Editor editor = PreferenceManager .getDefaultSharedPreferences(AutoUpdateService.this).edit(); editor.putString("weather_response",responseText); editor.apply(); } } @Override public void onFailure(Call call, IOException e) { } }); } } /** * 更新必应每日一图 */ private void updateBingPic() { Log.d( TAG,"AutoUpdateService中的updateBingPic执行了!!!"); String requestBingPic = "http://guolin.tech/api/bing_pic"; HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { final String imgUrl = response.body().string(); SharedPreferences.Editor editor = PreferenceManager .getDefaultSharedPreferences(AutoUpdateService.this) .edit(); editor.putString("bing_img_url",imgUrl); editor.apply(); } @Override public void onFailure(Call call, IOException e) { } }); } }
602497556/CoolWeather2
app/src/main/java/com/example/coolweather2/service/AutoUpdateService.java
Java
apache-2.0
4,377
package org.pac4j.async.vertx.core; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.scribejava.core.model.OAuth1RequestToken; import com.github.scribejava.core.model.Token; import com.nimbusds.oauth2.sdk.Scope; import com.nimbusds.oauth2.sdk.Scope.Value.Requirement; import com.nimbusds.oauth2.sdk.token.AccessTokenType; import com.nimbusds.oauth2.sdk.token.BearerAccessToken; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import org.pac4j.core.exception.TechnicalException; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * <p>Default eventbus object converter</p> * <p>The serialization strategy is:</p> * <ul> * <li>For primitive types (String, Number and Boolean), return as is</li> * <li>For arrays, convert to JsonArray</li> * <li>Otherwise, convert to a JsonObject with the class name in the "class" attribute and the serialized form with Jackson in the "value" attribute. * The (de)serialization Jackson process can be customized using the <code>addMixIn(target, mixinSource)</code> method</li> * </ul> * * @author Michael Remond * @since 1.1.0 * */ public class DefaultJsonConverter implements JsonConverter { private final ObjectMapper mapper = new ObjectMapper(); private static final DefaultJsonConverter INSTANCE = new DefaultJsonConverter(); public static JsonConverter getInstance() { return INSTANCE; } public DefaultJsonConverter() { mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); mapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE); mapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE); mapper.addMixIn(OAuth1RequestToken.class, OAuth1RequestTokenMixin.class) .addMixIn(BearerAccessToken.class, BearerAccessTokenMixin.class) .addMixIn(Scope.Value.class, ValueMixin.class) .addMixIn(Token.class, TokenMixin.class); } @Override public Object encodeObject(Object value) { if (value == null) { return null; } else if (isPrimitiveType(value)) { return value; } else if (value instanceof Object[]) { Object[] src = ((Object[]) value); List<Object> list = new ArrayList<>(src.length); fillEncodedList(src, list); return new JsonArray(list); } else { try { return new JsonObject().put("class", value.getClass().getName()).put("value", new JsonObject(encode(value))); } catch (Exception e) { throw new TechnicalException("Error while encoding object", e); } } } private void fillEncodedList(Object[] src, List<Object> list) { for (Object object : src) { list.add(encodeObject(object)); } } @Override public Object decodeObject(Object value) { if (value == null) { return null; } else if (isPrimitiveType(value)) { return value; } else if (value instanceof JsonArray) { JsonArray src = (JsonArray) value; List<Object> list = new ArrayList<>(src.size()); fillDecodedList(src, list); return list.toArray(); } else if (value instanceof JsonObject) { JsonObject src = (JsonObject) value; return decode(src); } return null; } private Object decode(JsonObject src) { try { return decode(src.getJsonObject("value").encode(), Class.forName(src.getString("class"))); } catch (Exception e) { throw new TechnicalException("Error while decoding object", e); } } private void fillDecodedList(JsonArray src, List<Object> list) { for (Object object : src) { list.add(decodeObject(object)); } } private boolean isPrimitiveType(Object value) { return value instanceof String || value instanceof Number || value instanceof Boolean; } private String encode(Object value) throws JsonGenerationException, JsonMappingException, IOException { return mapper.writeValueAsString(value); } @SuppressWarnings("unchecked") private <T> T decode(String string, Class<?> clazz) throws JsonParseException, JsonMappingException, IOException { return (T) mapper.readValue(string, clazz); } public static class BearerAccessTokenMixin { @JsonIgnore private AccessTokenType type; @JsonCreator public BearerAccessTokenMixin(@JsonProperty("value") String value, @JsonProperty("lifetime") long lifetime, @JsonProperty("scope") Scope scope) { } } public static class ValueMixin { @JsonCreator public ValueMixin(@JsonProperty("value") String value, @JsonProperty("requirement") Requirement requirement) { } } public static class TokenMixin { @JsonCreator public TokenMixin(@JsonProperty("token") String token, @JsonProperty("secret") String secret, @JsonProperty("rawResponse") String rawResponse) { } } public static class OAuth1RequestTokenMixin { @JsonCreator public OAuth1RequestTokenMixin(@JsonProperty("token") String token, @JsonProperty("tokenSecret") String tokenSecret, @JsonProperty("oauthCallbackConfirmed") boolean oauthCallbackConfirmed, @JsonProperty("rawResponse") String RawResponse) { } } }
millross/pac4j-async
vertx-pac4j-async-demo/src/main/java/org/pac4j/async/vertx/core/DefaultJsonConverter.java
Java
apache-2.0
5,941
/** * Copyright (C) 2012 Ness Computing, 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.nesscomputing.httpclient; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import java.util.Map; /** Response from the remote server. */ public interface HttpClientResponse { /** * Returns the status code for the request. * * @return the status code, use the related {@link HttpServletRequest} constants */ int getStatusCode(); /** * Returns the status text for the request. * * @return the status text */ String getStatusText(); /** * Returns an input stream for the response body. * * @return the input stream * @throws IOException on error */ InputStream getResponseBodyAsStream() throws IOException; /** @return the URI of the request. */ URI getUri(); /** @return Content type of the response. */ String getContentType(); /** * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no * content). */ @CheckForNull Long getContentLength(); /** @return Content charset if present in the header. Can be null. */ @CheckForNull String getCharset(); /** * @param name the header name * @return The named header from the response. Response can be null. */ @CheckForNull String getHeader(String name); /** * @param name the header name * @return all values for the given header. Response can be null. */ @CheckForNull List<String> getHeaders(String name); /** @return Map of header name -> list of values for each header name */ @Nonnull public Map<String, List<String>> getAllHeaders(); /** @return true if the response redirects to another object. */ boolean isRedirected(); }
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java
Java
apache-2.0
2,390
/* * 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.flink.runtime.io.network; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import org.apache.flink.core.io.IOReadableWritable; import org.apache.flink.core.memory.DataInputView; import org.apache.flink.core.memory.DataOutputView; /** * Objects of this class uniquely identify a connection to a remote {@link org.apache.flink.runtime.taskmanager.TaskManager}. */ public final class RemoteReceiver implements IOReadableWritable { /** * The address of the connection to the remote TaskManager. */ private InetSocketAddress connectionAddress; /** * The index of the connection to the remote TaskManager. */ private int connectionIndex; /** * Constructs a new remote receiver object. * * @param connectionAddress * the address of the connection to the remote TaskManager * @param connectionIndex * the index of the connection to the remote TaskManager */ public RemoteReceiver(final InetSocketAddress connectionAddress, final int connectionIndex) { if (connectionAddress == null) { throw new IllegalArgumentException("Argument connectionAddress must not be null"); } if (connectionIndex < 0) { throw new IllegalArgumentException("Argument connectionIndex must be a non-negative integer number"); } this.connectionAddress = connectionAddress; this.connectionIndex = connectionIndex; } /** * Default constructor for serialization/deserialization. */ public RemoteReceiver() { this.connectionAddress = null; this.connectionIndex = -1; } /** * Returns the address of the connection to the remote TaskManager. * * @return the address of the connection to the remote TaskManager */ public InetSocketAddress getConnectionAddress() { return this.connectionAddress; } /** * Returns the index of the connection to the remote TaskManager. * * @return the index of the connection to the remote TaskManager */ public int getConnectionIndex() { return this.connectionIndex; } @Override public int hashCode() { return this.connectionAddress.hashCode() + (31 * this.connectionIndex); } @Override public boolean equals(final Object obj) { if (!(obj instanceof RemoteReceiver)) { return false; } final RemoteReceiver rr = (RemoteReceiver) obj; if (!this.connectionAddress.equals(rr.connectionAddress)) { return false; } if (this.connectionIndex != rr.connectionIndex) { return false; } return true; } @Override public void write(final DataOutputView out) throws IOException { final InetAddress ia = this.connectionAddress.getAddress(); out.writeInt(ia.getAddress().length); out.write(ia.getAddress()); out.writeInt(this.connectionAddress.getPort()); out.writeInt(this.connectionIndex); } @Override public void read(final DataInputView in) throws IOException { final int addr_length = in.readInt(); final byte[] address = new byte[addr_length]; in.readFully(address); InetAddress ia = InetAddress.getByAddress(address); int port = in.readInt(); this.connectionAddress = new InetSocketAddress(ia, port); this.connectionIndex = in.readInt(); } @Override public String toString() { return this.connectionAddress + " (" + this.connectionIndex + ")"; } }
citlab/vs.msc.ws14
flink-0-7-custom/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/RemoteReceiver.java
Java
apache-2.0
4,094
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.interestrate.capletstripping; import com.opengamma.analytics.financial.model.volatility.VolatilityTermStructure; import com.opengamma.analytics.math.matrix.DoubleMatrix1D; import com.opengamma.util.ArgumentChecker; /** * Holds the results of performing caplet stripping on a set of caps (on the same Ibor index) <b>with the same strike</b>. */ public class CapletStrippingSingleStrikeResult { private final VolatilityTermStructure _volatilityCurve; private final double _chiSq; private final DoubleMatrix1D _fitParameters; private final DoubleMatrix1D _modelPrices; /** * * @param chiSq * The chi-square of the fit. This will be zero (to the stopping tolerance) for root finding based strippers * @param fitParms * The fit parameters from running the stripping routine. The model prices and volatility curve are derived from the fitted parameters via the model * used in the stripping routine. * @param volCurve * The volatility curve for the caplets that <i>best</i> reproduces the model cap prices * @param modelPrices * The cap prices produced by the stripping - these will be identical (to within tolerance) to the market prices for root finding based routines, but * could differ for least-squares */ public CapletStrippingSingleStrikeResult(final double chiSq, final DoubleMatrix1D fitParms, final VolatilityTermStructure volCurve, final DoubleMatrix1D modelPrices) { ArgumentChecker.isTrue(chiSq >= 0, "Negative chiSq"); ArgumentChecker.notNull(fitParms, "null fit parameters"); ArgumentChecker.notNull(volCurve, "null vol curve"); ArgumentChecker.notNull(modelPrices, "null model prices"); _chiSq = chiSq; _fitParameters = fitParms; _modelPrices = modelPrices; _volatilityCurve = volCurve; } /** * Gets the volatilityCurve. * * @return the volatilityCurve */ public VolatilityTermStructure getVolatilityCurve() { return _volatilityCurve; } /** * Gets the chiSq. * * @return the chiSq */ public double getChiSq() { return _chiSq; } /** * Gets the fitParameters. * * @return the fitParameters */ public DoubleMatrix1D getFitParameters() { return _fitParameters; } /** * Gets the modelValues. * * @return the modelValues */ public DoubleMatrix1D getModelValues() { return _modelPrices; } }
McLeodMoores/starling
projects/analytics/src/main/java/com/opengamma/analytics/financial/interestrate/capletstripping/CapletStrippingSingleStrikeResult.java
Java
apache-2.0
2,616
/* * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. * * 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 javax.crypto; import java.security.Key; /** * * * @author Diego Raúl Mercado * @version 1.2 * @ar.org.fitc.spec_ref */ public interface SecretKey extends Key { /** @ar.org.fitc.spec_ref */ public static final long serialVersionUID = -4795878709595146952l; }
freeVM/freeVM
enhanced/archive/classlib/modules/crypto2/src/javax/crypto/SecretKey.java
Java
apache-2.0
942
/* * Copyright 2007 the project originators. * * 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.teletalk.jserver.queue.command; import com.teletalk.jserver.queue.RemoteQueueSystem; import com.teletalk.jserver.queue.legacy.DefaultQueueSystemEndPoint; import com.teletalk.jserver.queue.legacy.DefaultQueueSystemEndPointProxy; /** * Command class used for DefaultQueueSystemEndPoint disconnection.<br> * <br> * Note: This class is part of the legacy queue system collaboration implementation (DefaultQueueSystemCollaborationManager). * * @author Tobias Löfstrand * * @since Beta 1 */ public final class DefaultDisconnectCommand extends Command { /** The serial version id of this class. */ static final long serialVersionUID = 3102587782464108038L; public void execute(RemoteQueueSystem remoteQueueSystem) { DefaultQueueSystemEndPoint endPoint = ((DefaultQueueSystemEndPointProxy)remoteQueueSystem).getEndPoint(); if(endPoint != null) endPoint.disconnectionCommandReceived(); } /** * Gets a string representation of this DefaultQueueSystemEndPoint. * * @return a string representation of this DefaultQueueSystemEndPoint. */ public String toString() { return this.getClass().getName(); } }
tolo/JServer
src/java/com/teletalk/jserver/queue/command/DefaultDisconnectCommand.java
Java
apache-2.0
1,834