repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
chdrdz/coolweather | app/src/main/java/com/random/coolweather/gson/Now.java | 354 | package com.random.coolweather.gson;
import com.google.gson.annotations.SerializedName;
/**
* Created by random on 17/2/17.
*/
public class Now {
@SerializedName("tmp")
public String temperature;
@SerializedName("cond")
public More more;
public class More {
@SerializedName("txt")
public String info;
}
}
| apache-2.0 |
bearsoft5/Flamingo | src/flamingo/reflect/MemberUtils.java | 3129 | /*
* +----------------------------------------------------------------------+
* | Flamingo Library |
* +----------------------------------------------------------------------+
* | Copyright (c) 2017 Flamingo Group |
* +----------------------------------------------------------------------+
* | Licensed under the Apache License, Version 2.0 (the "License"); |
* | you may not use this file except in compliance with the License. |
* | You may obtain a copy of the License at |
* | |
* | http://www.apache.org/licenses/LICENSE-2.0 |
* | |
* | Unless required by applicable law or agreed to in writing, software |
* | distributed under the License is distributed on an "AS IS" BASIS, |
* | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
* | impled. See the License for the specific language governing |
* | permissions and limitations under the License. |
* +----------------------------------------------------------------------+
* | Authors: bearsoft <bearsoft5@hotmail.com> |
* +----------------------------------------------------------------------+
*/
package flamingo.reflect;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
public class MemberUtils {
/**
* This method set (AccessibleObject) like accessible.
* @param ao - the accessible object.
*/
public static void setAccessibleWorkaround(final AccessibleObject ao) {
// Check if the (ao) equals null, or the (ao) is accessible.
if (ao == null || ao.isAccessible()) return;
// Make the (AccessibleObject) like accessible.
ao.setAccessible(true);
}
/**
* <pre>This method set (AccessibleObject) like acessible,
* But this method have a (IMethodInvoker) this parameter in
* Method setAccesibleWorkaroundInvoke, the accessible object is accessible,
* And the (IMethodInvoker) invoke the method, and after the method is finished,
* The accessible object is not accessible.</pre>
* @param ao - the accessible object.
* @param methodInvoker - the method invoker.
*/
public static void setAccessibleWorkaroundInvoke(final AccessibleObject ao, IMethodInvoker methodInvoker) {
// Check if the (ao) equals null, or the (ao) is accessible.
if (ao == null || ao.isAccessible()) return;
// Make the (ao) like accessible.
ao.setAccessible(true);
// Invoke the method of (IMethodInvoker).
methodInvoker.invoke();
ao.setAccessible(false);
}
/**
* This method check if the {@code Member} is accessible.
* @param m - the member.
* @return - Returns (true) if the member is accessible, otherwise return (false).
*/
public static boolean isAccessible(final Member m) {
return m != null && Modifier.isPublic(m.getModifiers()) && !m.isSynthetic();
}
}
| apache-2.0 |
flexiblepower/fpai-core | flexiblepower.ui/src/org/flexiblepower/runtime/ui/server/HttpUtils.java | 4332 | package org.flexiblepower.runtime.ui.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class HttpUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
private static final Map<String, String> CONTEINT_TYPES = new HashMap<String, String>();
static {
add("text/html", "html", "htm");
add("text/css", "css");
add("text/xml", "xml");
add("application/javascript", "js");
add("image/png", "png");
add("image/jpeg", "jpg", "jpeg");
add("image/gif", "gif");
add("image/svg", "svg");
}
private HttpUtils() {
}
private static void add(String contentType, String... extensions) {
logger.trace("Entering add, contentType = {}, extensions = {}", contentType, extensions);
for (String ext : extensions) {
CONTEINT_TYPES.put(ext, contentType);
}
logger.trace("Leaving add");
}
public static String getContentType(String filename) {
logger.trace("Entering getContentType, filename = {}", filename);
int ix = filename.lastIndexOf('.');
if (ix > 0) {
String ext = filename.substring(ix + 1).toLowerCase();
if (CONTEINT_TYPES.containsKey(ext)) {
return CONTEINT_TYPES.get(ext);
}
}
String result = URLConnection.guessContentTypeFromName(filename);
logger.trace("Leaving getContentType, result = {}", result);
return result;
}
public static void setNoCaching(HttpServletResponse resp) {
logger.trace("Entering setNoCaching, resp = {}", resp.getClass());
resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
resp.setHeader("Pragma", "no-cache"); // HTTP 1.0
resp.setDateHeader("Expires", 0);
logger.trace("Leaving setNoCaching");
}
public static void
writeFile(URL url, long expirationTime, String name, HttpServletResponse resp, Locale locale) throws IOException {
logger.trace("Entering writeFile, url = {}, expirationTime = {}, name = {}, locale = {}",
url,
expirationTime,
name,
locale);
if (url == null) {
resp.sendError(404);
} else {
if (expirationTime <= 0) {
setNoCaching(resp);
} else {
resp.setDateHeader("Expires", System.currentTimeMillis() + expirationTime);
}
resp.setContentType(getContentType(name));
if (name.endsWith(".html") || name.endsWith(".css") || name.endsWith(".js")) {
resp.setCharacterEncoding("UTF-8");
}
write(url.openStream(), resp.getOutputStream());
}
logger.trace("Leaving writeFile");
}
public static void write(InputStream input, OutputStream output) throws IOException {
logger.trace("Entering write, input = {}, output = {}", input, output);
byte[] buffer = new byte[4096];
int read = 0;
try {
while ((read = input.read(buffer)) >= 0) {
output.write(buffer, 0, read);
}
} finally {
input.close();
}
logger.trace("Leaving write", input, output);
}
public static String readData(InputStream input) throws IOException {
logger.trace("Entering readData, input = {}", input);
try {
Reader reader = new InputStreamReader(input);
StringBuilder sb = new StringBuilder();
char[] buffer = new char[1024];
int read = 0;
while ((read = reader.read(buffer)) >= 0) {
sb.append(buffer, 0, read);
}
logger.trace("Levaing readData, result = (String of {} characters)", sb.length());
return sb.toString();
} finally {
input.close();
}
}
}
| apache-2.0 |
arthurpaulino/PlantioCaianinho | app/src/main/java/br/org/udv/plantiocaianinho/adapter/ChacronasResultAdapter.java | 1294 | package br.org.udv.plantiocaianinho.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import br.org.udv.plantiocaianinho.R;
import br.org.udv.plantiocaianinho.statistics.ChacronaStatisticsResult;
import br.org.udv.plantiocaianinho.viewholder.ChacronasResultViewHolder;
public class ChacronasResultAdapter extends RecyclerView.Adapter<ChacronasResultViewHolder> {
private ArrayList<ChacronaStatisticsResult> results;
private LayoutInflater inflater;
public ChacronasResultAdapter(Context context, ArrayList<ChacronaStatisticsResult> results) {
inflater = LayoutInflater.from(context);
this.results = results;
}
@Override
public ChacronasResultViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.item_chacrona_result, parent, false);
return new ChacronasResultViewHolder(view);
}
@Override
public void onBindViewHolder(ChacronasResultViewHolder holder, int position) {
holder.bindResult(results.get(position));
}
@Override
public int getItemCount() {
return results.size();
}
}
| apache-2.0 |
AVnetWS/Hentoid | app/src/main/java/me/devsaki/hentoid/workers/data/DuplicateData.java | 2498 | package me.devsaki.hentoid.workers.data;
import androidx.work.Data;
import javax.annotation.Nonnull;
/**
* Helper class to transfer data from any Activity to {@link me.devsaki.hentoid.workers.DuplicateDetectorWorker}
* through a Data object
* <p>
* Use Builder class to set data; use Parser class to get data
*/
public class DuplicateData {
private static final String USE_TITLE = "title";
private static final String USE_COVER = "cover";
private static final String USE_ARTIST = "artist";
private static final String USE_SAME_LANGUAGE = "sameLanguage";
private static final String IGNORE_CHAPTERS = "ignoreChapters";
private static final String USE_SENSITIVITY = "sensitivity";
private DuplicateData() {
throw new UnsupportedOperationException();
}
public static final class Builder {
private final Data.Builder builder = new Data.Builder();
public void setUseTitle(boolean value) {
builder.putBoolean(USE_TITLE, value);
}
public void setUseCover(boolean value) {
builder.putBoolean(USE_COVER, value);
}
public void setUseArtist(boolean value) {
builder.putBoolean(USE_ARTIST, value);
}
public void setUseSameLanguage(boolean value) {
builder.putBoolean(USE_SAME_LANGUAGE, value);
}
public void setIgnoreChapters(boolean value) {
builder.putBoolean(IGNORE_CHAPTERS, value);
}
public void setSensitivity(int value) {
builder.putInt(USE_SENSITIVITY, value);
}
public Data getData() {
return builder.build();
}
}
public static final class Parser {
private final Data data;
public Parser(@Nonnull Data data) {
this.data = data;
}
public boolean getUseTitle() {
return data.getBoolean(USE_TITLE, false);
}
public boolean getUseCover() {
return data.getBoolean(USE_COVER, false);
}
public boolean getUseArtist() {
return data.getBoolean(USE_ARTIST, false);
}
public boolean getUseSameLanguage() {
return data.getBoolean(USE_SAME_LANGUAGE, false);
}
public boolean getIgnoreChapters() {
return data.getBoolean(IGNORE_CHAPTERS, false);
}
public int getSensitivity() {
return data.getInt(USE_SENSITIVITY, 1);
}
}
}
| apache-2.0 |
wankunde/cloudera_hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/ResourceManager.java | 46615 | /**
* 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.hadoop.yarn.server.resourcemanager;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ha.HAServiceProtocol;
import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState;
import org.apache.hadoop.http.lib.StaticUserWebFilter;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.metrics2.source.JvmMetrics;
import org.apache.hadoop.security.AuthenticationFilterInitializer;
import org.apache.hadoop.security.Groups;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler;
import org.apache.hadoop.security.authorize.ProxyUsers;
import org.apache.hadoop.service.AbstractService;
import org.apache.hadoop.service.CompositeService;
import org.apache.hadoop.service.Service;
import org.apache.hadoop.util.ExitUtil;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.ShutdownHookManager;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.YarnUncaughtExceptionHandler;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.conf.ConfigurationProvider;
import org.apache.hadoop.yarn.conf.ConfigurationProviderFactory;
import org.apache.hadoop.yarn.conf.HAUtil;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.event.AsyncDispatcher;
import org.apache.hadoop.yarn.event.Dispatcher;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.server.resourcemanager.ahs.RMApplicationHistoryWriter;
import org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncherEventType;
import org.apache.hadoop.yarn.server.resourcemanager.amlauncher.ApplicationMasterLauncher;
import org.apache.hadoop.yarn.server.resourcemanager.metrics.SystemMetricsPublisher;
import org.apache.hadoop.yarn.server.resourcemanager.monitor.SchedulingEditPolicy;
import org.apache.hadoop.yarn.server.resourcemanager.monitor.SchedulingMonitor;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.MemoryRMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.NullRMStateStore;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStoreFactory;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.Recoverable;
import org.apache.hadoop.yarn.server.resourcemanager.reservation.AbstractReservationSystem;
import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationSystem;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEvent;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEventType;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.AMLivelinessMonitor;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.ContainerAllocationExpirer;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeEvent;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeEventType;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ContainerPreemptEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ContainerPreemptEventType;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.PreemptableResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEventType;
import org.apache.hadoop.yarn.server.resourcemanager.security.DelegationTokenRenewer;
import org.apache.hadoop.yarn.server.resourcemanager.security.QueueACLsManager;
import org.apache.hadoop.yarn.server.resourcemanager.security.RMAuthenticationHandler;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebApp;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.server.security.http.RMAuthenticationFilter;
import org.apache.hadoop.yarn.server.security.http.RMAuthenticationFilterInitializer;
import org.apache.hadoop.yarn.server.webproxy.AppReportFetcher;
import org.apache.hadoop.yarn.server.webproxy.ProxyUriUtils;
import org.apache.hadoop.yarn.server.webproxy.WebAppProxy;
import org.apache.hadoop.yarn.server.webproxy.WebAppProxyServlet;
import org.apache.hadoop.yarn.webapp.WebApp;
import org.apache.hadoop.yarn.webapp.WebApps;
import org.apache.hadoop.yarn.webapp.WebApps.Builder;
import org.apache.hadoop.yarn.webapp.util.WebAppUtils;
import com.google.common.annotations.VisibleForTesting;
/**
* The ResourceManager is the main class that is a set of components.
* "I am the ResourceManager. All your resources belong to us..."
*
*/
@SuppressWarnings("unchecked")
public class ResourceManager extends CompositeService implements Recoverable {
/**
* Priority of the ResourceManager shutdown hook.
*/
public static final int SHUTDOWN_HOOK_PRIORITY = 30;
private static final Log LOG = LogFactory.getLog(ResourceManager.class);
private static long clusterTimeStamp = System.currentTimeMillis();
/**
* "Always On" services. Services that need to run always irrespective of
* the HA state of the RM.
*/
@VisibleForTesting
protected RMContextImpl rmContext;
private Dispatcher rmDispatcher;
@VisibleForTesting
protected AdminService adminService;
/**
* "Active" services. Services that need to run only on the Active RM.
* These services are managed (initialized, started, stopped) by the
* {@link CompositeService} RMActiveServices.
*
* RM is active when (1) HA is disabled, or (2) HA is enabled and the RM is
* in Active state.
*/
protected RMActiveServices activeServices;
protected RMSecretManagerService rmSecretManagerService;
protected ResourceScheduler scheduler;
protected ReservationSystem reservationSystem;
private ClientRMService clientRM;
protected ApplicationMasterService masterService;
protected NMLivelinessMonitor nmLivelinessMonitor;
protected NodesListManager nodesListManager;
protected RMAppManager rmAppManager;
protected ApplicationACLsManager applicationACLsManager;
protected QueueACLsManager queueACLsManager;
private WebApp webApp;
private AppReportFetcher fetcher = null;
protected ResourceTrackerService resourceTracker;
@VisibleForTesting
protected String webAppAddress;
private ConfigurationProvider configurationProvider = null;
/** End of Active services */
private Configuration conf;
private UserGroupInformation rmLoginUGI;
public ResourceManager() {
super("ResourceManager");
}
public RMContext getRMContext() {
return this.rmContext;
}
public static long getClusterTimeStamp() {
return clusterTimeStamp;
}
@VisibleForTesting
protected static void setClusterTimeStamp(long timestamp) {
clusterTimeStamp = timestamp;
}
@Override
protected void serviceInit(Configuration conf) throws Exception {
this.conf = conf;
this.rmContext = new RMContextImpl();
this.configurationProvider =
ConfigurationProviderFactory.getConfigurationProvider(conf);
this.configurationProvider.init(this.conf);
rmContext.setConfigurationProvider(configurationProvider);
// load core-site.xml
InputStream coreSiteXMLInputStream =
this.configurationProvider.getConfigurationInputStream(this.conf,
YarnConfiguration.CORE_SITE_CONFIGURATION_FILE);
if (coreSiteXMLInputStream != null) {
this.conf.addResource(coreSiteXMLInputStream,
YarnConfiguration.CORE_SITE_CONFIGURATION_FILE);
}
// Do refreshUserToGroupsMappings with loaded core-site.xml
Groups.getUserToGroupsMappingServiceWithLoadedConfiguration(this.conf)
.refresh();
// Do refreshSuperUserGroupsConfiguration with loaded core-site.xml
// Or use RM specific configurations to overwrite the common ones first
// if they exist
RMServerUtils.processRMProxyUsersConf(conf);
ProxyUsers.refreshSuperUserGroupsConfiguration(this.conf);
// load yarn-site.xml
InputStream yarnSiteXMLInputStream =
this.configurationProvider.getConfigurationInputStream(this.conf,
YarnConfiguration.YARN_SITE_CONFIGURATION_FILE);
if (yarnSiteXMLInputStream != null) {
this.conf.addResource(yarnSiteXMLInputStream,
YarnConfiguration.YARN_SITE_CONFIGURATION_FILE);
}
validateConfigs(this.conf);
// Set HA configuration should be done before login
this.rmContext.setHAEnabled(HAUtil.isHAEnabled(this.conf));
if (this.rmContext.isHAEnabled()) {
HAUtil.verifyAndSetConfiguration(this.conf);
}
// Set UGI and do login
// If security is enabled, use login user
// If security is not enabled, use current user
this.rmLoginUGI = UserGroupInformation.getCurrentUser();
try {
doSecureLogin();
} catch(IOException ie) {
throw new YarnRuntimeException("Failed to login", ie);
}
// register the handlers for all AlwaysOn services using setupDispatcher().
rmDispatcher = setupDispatcher();
addIfService(rmDispatcher);
rmContext.setDispatcher(rmDispatcher);
adminService = createAdminService();
addService(adminService);
rmContext.setRMAdminService(adminService);
createAndInitActiveServices();
webAppAddress = WebAppUtils.getWebAppBindURL(this.conf,
YarnConfiguration.RM_BIND_HOST,
WebAppUtils.getRMWebAppURLWithoutScheme(this.conf));
super.serviceInit(this.conf);
}
protected QueueACLsManager createQueueACLsManager(ResourceScheduler scheduler,
Configuration conf) {
return new QueueACLsManager(scheduler, conf);
}
@VisibleForTesting
protected void setRMStateStore(RMStateStore rmStore) {
rmStore.setRMDispatcher(rmDispatcher);
rmStore.setResourceManager(this);
rmContext.setStateStore(rmStore);
}
protected EventHandler<SchedulerEvent> createSchedulerEventDispatcher() {
return new SchedulerEventDispatcher(this.scheduler);
}
protected Dispatcher createDispatcher() {
return new AsyncDispatcher();
}
protected ResourceScheduler createScheduler() {
String schedulerClassName = conf.get(YarnConfiguration.RM_SCHEDULER,
YarnConfiguration.DEFAULT_RM_SCHEDULER);
LOG.info("Using Scheduler: " + schedulerClassName);
try {
Class<?> schedulerClazz = Class.forName(schedulerClassName);
if (ResourceScheduler.class.isAssignableFrom(schedulerClazz)) {
return (ResourceScheduler) ReflectionUtils.newInstance(schedulerClazz,
this.conf);
} else {
throw new YarnRuntimeException("Class: " + schedulerClassName
+ " not instance of " + ResourceScheduler.class.getCanonicalName());
}
} catch (ClassNotFoundException e) {
throw new YarnRuntimeException("Could not instantiate Scheduler: "
+ schedulerClassName, e);
}
}
protected ReservationSystem createReservationSystem() {
String reservationClassName =
conf.get(YarnConfiguration.RM_RESERVATION_SYSTEM_CLASS,
AbstractReservationSystem.getDefaultReservationSystem(scheduler));
if (reservationClassName == null) {
return null;
}
LOG.info("Using ReservationSystem: " + reservationClassName);
try {
Class<?> reservationClazz = Class.forName(reservationClassName);
if (ReservationSystem.class.isAssignableFrom(reservationClazz)) {
return (ReservationSystem) ReflectionUtils.newInstance(
reservationClazz, this.conf);
} else {
throw new YarnRuntimeException("Class: " + reservationClassName
+ " not instance of " + ReservationSystem.class.getCanonicalName());
}
} catch (ClassNotFoundException e) {
throw new YarnRuntimeException(
"Could not instantiate ReservationSystem: " + reservationClassName, e);
}
}
protected ApplicationMasterLauncher createAMLauncher() {
return new ApplicationMasterLauncher(this.rmContext);
}
private NMLivelinessMonitor createNMLivelinessMonitor() {
return new NMLivelinessMonitor(this.rmContext
.getDispatcher());
}
protected AMLivelinessMonitor createAMLivelinessMonitor() {
return new AMLivelinessMonitor(this.rmDispatcher);
}
protected RMNodeLabelsManager createNodeLabelManager()
throws InstantiationException, IllegalAccessException {
Class<? extends RMNodeLabelsManager> nlmCls =
conf.getClass(YarnConfiguration.RM_NODE_LABELS_MANAGER_CLASS,
MemoryRMNodeLabelsManager.class, RMNodeLabelsManager.class);
return nlmCls.newInstance();
}
protected DelegationTokenRenewer createDelegationTokenRenewer() {
return new DelegationTokenRenewer();
}
protected RMAppManager createRMAppManager() {
return new RMAppManager(this.rmContext, this.scheduler, this.masterService,
this.applicationACLsManager, this.conf);
}
protected RMApplicationHistoryWriter createRMApplicationHistoryWriter() {
return new RMApplicationHistoryWriter();
}
protected SystemMetricsPublisher createSystemMetricsPublisher() {
return new SystemMetricsPublisher();
}
// sanity check for configurations
protected static void validateConfigs(Configuration conf) {
// validate max-attempts
int globalMaxAppAttempts =
conf.getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS,
YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS);
if (globalMaxAppAttempts <= 0) {
throw new YarnRuntimeException("Invalid global max attempts configuration"
+ ", " + YarnConfiguration.RM_AM_MAX_ATTEMPTS
+ "=" + globalMaxAppAttempts + ", it should be a positive integer.");
}
// validate expireIntvl >= heartbeatIntvl
long expireIntvl = conf.getLong(YarnConfiguration.RM_NM_EXPIRY_INTERVAL_MS,
YarnConfiguration.DEFAULT_RM_NM_EXPIRY_INTERVAL_MS);
long heartbeatIntvl =
conf.getLong(YarnConfiguration.RM_NM_HEARTBEAT_INTERVAL_MS,
YarnConfiguration.DEFAULT_RM_NM_HEARTBEAT_INTERVAL_MS);
if (expireIntvl < heartbeatIntvl) {
throw new YarnRuntimeException("Nodemanager expiry interval should be no"
+ " less than heartbeat interval, "
+ YarnConfiguration.RM_NM_EXPIRY_INTERVAL_MS + "=" + expireIntvl
+ ", " + YarnConfiguration.RM_NM_HEARTBEAT_INTERVAL_MS + "="
+ heartbeatIntvl);
}
}
/**
* RMActiveServices handles all the Active services in the RM.
*/
@Private
public class RMActiveServices extends CompositeService {
private DelegationTokenRenewer delegationTokenRenewer;
private EventHandler<SchedulerEvent> schedulerDispatcher;
private ApplicationMasterLauncher applicationMasterLauncher;
private ContainerAllocationExpirer containerAllocationExpirer;
private ResourceManager rm;
private boolean recoveryEnabled;
private RMActiveServiceContext activeServiceContext;
RMActiveServices(ResourceManager rm) {
super("RMActiveServices");
this.rm = rm;
}
@Override
protected void serviceInit(Configuration configuration) throws Exception {
activeServiceContext = new RMActiveServiceContext();
rmContext.setActiveServiceContext(activeServiceContext);
conf.setBoolean(Dispatcher.DISPATCHER_EXIT_ON_ERROR_KEY, true);
rmSecretManagerService = createRMSecretManagerService();
addService(rmSecretManagerService);
containerAllocationExpirer = new ContainerAllocationExpirer(rmDispatcher);
addService(containerAllocationExpirer);
rmContext.setContainerAllocationExpirer(containerAllocationExpirer);
AMLivelinessMonitor amLivelinessMonitor = createAMLivelinessMonitor();
addService(amLivelinessMonitor);
rmContext.setAMLivelinessMonitor(amLivelinessMonitor);
AMLivelinessMonitor amFinishingMonitor = createAMLivelinessMonitor();
addService(amFinishingMonitor);
rmContext.setAMFinishingMonitor(amFinishingMonitor);
RMNodeLabelsManager nlm = createNodeLabelManager();
addService(nlm);
rmContext.setNodeLabelManager(nlm);
boolean isRecoveryEnabled = conf.getBoolean(
YarnConfiguration.RECOVERY_ENABLED,
YarnConfiguration.DEFAULT_RM_RECOVERY_ENABLED);
RMStateStore rmStore = null;
if (isRecoveryEnabled) {
recoveryEnabled = true;
rmStore = RMStateStoreFactory.getStore(conf);
boolean isWorkPreservingRecoveryEnabled =
conf.getBoolean(
YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_ENABLED,
YarnConfiguration.DEFAULT_RM_WORK_PRESERVING_RECOVERY_ENABLED);
rmContext
.setWorkPreservingRecoveryEnabled(isWorkPreservingRecoveryEnabled);
} else {
recoveryEnabled = false;
rmStore = new NullRMStateStore();
}
try {
rmStore.init(conf);
rmStore.setRMDispatcher(rmDispatcher);
rmStore.setResourceManager(rm);
} catch (Exception e) {
// the Exception from stateStore.init() needs to be handled for
// HA and we need to give up master status if we got fenced
LOG.error("Failed to init state store", e);
throw e;
}
rmContext.setStateStore(rmStore);
if (UserGroupInformation.isSecurityEnabled()) {
delegationTokenRenewer = createDelegationTokenRenewer();
rmContext.setDelegationTokenRenewer(delegationTokenRenewer);
}
RMApplicationHistoryWriter rmApplicationHistoryWriter =
createRMApplicationHistoryWriter();
addService(rmApplicationHistoryWriter);
rmContext.setRMApplicationHistoryWriter(rmApplicationHistoryWriter);
SystemMetricsPublisher systemMetricsPublisher = createSystemMetricsPublisher();
addService(systemMetricsPublisher);
rmContext.setSystemMetricsPublisher(systemMetricsPublisher);
// Register event handler for NodesListManager
nodesListManager = new NodesListManager(rmContext);
rmDispatcher.register(NodesListManagerEventType.class, nodesListManager);
addService(nodesListManager);
rmContext.setNodesListManager(nodesListManager);
// Initialize the scheduler
scheduler = createScheduler();
scheduler.setRMContext(rmContext);
addIfService(scheduler);
rmContext.setScheduler(scheduler);
schedulerDispatcher = createSchedulerEventDispatcher();
addIfService(schedulerDispatcher);
rmDispatcher.register(SchedulerEventType.class, schedulerDispatcher);
// Register event handler for RmAppEvents
rmDispatcher.register(RMAppEventType.class,
new ApplicationEventDispatcher(rmContext));
// Register event handler for RmAppAttemptEvents
rmDispatcher.register(RMAppAttemptEventType.class,
new ApplicationAttemptEventDispatcher(rmContext));
// Register event handler for RmNodes
rmDispatcher.register(
RMNodeEventType.class, new NodeEventDispatcher(rmContext));
nmLivelinessMonitor = createNMLivelinessMonitor();
addService(nmLivelinessMonitor);
resourceTracker = createResourceTrackerService();
addService(resourceTracker);
rmContext.setResourceTrackerService(resourceTracker);
DefaultMetricsSystem.initialize("ResourceManager");
JvmMetrics.initSingleton("ResourceManager", null);
// Initialize the Reservation system
if (conf.getBoolean(YarnConfiguration.RM_RESERVATION_SYSTEM_ENABLE,
YarnConfiguration.DEFAULT_RM_RESERVATION_SYSTEM_ENABLE)) {
reservationSystem = createReservationSystem();
if (reservationSystem != null) {
reservationSystem.setRMContext(rmContext);
addIfService(reservationSystem);
rmContext.setReservationSystem(reservationSystem);
LOG.info("Initialized Reservation system");
}
}
// creating monitors that handle preemption
createPolicyMonitors();
masterService = createApplicationMasterService();
addService(masterService) ;
rmContext.setApplicationMasterService(masterService);
applicationACLsManager = new ApplicationACLsManager(conf);
queueACLsManager = createQueueACLsManager(scheduler, conf);
rmAppManager = createRMAppManager();
// Register event handler for RMAppManagerEvents
rmDispatcher.register(RMAppManagerEventType.class, rmAppManager);
clientRM = createClientRMService();
addService(clientRM);
rmContext.setClientRMService(clientRM);
applicationMasterLauncher = createAMLauncher();
rmDispatcher.register(AMLauncherEventType.class,
applicationMasterLauncher);
addService(applicationMasterLauncher);
if (UserGroupInformation.isSecurityEnabled()) {
addService(delegationTokenRenewer);
delegationTokenRenewer.setRMContext(rmContext);
}
new RMNMInfo(rmContext, scheduler);
super.serviceInit(conf);
}
@Override
protected void serviceStart() throws Exception {
RMStateStore rmStore = rmContext.getStateStore();
// The state store needs to start irrespective of recoveryEnabled as apps
// need events to move to further states.
rmStore.start();
if(recoveryEnabled) {
try {
rmStore.checkVersion();
if (rmContext.isWorkPreservingRecoveryEnabled()) {
rmContext.setEpoch(rmStore.getAndIncrementEpoch());
}
RMState state = rmStore.loadState();
recover(state);
} catch (Exception e) {
// the Exception from loadState() needs to be handled for
// HA and we need to give up master status if we got fenced
LOG.error("Failed to load/recover state", e);
throw e;
}
}
super.serviceStart();
}
@Override
protected void serviceStop() throws Exception {
DefaultMetricsSystem.shutdown();
if (rmContext != null) {
RMStateStore store = rmContext.getStateStore();
try {
store.close();
} catch (Exception e) {
LOG.error("Error closing store.", e);
}
}
super.serviceStop();
}
protected void createPolicyMonitors() {
if (scheduler instanceof PreemptableResourceScheduler
&& conf.getBoolean(YarnConfiguration.RM_SCHEDULER_ENABLE_MONITORS,
YarnConfiguration.DEFAULT_RM_SCHEDULER_ENABLE_MONITORS)) {
LOG.info("Loading policy monitors");
List<SchedulingEditPolicy> policies = conf.getInstances(
YarnConfiguration.RM_SCHEDULER_MONITOR_POLICIES,
SchedulingEditPolicy.class);
if (policies.size() > 0) {
rmDispatcher.register(ContainerPreemptEventType.class,
new RMContainerPreemptEventDispatcher(
(PreemptableResourceScheduler) scheduler));
for (SchedulingEditPolicy policy : policies) {
LOG.info("LOADING SchedulingEditPolicy:" + policy.getPolicyName());
// periodically check whether we need to take action to guarantee
// constraints
SchedulingMonitor mon = new SchedulingMonitor(rmContext, policy);
addService(mon);
}
} else {
LOG.warn("Policy monitors configured (" +
YarnConfiguration.RM_SCHEDULER_ENABLE_MONITORS +
") but none specified (" +
YarnConfiguration.RM_SCHEDULER_MONITOR_POLICIES + ")");
}
}
}
}
@Private
public static class SchedulerEventDispatcher extends AbstractService
implements EventHandler<SchedulerEvent> {
private final ResourceScheduler scheduler;
private final BlockingQueue<SchedulerEvent> eventQueue =
new LinkedBlockingQueue<SchedulerEvent>();
private final Thread eventProcessor;
private volatile boolean stopped = false;
private boolean shouldExitOnError = false;
public SchedulerEventDispatcher(ResourceScheduler scheduler) {
super(SchedulerEventDispatcher.class.getName());
this.scheduler = scheduler;
this.eventProcessor = new Thread(new EventProcessor());
this.eventProcessor.setName("ResourceManager Event Processor");
}
@Override
protected void serviceInit(Configuration conf) throws Exception {
this.shouldExitOnError =
conf.getBoolean(Dispatcher.DISPATCHER_EXIT_ON_ERROR_KEY,
Dispatcher.DEFAULT_DISPATCHER_EXIT_ON_ERROR);
super.serviceInit(conf);
}
@Override
protected void serviceStart() throws Exception {
this.eventProcessor.start();
super.serviceStart();
}
private final class EventProcessor implements Runnable {
@Override
public void run() {
SchedulerEvent event;
while (!stopped && !Thread.currentThread().isInterrupted()) {
try {
event = eventQueue.take();
} catch (InterruptedException e) {
LOG.error("Returning, interrupted : " + e);
return; // TODO: Kill RM.
}
try {
scheduler.handle(event);
} catch (Throwable t) {
// An error occurred, but we are shutting down anyway.
// If it was an InterruptedException, the very act of
// shutdown could have caused it and is probably harmless.
if (stopped) {
LOG.warn("Exception during shutdown: ", t);
break;
}
LOG.fatal("Error in handling event type " + event.getType()
+ " to the scheduler", t);
if (shouldExitOnError
&& !ShutdownHookManager.get().isShutdownInProgress()) {
LOG.info("Exiting, bbye..");
System.exit(-1);
}
}
}
}
}
@Override
protected void serviceStop() throws Exception {
this.stopped = true;
this.eventProcessor.interrupt();
try {
this.eventProcessor.join();
} catch (InterruptedException e) {
throw new YarnRuntimeException(e);
}
super.serviceStop();
}
@Override
public void handle(SchedulerEvent event) {
try {
int qSize = eventQueue.size();
if (qSize !=0 && qSize %1000 == 0) {
LOG.info("Size of scheduler event-queue is " + qSize);
}
int remCapacity = eventQueue.remainingCapacity();
if (remCapacity < 1000) {
LOG.info("Very low remaining capacity on scheduler event queue: "
+ remCapacity);
}
this.eventQueue.put(event);
} catch (InterruptedException e) {
LOG.info("Interrupted. Trying to exit gracefully.");
}
}
}
@Private
public static class RMFatalEventDispatcher
implements EventHandler<RMFatalEvent> {
@Override
public void handle(RMFatalEvent event) {
LOG.fatal("Received a " + RMFatalEvent.class.getName() + " of type " +
event.getType().name() + ". Cause:\n" + event.getCause());
ExitUtil.terminate(1, event.getCause());
}
}
public void handleTransitionToStandBy() {
if (rmContext.isHAEnabled()) {
try {
// Transition to standby and reinit active services
LOG.info("Transitioning RM to Standby mode");
transitionToStandby(true);
adminService.resetLeaderElection();
return;
} catch (Exception e) {
LOG.fatal("Failed to transition RM to Standby mode.");
ExitUtil.terminate(1, e);
}
}
}
@Private
public static final class ApplicationEventDispatcher implements
EventHandler<RMAppEvent> {
private final RMContext rmContext;
public ApplicationEventDispatcher(RMContext rmContext) {
this.rmContext = rmContext;
}
@Override
public void handle(RMAppEvent event) {
ApplicationId appID = event.getApplicationId();
RMApp rmApp = this.rmContext.getRMApps().get(appID);
if (rmApp != null) {
try {
rmApp.handle(event);
} catch (Throwable t) {
LOG.error("Error in handling event type " + event.getType()
+ " for application " + appID, t);
}
}
}
}
@Private
public static final class
RMContainerPreemptEventDispatcher
implements EventHandler<ContainerPreemptEvent> {
private final PreemptableResourceScheduler scheduler;
public RMContainerPreemptEventDispatcher(
PreemptableResourceScheduler scheduler) {
this.scheduler = scheduler;
}
@Override
public void handle(ContainerPreemptEvent event) {
ApplicationAttemptId aid = event.getAppId();
RMContainer container = event.getContainer();
switch (event.getType()) {
case DROP_RESERVATION:
scheduler.dropContainerReservation(container);
break;
case PREEMPT_CONTAINER:
scheduler.preemptContainer(aid, container);
break;
case KILL_CONTAINER:
scheduler.killContainer(container);
break;
}
}
}
@Private
public static final class ApplicationAttemptEventDispatcher implements
EventHandler<RMAppAttemptEvent> {
private final RMContext rmContext;
public ApplicationAttemptEventDispatcher(RMContext rmContext) {
this.rmContext = rmContext;
}
@Override
public void handle(RMAppAttemptEvent event) {
ApplicationAttemptId appAttemptID = event.getApplicationAttemptId();
ApplicationId appAttemptId = appAttemptID.getApplicationId();
RMApp rmApp = this.rmContext.getRMApps().get(appAttemptId);
if (rmApp != null) {
RMAppAttempt rmAppAttempt = rmApp.getRMAppAttempt(appAttemptID);
if (rmAppAttempt != null) {
try {
rmAppAttempt.handle(event);
} catch (Throwable t) {
LOG.error("Error in handling event type " + event.getType()
+ " for applicationAttempt " + appAttemptId, t);
}
}
}
}
}
@Private
public static final class NodeEventDispatcher implements
EventHandler<RMNodeEvent> {
private final RMContext rmContext;
public NodeEventDispatcher(RMContext rmContext) {
this.rmContext = rmContext;
}
@Override
public void handle(RMNodeEvent event) {
NodeId nodeId = event.getNodeId();
RMNode node = this.rmContext.getRMNodes().get(nodeId);
if (node != null) {
try {
((EventHandler<RMNodeEvent>) node).handle(event);
} catch (Throwable t) {
LOG.error("Error in handling event type " + event.getType()
+ " for node " + nodeId, t);
}
}
}
}
protected void startWepApp() {
// Use the customized yarn filter instead of the standard kerberos filter to
// allow users to authenticate using delegation tokens
// 4 conditions need to be satisfied -
// 1. security is enabled
// 2. http auth type is set to kerberos
// 3. "yarn.resourcemanager.webapp.use-yarn-filter" override is set to true
// 4. hadoop.http.filter.initializers container AuthenticationFilterInitializer
Configuration conf = getConfig();
boolean useYarnAuthenticationFilter =
conf.getBoolean(
YarnConfiguration.RM_WEBAPP_DELEGATION_TOKEN_AUTH_FILTER,
YarnConfiguration.DEFAULT_RM_WEBAPP_DELEGATION_TOKEN_AUTH_FILTER);
String authPrefix = "hadoop.http.authentication.";
String authTypeKey = authPrefix + "type";
String filterInitializerConfKey = "hadoop.http.filter.initializers";
String actualInitializers = "";
Class<?>[] initializersClasses =
conf.getClasses(filterInitializerConfKey);
boolean hasHadoopAuthFilterInitializer = false;
boolean hasRMAuthFilterInitializer = false;
if (initializersClasses != null) {
for (Class<?> initializer : initializersClasses) {
if (initializer.getName().equals(
AuthenticationFilterInitializer.class.getName())) {
hasHadoopAuthFilterInitializer = true;
}
if (initializer.getName().equals(
RMAuthenticationFilterInitializer.class.getName())) {
hasRMAuthFilterInitializer = true;
}
}
if (UserGroupInformation.isSecurityEnabled()
&& useYarnAuthenticationFilter
&& hasHadoopAuthFilterInitializer
&& conf.get(authTypeKey, "").equals(
KerberosAuthenticationHandler.TYPE)) {
ArrayList<String> target = new ArrayList<String>();
for (Class<?> filterInitializer : initializersClasses) {
if (filterInitializer.getName().equals(
AuthenticationFilterInitializer.class.getName())) {
if (hasRMAuthFilterInitializer == false) {
target.add(RMAuthenticationFilterInitializer.class.getName());
}
continue;
}
target.add(filterInitializer.getName());
}
actualInitializers = StringUtils.join(",", target);
LOG.info("Using RM authentication filter(kerberos/delegation-token)"
+ " for RM webapp authentication");
RMAuthenticationHandler
.setSecretManager(getClientRMService().rmDTSecretManager);
RMAuthenticationFilter
.setDelegationTokenSecretManager(getClientRMService().rmDTSecretManager);
String yarnAuthKey =
authPrefix + RMAuthenticationFilter.AUTH_HANDLER_PROPERTY;
conf.setStrings(yarnAuthKey, RMAuthenticationHandler.class.getName());
conf.set(filterInitializerConfKey, actualInitializers);
}
}
// if security is not enabled and the default filter initializer has not
// been set, set the initializer to include the
// RMAuthenticationFilterInitializer which in turn will set up the simple
// auth filter.
String initializers = conf.get(filterInitializerConfKey);
if (!UserGroupInformation.isSecurityEnabled()) {
if (initializersClasses == null || initializersClasses.length == 0) {
conf.set(filterInitializerConfKey,
RMAuthenticationFilterInitializer.class.getName());
conf.set(authTypeKey, "simple");
} else if (initializers.equals(StaticUserWebFilter.class.getName())) {
conf.set(filterInitializerConfKey,
RMAuthenticationFilterInitializer.class.getName() + ","
+ initializers);
conf.set(authTypeKey, "simple");
}
}
Builder<ApplicationMasterService> builder =
WebApps
.$for("cluster", ApplicationMasterService.class, masterService,
"ws")
.with(conf)
.withHttpSpnegoPrincipalKey(
YarnConfiguration.RM_WEBAPP_SPNEGO_USER_NAME_KEY)
.withHttpSpnegoKeytabKey(
YarnConfiguration.RM_WEBAPP_SPNEGO_KEYTAB_FILE_KEY)
.at(webAppAddress);
String proxyHostAndPort = WebAppUtils.getProxyHostAndPort(conf);
if(WebAppUtils.getResolvedRMWebAppURLWithoutScheme(conf).
equals(proxyHostAndPort)) {
if (HAUtil.isHAEnabled(conf)) {
fetcher = new AppReportFetcher(conf);
} else {
fetcher = new AppReportFetcher(conf, getClientRMService());
}
builder.withServlet(ProxyUriUtils.PROXY_SERVLET_NAME,
ProxyUriUtils.PROXY_PATH_SPEC, WebAppProxyServlet.class);
builder.withAttribute(WebAppProxy.FETCHER_ATTRIBUTE, fetcher);
String[] proxyParts = proxyHostAndPort.split(":");
builder.withAttribute(WebAppProxy.PROXY_HOST_ATTRIBUTE, proxyParts[0]);
}
webApp = builder.start(new RMWebApp(this));
}
/**
* Helper method to create and init {@link #activeServices}. This creates an
* instance of {@link RMActiveServices} and initializes it.
* @throws Exception
*/
protected void createAndInitActiveServices() throws Exception {
activeServices = new RMActiveServices(this);
activeServices.init(conf);
}
/**
* Helper method to start {@link #activeServices}.
* @throws Exception
*/
void startActiveServices() throws Exception {
if (activeServices != null) {
clusterTimeStamp = System.currentTimeMillis();
activeServices.start();
}
}
/**
* Helper method to stop {@link #activeServices}.
* @throws Exception
*/
void stopActiveServices() throws Exception {
if (activeServices != null) {
activeServices.stop();
activeServices = null;
}
}
void reinitialize(boolean initialize) throws Exception {
ClusterMetrics.destroy();
QueueMetrics.clearQueueMetrics();
if (initialize) {
resetDispatcher();
createAndInitActiveServices();
}
}
@VisibleForTesting
protected boolean areActiveServicesRunning() {
return activeServices != null && activeServices.isInState(STATE.STARTED);
}
synchronized void transitionToActive() throws Exception {
if (rmContext.getHAServiceState() == HAServiceProtocol.HAServiceState.ACTIVE) {
LOG.info("Already in active state");
return;
}
LOG.info("Transitioning to active state");
this.rmLoginUGI.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
try {
startActiveServices();
return null;
} catch (Exception e) {
reinitialize(true);
throw e;
}
}
});
rmContext.setHAServiceState(HAServiceProtocol.HAServiceState.ACTIVE);
LOG.info("Transitioned to active state");
}
synchronized void transitionToStandby(boolean initialize)
throws Exception {
if (rmContext.getHAServiceState() ==
HAServiceProtocol.HAServiceState.STANDBY) {
LOG.info("Already in standby state");
return;
}
LOG.info("Transitioning to standby state");
if (rmContext.getHAServiceState() ==
HAServiceProtocol.HAServiceState.ACTIVE) {
stopActiveServices();
reinitialize(initialize);
}
rmContext.setHAServiceState(HAServiceProtocol.HAServiceState.STANDBY);
LOG.info("Transitioned to standby state");
}
@Override
protected void serviceStart() throws Exception {
if (this.rmContext.isHAEnabled()) {
transitionToStandby(true);
} else {
transitionToActive();
}
startWepApp();
if (getConfig().getBoolean(YarnConfiguration.IS_MINI_YARN_CLUSTER,
false)) {
int port = webApp.port();
WebAppUtils.setRMWebAppPort(conf, port);
}
super.serviceStart();
}
protected void doSecureLogin() throws IOException {
InetSocketAddress socAddr = getBindAddress(conf);
SecurityUtil.login(this.conf, YarnConfiguration.RM_KEYTAB,
YarnConfiguration.RM_PRINCIPAL, socAddr.getHostName());
// if security is enable, set rmLoginUGI as UGI of loginUser
if (UserGroupInformation.isSecurityEnabled()) {
this.rmLoginUGI = UserGroupInformation.getLoginUser();
}
}
@Override
protected void serviceStop() throws Exception {
if (webApp != null) {
webApp.stop();
}
if (fetcher != null) {
fetcher.stop();
}
if (configurationProvider != null) {
configurationProvider.close();
}
super.serviceStop();
transitionToStandby(false);
rmContext.setHAServiceState(HAServiceState.STOPPING);
}
protected ResourceTrackerService createResourceTrackerService() {
return new ResourceTrackerService(this.rmContext, this.nodesListManager,
this.nmLivelinessMonitor,
this.rmContext.getContainerTokenSecretManager(),
this.rmContext.getNMTokenSecretManager());
}
protected ClientRMService createClientRMService() {
return new ClientRMService(this.rmContext, scheduler, this.rmAppManager,
this.applicationACLsManager, this.queueACLsManager,
this.rmContext.getRMDelegationTokenSecretManager());
}
protected ApplicationMasterService createApplicationMasterService() {
return new ApplicationMasterService(this.rmContext, scheduler);
}
protected AdminService createAdminService() {
return new AdminService(this, rmContext);
}
protected RMSecretManagerService createRMSecretManagerService() {
return new RMSecretManagerService(conf, rmContext);
}
@Private
public ClientRMService getClientRMService() {
return this.clientRM;
}
/**
* return the scheduler.
* @return the scheduler for the Resource Manager.
*/
@Private
public ResourceScheduler getResourceScheduler() {
return this.scheduler;
}
/**
* return the resource tracking component.
* @return the resource tracking component.
*/
@Private
public ResourceTrackerService getResourceTrackerService() {
return this.resourceTracker;
}
@Private
public ApplicationMasterService getApplicationMasterService() {
return this.masterService;
}
@Private
public ApplicationACLsManager getApplicationACLsManager() {
return this.applicationACLsManager;
}
@Private
public QueueACLsManager getQueueACLsManager() {
return this.queueACLsManager;
}
@Private
WebApp getWebapp() {
return this.webApp;
}
@Override
public void recover(RMState state) throws Exception {
// recover RMdelegationTokenSecretManager
rmContext.getRMDelegationTokenSecretManager().recover(state);
// recover AMRMTokenSecretManager
rmContext.getAMRMTokenSecretManager().recover(state);
// recover applications
rmAppManager.recover(state);
setSchedulerRecoveryStartAndWaitTime(state, conf);
}
public static void main(String argv[]) {
Thread.setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler());
StringUtils.startupShutdownMessage(ResourceManager.class, argv, LOG);
try {
Configuration conf = new YarnConfiguration();
// If -format-state-store, then delete RMStateStore; else startup normally
if (argv.length == 1 && argv[0].equals("-format-state-store")) {
deleteRMStateStore(conf);
} else {
ResourceManager resourceManager = new ResourceManager();
ShutdownHookManager.get().addShutdownHook(
new CompositeServiceShutdownHook(resourceManager),
SHUTDOWN_HOOK_PRIORITY);
resourceManager.init(conf);
resourceManager.start();
}
} catch (Throwable t) {
LOG.fatal("Error starting ResourceManager", t);
System.exit(-1);
}
}
/**
* Register the handlers for alwaysOn services
*/
private Dispatcher setupDispatcher() {
Dispatcher dispatcher = createDispatcher();
dispatcher.register(RMFatalEventType.class,
new ResourceManager.RMFatalEventDispatcher());
return dispatcher;
}
private void resetDispatcher() {
Dispatcher dispatcher = setupDispatcher();
((Service)dispatcher).init(this.conf);
((Service)dispatcher).start();
removeService((Service)rmDispatcher);
// Need to stop previous rmDispatcher before assigning new dispatcher
// otherwise causes "AsyncDispatcher event handler" thread leak
((Service) rmDispatcher).stop();
rmDispatcher = dispatcher;
addIfService(rmDispatcher);
rmContext.setDispatcher(rmDispatcher);
}
private void setSchedulerRecoveryStartAndWaitTime(RMState state,
Configuration conf) {
if (!state.getApplicationState().isEmpty()) {
long waitTime =
conf.getLong(YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_SCHEDULING_WAIT_MS,
YarnConfiguration.DEFAULT_RM_WORK_PRESERVING_RECOVERY_SCHEDULING_WAIT_MS);
rmContext.setSchedulerRecoveryStartAndWaitTime(waitTime);
}
}
/**
* Retrieve RM bind address from configuration
*
* @param conf
* @return InetSocketAddress
*/
public static InetSocketAddress getBindAddress(Configuration conf) {
return conf.getSocketAddr(YarnConfiguration.RM_ADDRESS,
YarnConfiguration.DEFAULT_RM_ADDRESS, YarnConfiguration.DEFAULT_RM_PORT);
}
/**
* Deletes the RMStateStore
*
* @param conf
* @throws Exception
*/
private static void deleteRMStateStore(Configuration conf) throws Exception {
RMStateStore rmStore = RMStateStoreFactory.getStore(conf);
rmStore.init(conf);
rmStore.start();
try {
LOG.info("Deleting ResourceManager state store...");
rmStore.deleteStore();
LOG.info("State store deleted");
} finally {
rmStore.stop();
}
}
}
| apache-2.0 |
itshorty/waspi | src/main/java/at/ffesternberg/waspi/api/WasPiOrder.java | 284 | package at.ffesternberg.waspi.api;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import at.ffesternberg.libwas.entity.Order;
@JsonAutoDetect
public class WasPiOrder extends Order {
public WasPiOrder() {
}
public WasPiOrder(Order old){
super(old);
}
}
| apache-2.0 |
zelig81/hyperactive-home | YetAnotherChess/src/project/ilyagorban/view/ChessViewConsole.java | 1835 | package project.ilyagorban.view;
import java.util.Scanner;
import project.ilyagorban.model.XY;
import project.ilyagorban.model.figures.Figure;
public class ChessViewConsole implements Visualizable {
private final Scanner sc = new Scanner(System.in);
private String message;
@Override
public String getInput(String string) {
System.out.println(string);
String result = this.sc.nextLine();
return result;
}
@Override
public void getMessageToView(String string) {
System.out.println(string);
}
@Override
public void setMessage(String message) {
this.message = message;
}
// 254B cross
// 2501 horizontal
// 2503 vertical
@Override
public String showBoard(Figure[] figures, String currentOwner) {
System.out.println("\n\n\n\n\n\n\n\n\n\n");
System.out.println("░|░A░| ░B░| ░C░| ░D░|░E░| ░F░| ░G░| ░H░|░");
// 8|▓♜▓|░♞░|▓♝▓|░♛░|▓♚▓|░♝░|▓♞▓|░♜░|
for (int y = 7; y >= 0; y--) {
StringBuilder output = (new StringBuilder(String.valueOf(y + 1))).append("|");
for (int x = 0; x <= 7; x++) {
String color = ((x + y) % 2 == 1) ? "▓" : "░";
Figure fig = figures[XY.getIndexFromXY(x, y)];
if (fig != null) {
output.append(color).append(fig).append(color).append("|");
} else {
output.append(color).append(color).append(color).append("|");
}
}
output.append(y + 1);
System.out.println(output);
}
System.out.println("░|░A░| ░B░| ░C░| ░D░|░E░| ░F░| ░G░| ░H░|░");
if (this.message != null) {
System.out.println(this.message);
this.message = null;
}
System.out.println(currentOwner
+ " your move (for example [e2e4]) or enter [exit] to quit the game:");
String input = this.sc.nextLine();
return input;
}
}
| apache-2.0 |
DarkMentat/GuitarScalesBoxes | src/org/darkmentat/GuitarScalesBoxes/Model/Box.java | 5312 | package org.darkmentat.GuitarScalesBoxes.Model;
import android.graphics.Point;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Box
{
public final List<Point> Points;
public final int StartFret;
public final int EndFret;
public final int Width;
public Box(GuitarModel fretBoard, Scale scale, int startFret, int endFret) {
Map<NoteModel, List<Point>> points = new TreeMap<>();
NoteModel startNote = null;
for(int y = fretBoard.StringCount-1; y >= 0; y--)
for(int x = 0; x < fretBoard.FretCount; x++)
{
if(y == fretBoard.StringCount-1 && x < startFret-1)
continue;
NoteModel note = (NoteModel) fretBoard.Tab[x][y];
if(scale.isNoteOnScale(note))
{
if(startNote == null)
startNote = note;
if(note.compareTo(startNote) < 0)
continue;
if(!points.containsKey(note))
points.put(note, new ArrayList<Point>());
points.get(note).add(new Point(x,y));
}
}
Points = new ArrayList<>(points.size());
ArrayList<Point> checked = new ArrayList<>();
for (NoteModel note : points.keySet())
{
boolean allInInterval = true;
checked.clear();
checked.addAll(points.get(note));
//region Check interval
for (int i = 0; i < checked.size(); i++)
if(!inInterval(checked.get(i), startFret, endFret))
{
checked.remove(i);
i--;
}
if(checked.size() == 1)
{
Point current = checked.get(0);
if(current.x > endFret && current.y == 0)
break;
Points.add(current);
continue;
}
if(checked.isEmpty())
{
checked.addAll(points.get(note));
allInInterval = false;
}
//endregion
//region Check width
for (int i = 0; i < checked.size(); i++)
if(!acceptedWidth(checked.get(i)))
{
checked.remove(i);
i--;
}
if(checked.size() == 1)
{
Point current = checked.get(0);
Points.add(current);
continue;
}
if(checked.isEmpty())
checked.addAll(points.get(note));
//endregion
//region Check distance to interval
int minDistance = fretBoard.FretCount;
for (Point p : checked)
{
int d = distanceToInterval(p, startFret, endFret);
if (d < minDistance) minDistance = d;
}
for (int i = 0; i < checked.size(); i++)
if(distanceToInterval(checked.get(i), startFret, endFret) > minDistance)
{
checked.remove(i);
i--;
}
if(checked.size() == 1)
{
Point current = checked.get(0);
if(current.x > endFret && current.y == 0)
break;
Points.add(current);
continue;
}
//endregion
//region Check righter and lefter
int maxX = 0;
int righterIndex = 0;
int minX = fretBoard.FretCount;
int lefterIndex = 0;
for (int i = 0; i < checked.size(); i++)
{
if (checked.get(i).x > maxX)
{
maxX = checked.get(i).x;
righterIndex = i;
}
if (checked.get(i).x < minX)
{
minX = checked.get(i).x;
lefterIndex = i;
}
}
Point current;
if(allInInterval)
current = checked.get(righterIndex);
else
current = checked.get(lefterIndex);
if(current.x > endFret && current.y == 0)
break;
Points.add(current);
//endregion
}
int end = 0;
int start = fretBoard.FretCount;
for (Point p : Points)
{
if(p.x > end) end = p.x;
if(p.x < start) start = p.x;
}
StartFret = start;
EndFret = end;
Width = EndFret - StartFret;
}
private boolean inInterval(Point p, int s, int e){
return s <= p.x && p.x <= e;
}
private boolean acceptedWidth(Point p){
int a = firstBoxNoteOnString(p.y);
return a < 0 || p.x - a < 5;
}
private int distanceToInterval(Point p, int s, int e){
if(p.x < s) return s - p.x;
if(p.x > e) return p.x - e;
return 0;
}
private int firstBoxNoteOnString(int y){
for (Point point : Points)
if(point.y == y)
return point.x;
return -1;
}
}
| apache-2.0 |
rinde/RinLog | src/main/java/com/github/rinde/logistics/pdptw/mas/comm/Bid.java | 925 | /*
* Copyright (C) 2013-2016 Rinde van Lon, iMinds-DistriNet, KU Leuven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.rinde.logistics.pdptw.mas.comm;
import com.github.rinde.rinsim.core.model.pdp.Parcel;
/**
*
* @author Rinde van Lon
*/
public interface Bid<T extends Bid<T>> extends Comparable<T> {
long getTimeOfAuction();
Bidder<T> getBidder();
Parcel getParcel();
}
| apache-2.0 |
apigee-labs/apibaas-monitoring | rest/src/test/java/org/apache/usergrid/apm/rest/APMRestServiceSmokeTest.java | 14819 | /*
* 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.usergrid.apm.rest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.apache.http.HttpStatus;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.apache.usergrid.apm.rest.AppDetailsForAPM;
import org.apache.usergrid.apm.model.ApigeeMobileAPMConstants;
import org.apache.usergrid.apm.model.App;
import org.apache.usergrid.apm.model.AppConfigCustomParameter;
import org.apache.usergrid.apm.model.AppConfigOverrideFilter;
import org.apache.usergrid.apm.model.ApplicationConfigurationModel;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import junit.framework.TestCase;
/**
* Unit test for simple App.
*/
public class APMRestServiceSmokeTest extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
private String serverURL = "http://localhost:8080/apigee-apm/org/app/apm/";
public APMRestServiceSmokeTest( String testName )
{
super( testName );
}
public void testCreateAndGetApp()
{
try {
Client client = Client.create();
WebResource webResource = client.resource(serverURL+"appConfig");
AppDetailsForAPM app = new AppDetailsForAPM();
app.setAppUUID(UUID.randomUUID());
app.setOrgUUID(UUID.randomUUID());
app.setAppName("app");
app.setOrgName("org");
app.setCreatedDate(new Date());
String input = new ObjectMapper().writeValueAsString(app);
System.out.println("JSON request to server for create app" + input);
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output for create request .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
//Calling to get app
webResource = client
.resource(serverURL+"appConfig/1");
response = webResource.type("application/json")
.get (ClientResponse.class);
System.out.println("Output from Server for Get App .... \n");
output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
} catch (Exception e) {
fail();
e.printStackTrace();
}
}
public void testGetVisibleSessionChartCriteria() {
try {
Client client = Client.create();
WebResource webResource = client.resource(serverURL+"sessionChartCriteria/1");
ClientResponse response = webResource.type("application/x-javascript")
.get (ClientResponse.class);
System.out.println("Output from Server for Get Visible session chart criteria .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
}
catch (Exception e) {
fail();
e.printStackTrace();
}
}
public void testGetVisibleLogChartCriteria() {
try {
Client client = Client.create();
WebResource webResource = client.resource(serverURL+"logChartCriteria/1");
ClientResponse response = webResource.type("application/json")
.get (ClientResponse.class);
System.out.println("Output from Server for Get Visible log chart criteria .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
}
catch (Exception e) {
fail();
e.printStackTrace();
}
}
public void testGetVisibleNetworkChartCriteria() {
try {
Client client = Client.create();
WebResource webResource = client.resource(serverURL+"networkChartCriteria/1");
ClientResponse response = webResource.type("application/json")
.get (ClientResponse.class);
System.out.println("Output from Server for Get Visible network chart criteria .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
}
catch (Exception e) {
fail();
e.printStackTrace();
}
}
public void testGetSessionChartData() {
try {
Client client = Client.create();
WebResource webResource = client.resource(serverURL+"sessionChartData/1");
ClientResponse response = webResource.type("application/json")
.get (ClientResponse.class);
System.out.println("Output from Server for Get sesson chart data .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
}
catch (Exception e) {
fail();
e.printStackTrace();
}
}
public void testGetSessionChartDataBarChart() {
try {
Client client = Client.create();
WebResource webResource = client.resource(serverURL+"sessionChartData/1?period=3h&chartType=bar");
ClientResponse response = webResource.type("application/json")
.get (ClientResponse.class);
System.out.println("Output from Server for Get sesson chart data for bar chart.... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
}
catch (Exception e) {
fail();
e.printStackTrace();
}
}
public void testGetLogChartData() {
try {
Client client = Client.create();
WebResource webResource = client.resource(serverURL+"logChartData/1");
ClientResponse response = webResource.type("application/json")
.get (ClientResponse.class);
System.out.println("Output from Server for Get Log chart data .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
}
catch (Exception e) {
fail();
e.printStackTrace();
}
}
public void testGetLogChartDataPieChart() {
try {
Client client = Client.create();
WebResource webResource = client.resource(serverURL+"logChartData/3?period=3h&chartType=pie");
ClientResponse response = webResource.type("application/json")
.get (ClientResponse.class);
System.out.println("Output from Server for Get Log chart data for pie chart.... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
}
catch (Exception e) {
fail();
e.printStackTrace();
}
}
public void testNetworkChartData() {
try {
Client client = Client.create();
WebResource webResource = client.resource(serverURL+"networkChartData/1");
ClientResponse response = webResource.type("application/json")
.get (ClientResponse.class);
System.out.println("Output from Server for Get Log chart data .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
}
catch (Exception e) {
fail();
e.printStackTrace();
}
}
public void testLogRawData() {
try {
Client client = Client.create();
WebResource webResource = client.resource(serverURL+"logRawData/1");
ClientResponse response = webResource.type("application/json")
.get (ClientResponse.class);
System.out.println("Output from Server for Get Raw Log data .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
}
catch (Exception e) {
fail();
e.printStackTrace();
}
}
public void testCrashRawData() {
try {
Client client = Client.create();
WebResource webResource = client.resource(serverURL+"crashRawData/1");
ClientResponse response = webResource.type("application/json")
.get (ClientResponse.class);
System.out.println("Output from Server for Get Crash Log data .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
}
catch (Exception e) {
fail();
e.printStackTrace();
}
}
public void testNetworkRawData() {
try {
Client client = Client.create();
WebResource webResource = client.resource(serverURL+"networkRawData/1");
ClientResponse response = webResource.type("application/json")
.get (ClientResponse.class);
System.out.println("Output from Server for Get Raw Network data .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
}
catch (Exception e) {
fail();
e.printStackTrace();
}
}
public void testGetStatus() {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/apigee-apm/apm/status");
ClientResponse response = webResource.type("application/json")
.get (ClientResponse.class);
System.out.println("Output from Server for Getting Status.... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
}
catch (Exception e) {
fail("testGetStatus");
e.printStackTrace();
}
}
public void _testCrashLogSend () {
final Client client = Client.create();
final WebResource webResource = client.resource(serverURL+"/crashLogs/myfile.crash");
String crashContent = null;
try {
crashContent = readFile("ios.crash");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, crashContent);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output for create request .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
assert (response.getStatus() == HttpStatus.SC_OK);
}
public void testGetRawLogData() {
}
private String readFile( String file ) throws IOException {
BufferedReader reader = new BufferedReader( new InputStreamReader(getClass().getClassLoader().getResourceAsStream(file)));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
reader.close();
return stringBuilder.toString();
}
public void testGetAppWithEverythingInIt() throws JsonGenerationException, JsonMappingException, IOException {
App app = new App();
app.setInstaOpsApplicationId(235L);
app.setOrgName("prabhat-org");
app.setAppName("prabhat-app");
app.setOrganizationUUID(UUID.randomUUID().toString());
app.setApplicationUUID(UUID.randomUUID().toString());
app.setAppleId(UUID.randomUUID().toString());
app.setApplicationUUID(UUID.randomUUID().toString());
app.setAppName("App with Everything In It");
app.setAppOwner("Mr. Jha");
app.setCreatedDate(new Date());
app.setDeleted(Boolean.FALSE);
app.setDescription("App with all fields populated so that UI JSON parsing can be tested");
app.setEnvironment("prabhat-test");
app.setGoogleId(UUID.randomUUID().toString());
ApplicationConfigurationModel defaultConfig = new ApplicationConfigurationModel();
defaultConfig.setAgentUploadIntervalInSeconds(60L);
defaultConfig.setAppConfigType(ApigeeMobileAPMConstants.CONFIG_TYPE_DEFAULT);
defaultConfig.setDeviceIdCaptureEnabled(Boolean.TRUE);
defaultConfig.setDeviceModelCaptureEnabled(Boolean.TRUE);
defaultConfig.setEnableLogMonitoring(Boolean.TRUE);
defaultConfig.setEnableUploadWhenMobile(Boolean.TRUE);
defaultConfig.setEnableUploadWhenRoaming(Boolean.FALSE);
defaultConfig.setLogLevelToMonitor(ApigeeMobileAPMConstants.LOG_INFO);
defaultConfig.setSamplingRate(100L);
defaultConfig.setSessionDataCaptureEnabled(Boolean.TRUE);
Set<AppConfigCustomParameter> customParameters = new HashSet<AppConfigCustomParameter>();
customParameters.add(new AppConfigCustomParameter("UI", "ENABLE_SCROLLING", "TRUE"));
customParameters.add(new AppConfigCustomParameter("NETWORK", "OPEN_REST_URL", "http://myopenserver.com/v1"));
defaultConfig.setCustomConfigParameters(customParameters);
app.setDefaultAppConfig(defaultConfig);
Set<AppConfigOverrideFilter> deviceIdFilters = new HashSet<AppConfigOverrideFilter>();
deviceIdFilters.add(new AppConfigOverrideFilter(UUID.randomUUID().toString(), ApigeeMobileAPMConstants.FILTER_TYPE_DEVICE_ID));
deviceIdFilters.add(new AppConfigOverrideFilter(UUID.randomUUID().toString(), ApigeeMobileAPMConstants.FILTER_TYPE_DEVICE_ID));
app.setDeviceIdFilters(deviceIdFilters);
Set<AppConfigOverrideFilter> deviceNumberFilters = new HashSet<AppConfigOverrideFilter>();
deviceNumberFilters.add(new AppConfigOverrideFilter("512-111-222", ApigeeMobileAPMConstants.FILTER_TYPE_DEVICE_NUMBER));
deviceNumberFilters.add(new AppConfigOverrideFilter("512-222-333", ApigeeMobileAPMConstants.FILTER_TYPE_DEVICE_NUMBER));
app.setDeviceNumberFilters(deviceNumberFilters);
app.setABTestingPercentage(50);
String json = new ObjectMapper().writeValueAsString(app);
System.out.println(json);
}
public void testGetDomain () throws URISyntaxException {
String url = "http://ws.spotify.com/search/1/artist?q=zz top";
url = url.substring(0,url.indexOf('?'));
String domain = new URI(url).getHost();
System.out.println (domain);
}
}
| apache-2.0 |
vlucenco/java_learn | mantis-tests/src/test/java/ru/vitali/pft/mantis/model/Issue.java | 756 | package ru.vitali.pft.mantis.model;
public class Issue {
private int id;
private String summary;
private String description;
private Project project;
public int getId() {
return id;
}
public Issue withId(int id) {
this.id = id;
return this;
}
public String getSummary() {
return summary;
}
public Issue withSummary(String summary) {
this.summary = summary;
return this;
}
public String getDescription() {
return description;
}
public Issue withDescription(String description) {
this.description = description;
return this;
}
public Project getProject() {
return project;
}
public Issue withProject(Project project) {
this.project = project;
return this;
}
}
| apache-2.0 |
songzhw/AndroidArchitecture | deprecated/Modularity/common/src/test/java/ca/six/common/ExampleUnitTest.java | 391 | package ca.six.common;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/FailedCreateAssociationMarshaller.java | 2664 | /*
* Copyright 2012-2017 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.simplesystemsmanagement.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* FailedCreateAssociationMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class FailedCreateAssociationMarshaller {
private static final MarshallingInfo<StructuredPojo> ENTRY_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Entry").build();
private static final MarshallingInfo<String> MESSAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Message").build();
private static final MarshallingInfo<String> FAULT_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Fault").build();
private static final FailedCreateAssociationMarshaller instance = new FailedCreateAssociationMarshaller();
public static FailedCreateAssociationMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(FailedCreateAssociation failedCreateAssociation, ProtocolMarshaller protocolMarshaller) {
if (failedCreateAssociation == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(failedCreateAssociation.getEntry(), ENTRY_BINDING);
protocolMarshaller.marshall(failedCreateAssociation.getMessage(), MESSAGE_BINDING);
protocolMarshaller.marshall(failedCreateAssociation.getFault(), FAULT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
zuoweitan/Hitalk | app/src/main/java/com/vivifram/second/hitalk/wheelview/graphics/HoloDrawable.java | 2174 | /*
* Copyright (C) 2016 venshine.cn@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vivifram.second.hitalk.wheelview.graphics;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.vivifram.second.hitalk.wheelview.common.WheelConstants;
import com.vivifram.second.hitalk.wheelview.widget.WheelView;
/**
* holo滚轮样式
*
* @author venshine
*/
public class HoloDrawable extends WheelDrawable {
private Paint mHoloBgPaint, mHoloPaint;
private int mWheelSize, mItemH;
public HoloDrawable(int width, int height, WheelView.WheelViewStyle style, int wheelSize, int itemH) {
super(width, height, style);
mWheelSize = wheelSize;
mItemH = itemH;
init();
}
private void init() {
mHoloBgPaint = new Paint();
mHoloBgPaint.setColor(mStyle.backgroundColor != -1 ? mStyle.backgroundColor : WheelConstants
.WHEEL_SKIN_HOLO_BG);
mHoloPaint = new Paint();
mHoloPaint.setStrokeWidth(3);
mHoloPaint.setColor(mStyle.holoBorderColor != -1 ? mStyle.holoBorderColor : WheelConstants
.WHEEL_SKIN_HOLO_BORDER_COLOR);
}
@Override
public void draw(Canvas canvas) {
// draw background
canvas.drawRect(0, 0, mWidth, mHeight, mHoloBgPaint);
// draw select border
if (mItemH != 0) {
canvas.drawLine(0, mItemH * (mWheelSize / 2), mWidth, mItemH
* (mWheelSize / 2), mHoloPaint);
canvas.drawLine(0, mItemH * (mWheelSize / 2 + 1), mWidth, mItemH
* (mWheelSize / 2 + 1), mHoloPaint);
}
}
}
| apache-2.0 |
spring-projects/spring-data-examples | jpa/deferred/src/main/java/example/model/Customer675.java | 624 | package example.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer675 {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private long id;
private String firstName;
private String lastName;
protected Customer675() {}
public Customer675(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format("Customer675[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
}
}
| apache-2.0 |
gitzxon/MyLocker | angyourlocker/src/com/zxon/angyourlocker/receiver/AdminReceiver.java | 879 | package com.zxon.angyourlocker.receiver;
import android.app.admin.DeviceAdminReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class AdminReceiver extends DeviceAdminReceiver{
@Override
public void onDisabled(Context context, Intent intent) {
Toast.makeText(context, "AngYourLocker Device Admin Disabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onEnabled(Context context, Intent intent) {
Toast.makeText(context, "AngYourLocker Device Admin is now enabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d("debug_ang", "MyDevicePolicyReciever Received: " + intent.getAction());
super.onReceive(context, intent);
}
}
| apache-2.0 |
goodwinnk/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUtil.java | 55785 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.util;
import com.intellij.build.BuildConsoleUtils;
import com.intellij.build.BuildContentDescriptor;
import com.intellij.build.DefaultBuildDescriptor;
import com.intellij.build.SyncViewManager;
import com.intellij.build.events.BuildEvent;
import com.intellij.build.events.EventResult;
import com.intellij.build.events.FinishBuildEvent;
import com.intellij.build.events.impl.FailureImpl;
import com.intellij.build.events.impl.FailureResultImpl;
import com.intellij.build.events.impl.SkippedResultImpl;
import com.intellij.build.events.impl.SuccessResultImpl;
import com.intellij.build.events.impl.*;
import com.intellij.build.output.BuildOutputInstantReaderImpl;
import com.intellij.build.output.BuildOutputParser;
import com.intellij.execution.*;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.executors.DefaultDebugExecutor;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ProcessOutputTypes;
import com.intellij.execution.rmi.RemoteUtil;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ProgramRunner;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.icons.AllIcons;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationGroup;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.externalSystem.ExternalSystemManager;
import com.intellij.openapi.externalSystem.execution.ExternalSystemExecutionConsoleManager;
import com.intellij.openapi.externalSystem.importing.ImportSpec;
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder;
import com.intellij.openapi.externalSystem.model.*;
import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings;
import com.intellij.openapi.externalSystem.model.project.ProjectData;
import com.intellij.openapi.externalSystem.model.task.*;
import com.intellij.openapi.externalSystem.model.task.event.*;
import com.intellij.openapi.externalSystem.service.ImportCanceledException;
import com.intellij.openapi.externalSystem.service.execution.*;
import com.intellij.openapi.externalSystem.service.internal.ExternalSystemProcessingManager;
import com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask;
import com.intellij.openapi.externalSystem.service.notification.ExternalSystemNotificationManager;
import com.intellij.openapi.externalSystem.service.notification.NotificationData;
import com.intellij.openapi.externalSystem.service.notification.NotificationSource;
import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback;
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager;
import com.intellij.openapi.externalSystem.service.project.manage.ContentRootDataService;
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl;
import com.intellij.openapi.externalSystem.service.project.manage.ExternalSystemTaskActivator;
import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataManagerImpl;
import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemLocalSettings;
import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings;
import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings;
import com.intellij.openapi.externalSystem.task.TaskCallback;
import com.intellij.openapi.externalSystem.view.ExternalProjectsView;
import com.intellij.openapi.externalSystem.view.ExternalProjectsViewImpl;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.progress.PerformInBackgroundOption;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.StandardFileSystems;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowEP;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.ex.ProgressIndicatorEx;
import com.intellij.openapi.wm.ex.ToolWindowManagerEx;
import com.intellij.openapi.wm.impl.ToolWindowImpl;
import com.intellij.pom.Navigatable;
import com.intellij.pom.NonNavigatable;
import com.intellij.util.*;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.containers.ContainerUtilRt;
import gnu.trove.TObjectHashingStrategy;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import static com.intellij.openapi.externalSystem.settings.AbstractExternalSystemLocalSettings.SyncType.*;
import static com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.doWriteAction;
import static com.intellij.util.containers.ContainerUtil.list;
/**
* @author Denis Zhdanov
* @since 4/22/13 9:36 AM
*/
public class ExternalSystemUtil {
@NotNull public static final Key<ExternalSystemTaskId> EXTERNAL_SYSTEM_TASK_ID_KEY =
Key.create("com.intellij.openapi.externalSystem.util.taskId");
private static final Logger LOG = Logger.getInstance(ExternalSystemUtil.class);
@NotNull private static final Map<String, String> RUNNER_IDS = ContainerUtilRt.newHashMap();
public static final TObjectHashingStrategy<Pair<ProjectSystemId, File>> HASHING_STRATEGY =
new TObjectHashingStrategy<Pair<ProjectSystemId, File>>() {
@Override
public int computeHashCode(Pair<ProjectSystemId, File> object) {
return object.first.hashCode() + fileHashCode(object.second);
}
@Override
public boolean equals(Pair<ProjectSystemId, File> o1, Pair<ProjectSystemId, File> o2) {
return o1.first.equals(o2.first) && filesEqual(o1.second, o2.second);
}
};
static {
RUNNER_IDS.put(DefaultRunExecutor.EXECUTOR_ID, ExternalSystemConstants.RUNNER_ID);
RUNNER_IDS.put(DefaultDebugExecutor.EXECUTOR_ID, ExternalSystemConstants.DEBUG_RUNNER_ID);
}
private ExternalSystemUtil() {
}
public static int fileHashCode(@Nullable File file) {
int hash;
try {
hash = FileUtil.pathHashCode(file == null ? null : file.getCanonicalPath());
}
catch (IOException e) {
LOG.warn("unable to get canonical file path", e);
hash = FileUtil.fileHashCode(file);
}
return hash;
}
public static boolean filesEqual(@Nullable File file1, @Nullable File file2) {
try {
return FileUtil.pathsEqual(file1 == null ? null : file1.getCanonicalPath(), file2 == null ? null : file2.getCanonicalPath());
}
catch (IOException e) {
LOG.warn("unable to get canonical file path", e);
}
return FileUtil.filesEqual(file1, file2);
}
public static void ensureToolWindowInitialized(@NotNull Project project, @NotNull ProjectSystemId externalSystemId) {
try {
ToolWindowManager manager = ToolWindowManager.getInstance(project);
if (!(manager instanceof ToolWindowManagerEx)) {
return;
}
ToolWindowManagerEx managerEx = (ToolWindowManagerEx)manager;
String id = externalSystemId.getReadableName();
ToolWindow window = manager.getToolWindow(id);
if (window != null) {
return;
}
ToolWindowEP[] beans = Extensions.getExtensions(ToolWindowEP.EP_NAME);
for (final ToolWindowEP bean : beans) {
if (id.equals(bean.id)) {
managerEx.initToolWindow(bean);
}
}
}
catch (Exception e) {
LOG.error(String.format("Unable to initialize %s tool window", externalSystemId.getReadableName()), e);
}
}
@Nullable
public static ToolWindow ensureToolWindowContentInitialized(@NotNull Project project, @NotNull ProjectSystemId externalSystemId) {
final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
if (toolWindowManager == null) return null;
final ToolWindow toolWindow = toolWindowManager.getToolWindow(externalSystemId.getReadableName());
if (toolWindow == null) return null;
if (toolWindow instanceof ToolWindowImpl) {
((ToolWindowImpl)toolWindow).ensureContentInitialized();
}
return toolWindow;
}
/**
* Asks to refresh all external projects of the target external system linked to the given ide project.
* <p/>
* 'Refresh' here means 'obtain the most up-to-date version and apply it to the ide'.
*
* @param project target ide project
* @param externalSystemId target external system which projects should be refreshed
* @param force flag which defines if external project refresh should be performed if it's config is up-to-date
* @deprecated use {@link ExternalSystemUtil#refreshProjects(ImportSpecBuilder)}
*/
@Deprecated
public static void refreshProjects(@NotNull final Project project, @NotNull final ProjectSystemId externalSystemId, boolean force) {
refreshProjects(project, externalSystemId, force, ProgressExecutionMode.IN_BACKGROUND_ASYNC);
}
/**
* Asks to refresh all external projects of the target external system linked to the given ide project.
* <p/>
* 'Refresh' here means 'obtain the most up-to-date version and apply it to the ide'.
*
* @param project target ide project
* @param externalSystemId target external system which projects should be refreshed
* @param force flag which defines if external project refresh should be performed if it's config is up-to-date
* @deprecated use {@link ExternalSystemUtil#refreshProjects(ImportSpecBuilder)}
*/
@Deprecated
public static void refreshProjects(@NotNull final Project project,
@NotNull final ProjectSystemId externalSystemId,
boolean force,
@NotNull final ProgressExecutionMode progressExecutionMode) {
refreshProjects(
new ImportSpecBuilder(project, externalSystemId)
.forceWhenUptodate(force)
.use(progressExecutionMode)
);
}
/**
* Asks to refresh all external projects of the target external system linked to the given ide project based on provided spec
*
* @param specBuilder import specification builder
*/
public static void refreshProjects(@NotNull final ImportSpecBuilder specBuilder) {
refreshProjects(specBuilder.build());
}
/**
* Asks to refresh all external projects of the target external system linked to the given ide project based on provided spec
*
* @param spec import specification
*/
public static void refreshProjects(@NotNull final ImportSpec spec) {
ExternalSystemManager<?, ?, ?, ?, ?> manager = ExternalSystemApiUtil.getManager(spec.getExternalSystemId());
if (manager == null) {
return;
}
AbstractExternalSystemSettings<?, ?, ?> settings = manager.getSettingsProvider().fun(spec.getProject());
final Collection<? extends ExternalProjectSettings> projectsSettings = settings.getLinkedProjectsSettings();
if (projectsSettings.isEmpty()) {
return;
}
final ExternalProjectRefreshCallback callback;
if (spec.getCallback() == null) {
callback = new MyMultiExternalProjectRefreshCallback(spec.getProject());
}
else {
callback = spec.getCallback();
}
Set<String> toRefresh = ContainerUtilRt.newHashSet();
for (ExternalProjectSettings setting : projectsSettings) {
// don't refresh project when auto-import is disabled if such behavior needed (e.g. on project opening when auto-import is disabled)
if (!setting.isUseAutoImport() && spec.whenAutoImportEnabled()) continue;
toRefresh.add(setting.getExternalProjectPath());
}
if (!toRefresh.isEmpty()) {
ExternalSystemNotificationManager.getInstance(spec.getProject())
.clearNotifications(null, NotificationSource.PROJECT_SYNC, spec.getExternalSystemId());
for (String path : toRefresh) {
refreshProject(path, new ImportSpecBuilder(spec).callback(callback).build());
}
}
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Nullable
private static String extractDetails(@NotNull Throwable e) {
final Throwable unwrapped = RemoteUtil.unwrap(e);
if (unwrapped instanceof ExternalSystemException) {
return ((ExternalSystemException)unwrapped).getOriginalReason();
}
return null;
}
public static void refreshProject(@NotNull final Project project,
@NotNull final ProjectSystemId externalSystemId,
@NotNull final String externalProjectPath,
final boolean isPreviewMode,
@NotNull final ProgressExecutionMode progressExecutionMode) {
refreshProject(project, externalSystemId, externalProjectPath, new ExternalProjectRefreshCallback() {
@Override
public void onSuccess(@Nullable final DataNode<ProjectData> externalProject) {
if (externalProject == null) {
return;
}
final boolean synchronous = progressExecutionMode == ProgressExecutionMode.MODAL_SYNC;
ServiceManager.getService(ProjectDataManager.class).importData(externalProject, project, synchronous);
}
}, isPreviewMode, progressExecutionMode, true);
}
/**
* TODO[Vlad]: refactor the method to use {@link ImportSpecBuilder}
* <p>
* Queries slave gradle process to refresh target gradle project.
*
* @param project target intellij project to use
* @param externalProjectPath path of the target gradle project's file
* @param callback callback to be notified on refresh result
* @param isPreviewMode flag that identifies whether gradle libraries should be resolved during the refresh
* @return the most up-to-date gradle project (if any)
*/
public static void refreshProject(@NotNull final Project project,
@NotNull final ProjectSystemId externalSystemId,
@NotNull final String externalProjectPath,
@NotNull final ExternalProjectRefreshCallback callback,
final boolean isPreviewMode,
@NotNull final ProgressExecutionMode progressExecutionMode) {
refreshProject(project, externalSystemId, externalProjectPath, callback, isPreviewMode, progressExecutionMode, true);
}
/**
* <p>
* Refresh target gradle project.
*
* @param project target intellij project to use
* @param externalProjectPath path of the target external project
* @param callback callback to be notified on refresh result
* @param isPreviewMode flag that identifies whether libraries should be resolved during the refresh
* @param reportRefreshError prevent to show annoying error notification, e.g. if auto-import mode used
*/
public static void refreshProject(@NotNull final Project project,
@NotNull final ProjectSystemId externalSystemId,
@NotNull final String externalProjectPath,
@NotNull final ExternalProjectRefreshCallback callback,
final boolean isPreviewMode,
@NotNull final ProgressExecutionMode progressExecutionMode,
final boolean reportRefreshError) {
ImportSpecBuilder builder = new ImportSpecBuilder(project, externalSystemId).callback(callback).use(progressExecutionMode);
if (isPreviewMode) builder.usePreviewMode();
if (!reportRefreshError) builder.dontReportRefreshErrors();
refreshProject(externalProjectPath, builder.build());
}
public static void refreshProject(@NotNull final String externalProjectPath, @NotNull final ImportSpec importSpec) {
Project project = importSpec.getProject();
ProjectSystemId externalSystemId = importSpec.getExternalSystemId();
ExternalProjectRefreshCallback callback = importSpec.getCallback();
boolean isPreviewMode = importSpec.isPreviewMode();
ProgressExecutionMode progressExecutionMode = importSpec.getProgressExecutionMode();
boolean reportRefreshError = importSpec.isReportRefreshError();
String arguments = importSpec.getArguments();
String vmOptions = importSpec.getVmOptions();
File projectFile = new File(externalProjectPath);
final String projectName;
if (projectFile.isFile()) {
projectName = projectFile.getParentFile().getName();
}
else {
projectName = projectFile.getName();
}
AbstractExternalSystemLocalSettings localSettings = ExternalSystemApiUtil.getLocalSettings(project, externalSystemId);
AbstractExternalSystemLocalSettings.SyncType syncType =
isPreviewMode ? PREVIEW :
localSettings.getProjectSyncType().get(externalProjectPath) == PREVIEW ? IMPORT : RE_IMPORT;
localSettings.getProjectSyncType().put(externalProjectPath, syncType);
final ExternalSystemResolveProjectTask resolveProjectTask =
new ExternalSystemResolveProjectTask(externalSystemId, project, externalProjectPath, vmOptions, arguments, isPreviewMode);
final TaskUnderProgress refreshProjectStructureTask = new TaskUnderProgress() {
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "IOResourceOpenedButNotSafelyClosed"})
@Override
public void execute(@NotNull ProgressIndicator indicator) {
if (project.isDisposed()) return;
if (indicator instanceof ProgressIndicatorEx) {
((ProgressIndicatorEx)indicator).addStateDelegate(new AbstractProgressIndicatorExBase() {
@Override
public void cancel() {
super.cancel();
cancelImport();
}
});
}
ExternalSystemProcessingManager processingManager = ServiceManager.getService(ExternalSystemProcessingManager.class);
if (processingManager.findTask(ExternalSystemTaskType.RESOLVE_PROJECT, externalSystemId, externalProjectPath) != null) {
if (callback != null) {
callback.onFailure(resolveProjectTask.getId(), ExternalSystemBundle.message("error.resolve.already.running", externalProjectPath), null);
}
return;
}
if (!(callback instanceof MyMultiExternalProjectRefreshCallback)) {
ExternalSystemNotificationManager.getInstance(project)
.clearNotifications(null, NotificationSource.PROJECT_SYNC, externalSystemId);
}
final ExternalSystemTaskActivator externalSystemTaskActivator = ExternalProjectsManagerImpl.getInstance(project).getTaskActivator();
if (!isPreviewMode && !externalSystemTaskActivator.runTasks(externalProjectPath, ExternalSystemTaskActivator.Phase.BEFORE_SYNC)) {
return;
}
final ExternalSystemProcessHandler processHandler = new ExternalSystemProcessHandler(resolveProjectTask, projectName + " import") {
@Override
protected void destroyProcessImpl() {
cancelImport();
closeInput();
}
};
final ExternalSystemExecutionConsoleManager<ExternalSystemRunConfiguration, ExecutionConsole, ProcessHandler>
consoleManager = getConsoleManagerFor(resolveProjectTask);
final ExecutionConsole consoleView =
consoleManager.attachExecutionConsole(project, resolveProjectTask, null, processHandler);
if (consoleView != null) {
Disposer.register(project, consoleView);
}
else {
Disposer.register(project, processHandler);
}
List<BuildOutputParser> buildOutputParsers = new SmartList<>();
for (ExternalSystemOutputParserProvider outputParserProvider : ExternalSystemOutputParserProvider.EP_NAME.getExtensions()) {
if (resolveProjectTask.getExternalSystemId().equals(outputParserProvider.getExternalSystemId())) {
buildOutputParsers.addAll(outputParserProvider.getBuildOutputParsers(resolveProjectTask));
}
}
//noinspection IOResourceOpenedButNotSafelyClosed
final BuildOutputInstantReaderImpl buildOutputInstantReader =
buildOutputParsers.isEmpty() ? null : new BuildOutputInstantReaderImpl(
resolveProjectTask.getId(), ServiceManager.getService(project, SyncViewManager.class), buildOutputParsers);
Ref<Supplier<FinishBuildEvent>> finishSyncEventSupplier = Ref.create();
ExternalSystemTaskNotificationListenerAdapter taskListener = new ExternalSystemTaskNotificationListenerAdapter() {
@Override
public void onStart(@NotNull ExternalSystemTaskId id, String workingDir) {
long eventTime = System.currentTimeMillis();
AnAction rerunImportAction = new AnAction() {
@Override
public void update(@NotNull AnActionEvent e) {
super.update(e);
Presentation p = e.getPresentation();
p.setEnabled(processHandler.isProcessTerminated());
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Presentation p = e.getPresentation();
p.setEnabled(false);
refreshProject(externalProjectPath, importSpec);
}
};
String systemId = id.getProjectSystemId().getReadableName();
rerunImportAction.getTemplatePresentation().setText(ExternalSystemBundle.message("action.refresh.project.text", systemId));
rerunImportAction.getTemplatePresentation()
.setDescription(ExternalSystemBundle.message("action.refresh.project.description", systemId));
rerunImportAction.getTemplatePresentation().setIcon(AllIcons.Actions.Refresh);
if(isPreviewMode) return;
String message = "syncing...";
ServiceManager.getService(project, SyncViewManager.class).onEvent(
new StartBuildEventImpl(new DefaultBuildDescriptor(id, projectName, externalProjectPath, eventTime), message)
.withProcessHandler(processHandler, null)
.withRestartAction(rerunImportAction)
.withContentDescriptorSupplier(() -> {
if (consoleView == null) {
return null;
}
else {
boolean activateToolWindow = isNewProject(project);
BuildContentDescriptor contentDescriptor = new BuildContentDescriptor(
consoleView, processHandler, consoleView.getComponent(), "Sync");
contentDescriptor.setActivateToolWindowWhenAdded(activateToolWindow);
contentDescriptor.setActivateToolWindowWhenFailed(reportRefreshError);
contentDescriptor.setAutoFocusContent(reportRefreshError);
return contentDescriptor;
}
})
);
}
@Override
public void onTaskOutput(@NotNull ExternalSystemTaskId id, @NotNull String text, boolean stdOut) {
processHandler.notifyTextAvailable(text, stdOut ? ProcessOutputTypes.STDOUT : ProcessOutputTypes.STDERR);
if (buildOutputInstantReader != null) {
buildOutputInstantReader.append(text);
}
}
@Override
public void onFailure(@NotNull ExternalSystemTaskId id, @NotNull Exception e) {
String title = ExternalSystemBundle.message("notification.project.refresh.fail.title",
externalSystemId.getReadableName(), projectName);
com.intellij.build.events.FailureResult failureResult = createFailureResult(title, e, externalSystemId, project);
String message = isPreviewMode ? "project preview creation failed" : "sync failed";
finishSyncEventSupplier.set(
() -> new FinishBuildEventImpl(id, null, System.currentTimeMillis(), message, failureResult));
printFailure(e, failureResult, consoleView, processHandler);
processHandler.notifyProcessTerminated(1);
}
@Override
public void onSuccess(@NotNull ExternalSystemTaskId id) {
String message = isPreviewMode ? "project preview created" : "sync finished";
finishSyncEventSupplier.set(
() -> new FinishBuildEventImpl(id, null, System.currentTimeMillis(), message, new SuccessResultImpl()));
processHandler.notifyProcessTerminated(0);
}
@Override
public void onStatusChange(@NotNull ExternalSystemTaskNotificationEvent event) {
if (!isPreviewMode && event instanceof ExternalSystemTaskExecutionEvent) {
BuildEvent buildEvent = convert(((ExternalSystemTaskExecutionEvent)event));
ServiceManager.getService(project, SyncViewManager.class).onEvent(buildEvent);
}
}
@Override
public void onEnd(@NotNull ExternalSystemTaskId id) {
if (buildOutputInstantReader != null) {
buildOutputInstantReader.close();
}
}
};
final long startTS = System.currentTimeMillis();
resolveProjectTask.execute(indicator, ArrayUtil.prepend(taskListener, ExternalSystemTaskNotificationListener.EP_NAME.getExtensions()));
LOG.info("External project [" + externalProjectPath + "] resolution task executed in " + (System.currentTimeMillis() - startTS) + " ms.");
if (project.isDisposed()) return;
try {
final Throwable error = resolveProjectTask.getError();
if (error == null) {
if (callback != null) {
final ExternalProjectInfo externalProjectData = ProjectDataManagerImpl.getInstance()
.getExternalProjectData(project, externalSystemId, externalProjectPath);
if (externalProjectData != null) {
DataNode<ProjectData> externalProject = externalProjectData.getExternalProjectStructure();
if (externalProject != null && importSpec.shouldCreateDirectoriesForEmptyContentRoots()) {
externalProject.putUserData(ContentRootDataService.CREATE_EMPTY_DIRECTORIES, Boolean.TRUE);
}
callback.onSuccess(resolveProjectTask.getId(), externalProject);
}
}
if (!isPreviewMode) {
externalSystemTaskActivator.runTasks(externalProjectPath, ExternalSystemTaskActivator.Phase.AFTER_SYNC);
}
return;
}
if (error instanceof ImportCanceledException) {
// stop refresh task
return;
}
String message = ExternalSystemApiUtil.buildErrorMessage(error);
if (StringUtil.isEmpty(message)) {
message = String.format(
"Can't resolve %s project at '%s'. Reason: %s", externalSystemId.getReadableName(), externalProjectPath, message
);
}
if (callback != null) {
callback.onFailure(resolveProjectTask.getId(), message, extractDetails(error));
}
}
finally {
if (!isPreviewMode) {
boolean isNewProject = isNewProject(project);
if(isNewProject) {
VirtualFile virtualFile = VfsUtil.findFileByIoFile(projectFile, false);
if (virtualFile != null) {
VfsUtil.markDirtyAndRefresh(true, false, true, virtualFile);
}
}
project.putUserData(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT, null);
project.putUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT, null);
sendSyncFinishEvent(finishSyncEventSupplier);
}
}
}
private void sendSyncFinishEvent(@NotNull Ref<? extends Supplier<FinishBuildEvent>> finishSyncEventSupplier) {
Exception exception = null;
FinishBuildEvent finishBuildEvent = null;
Supplier<FinishBuildEvent> finishBuildEventSupplier = finishSyncEventSupplier.get();
if (finishBuildEventSupplier != null) {
try {
finishBuildEvent = finishBuildEventSupplier.get();
}
catch (Exception e) {
exception = e;
}
}
if (finishBuildEvent != null) {
ServiceManager.getService(project, SyncViewManager.class).onEvent(finishBuildEvent);
}
else {
String message = "Sync finish event has not been received";
LOG.warn(message, exception);
ServiceManager.getService(project, SyncViewManager.class).onEvent(
new FinishBuildEventImpl(resolveProjectTask.getId(), null, System.currentTimeMillis(), "sync failed",
new FailureResultImpl(new Exception(message, exception))));
}
}
private void cancelImport() {
resolveProjectTask.cancel(ExternalSystemTaskNotificationListener.EP_NAME.getExtensions());
}
};
TransactionGuard.getInstance().assertWriteSafeContext(ModalityState.defaultModalityState());
ApplicationManager.getApplication().invokeAndWait(FileDocumentManager.getInstance()::saveAllDocuments);
final String title;
switch (progressExecutionMode) {
case NO_PROGRESS_SYNC:
case NO_PROGRESS_ASYNC:
throw new ExternalSystemException("Please, use progress for the project import!");
case MODAL_SYNC:
title = ExternalSystemBundle.message("progress.import.text", projectName, externalSystemId.getReadableName());
new Task.Modal(project, title, true) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
refreshProjectStructureTask.execute(indicator);
}
}.queue();
break;
case IN_BACKGROUND_ASYNC:
title = ExternalSystemBundle.message("progress.refresh.text", projectName, externalSystemId.getReadableName());
new Task.Backgroundable(project, title) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
refreshProjectStructureTask.execute(indicator);
}
}.queue();
break;
case START_IN_FOREGROUND_ASYNC:
title = ExternalSystemBundle.message("progress.refresh.text", projectName, externalSystemId.getReadableName());
new Task.Backgroundable(project, title, true, PerformInBackgroundOption.DEAF) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
refreshProjectStructureTask.execute(indicator);
}
}.queue();
}
}
public static boolean isNewProject(Project project) {
return project.getUserData(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT) == Boolean.TRUE ||
project.getUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT) == Boolean.TRUE;
}
public static void printFailure(@NotNull Exception e,
com.intellij.build.events.FailureResult failureResult,
ExecutionConsole consoleView,
ExternalSystemProcessHandler processHandler) {
if (consoleView instanceof ConsoleView) {
for (com.intellij.build.events.Failure failure : failureResult.getFailures()) {
BuildConsoleUtils.printDetails((ConsoleView)consoleView, failure);
}
}
else {
String exceptionMessage = ExceptionUtil.getMessage(e);
String text = exceptionMessage == null ? e.toString() : exceptionMessage;
processHandler.notifyTextAvailable(text + '\n', ProcessOutputTypes.STDERR);
}
}
@NotNull
public static FailureResultImpl createFailureResult(@NotNull String title,
@NotNull Exception exception,
@NotNull ProjectSystemId externalSystemId,
@NotNull Project project) {
ExternalSystemNotificationManager notificationManager = ExternalSystemNotificationManager.getInstance(project);
NotificationData notificationData = notificationManager.createNotification(title, exception, externalSystemId, project);
return createFailureResult(exception, externalSystemId, project, notificationManager, notificationData);
}
@NotNull
private static FailureResultImpl createFailureResult(@NotNull Exception exception,
@NotNull ProjectSystemId externalSystemId,
@NotNull Project project,
@NotNull ExternalSystemNotificationManager notificationManager,
@NotNull NotificationData notificationData) {
if (notificationData.isBalloonNotification()) {
notificationManager.showNotification(externalSystemId, notificationData);
return new FailureResultImpl(exception);
}
NotificationGroup group;
if (notificationData.getBalloonGroup() == null) {
ExternalProjectsView externalProjectsView =
ExternalProjectsManagerImpl.getInstance(project).getExternalProjectsView(externalSystemId);
group = externalProjectsView instanceof ExternalProjectsViewImpl ?
((ExternalProjectsViewImpl)externalProjectsView).getNotificationGroup() : null;
}
else {
final NotificationGroup registeredGroup = NotificationGroup.findRegisteredGroup(notificationData.getBalloonGroup());
group = registeredGroup != null ? registeredGroup : NotificationGroup.balloonGroup(notificationData.getBalloonGroup());
}
int line = notificationData.getLine() - 1;
int column = notificationData.getColumn() - 1;
final VirtualFile virtualFile =
notificationData.getFilePath() != null ? findLocalFileByPath(notificationData.getFilePath()) : null;
final Navigatable navigatable;
if (notificationData.getNavigatable() == null || notificationData.getNavigatable() instanceof NonNavigatable) {
navigatable = virtualFile != null ? new OpenFileDescriptor(project, virtualFile, line, column) : NonNavigatable.INSTANCE;
}
else {
navigatable = notificationData.getNavigatable();
}
final Notification notification;
if (group == null) {
notification = new Notification(externalSystemId.getReadableName() + " build", notificationData.getTitle(),
notificationData.getMessage(),
notificationData.getNotificationCategory().getNotificationType(),
notificationData.getListener());
}
else {
notification = group.createNotification(
notificationData.getTitle(), notificationData.getMessage(),
notificationData.getNotificationCategory().getNotificationType(), notificationData.getListener());
}
return new FailureResultImpl(list(new FailureImpl(notificationData.getMessage(), exception, notification, navigatable)));
}
public static BuildEvent convert(ExternalSystemTaskExecutionEvent taskExecutionEvent) {
ExternalSystemProgressEvent progressEvent = taskExecutionEvent.getProgressEvent();
String displayName = progressEvent.getDescriptor().getDisplayName();
long eventTime = progressEvent.getDescriptor().getEventTime();
Object parentEventId = ObjectUtils.chooseNotNull(progressEvent.getParentEventId(), taskExecutionEvent.getId());
AbstractBuildEvent buildEvent;
if (progressEvent instanceof ExternalSystemStartEvent) {
buildEvent = new StartEventImpl(progressEvent.getEventId(), parentEventId, eventTime, displayName);
}
else if (progressEvent instanceof ExternalSystemFinishEvent) {
final EventResult eventResult;
final OperationResult operationResult = ((ExternalSystemFinishEvent)progressEvent).getOperationResult();
if (operationResult instanceof FailureResult) {
List<com.intellij.build.events.Failure> failures = new SmartList<>();
for (Failure failure : ((FailureResult)operationResult).getFailures()) {
failures.add(convert(failure));
}
eventResult = new FailureResultImpl(failures);
}
else if (operationResult instanceof SkippedResult) {
eventResult = new SkippedResultImpl();
}
else if (operationResult instanceof SuccessResult) {
eventResult = new SuccessResultImpl(((SuccessResult)operationResult).isUpToDate());
}
else {
eventResult = new SuccessResultImpl();
}
buildEvent = new FinishEventImpl(progressEvent.getEventId(), parentEventId, eventTime, displayName, eventResult);
}
else if (progressEvent instanceof ExternalSystemStatusEvent) {
ExternalSystemStatusEvent statusEvent = (ExternalSystemStatusEvent)progressEvent;
buildEvent = new ProgressBuildEventImpl(progressEvent.getEventId(), parentEventId, eventTime, displayName,
statusEvent.getTotal(), statusEvent.getProgress(), statusEvent.getUnit());
}
else {
buildEvent = new OutputBuildEventImpl(progressEvent.getEventId(), parentEventId, displayName, true);
}
String hint = progressEvent.getDescriptor().getHint();
buildEvent.setHint(hint);
return buildEvent;
}
private static com.intellij.build.events.Failure convert(Failure failure) {
List<com.intellij.build.events.Failure> causes = new SmartList<>();
for (Failure cause : failure.getCauses()) {
causes.add(convert(cause));
}
return new FailureImpl(failure.getMessage(), failure.getDescription(), causes);
}
public static void runTask(@NotNull ExternalSystemTaskExecutionSettings taskSettings,
@NotNull String executorId,
@NotNull Project project,
@NotNull ProjectSystemId externalSystemId) {
runTask(taskSettings, executorId, project, externalSystemId, null, ProgressExecutionMode.IN_BACKGROUND_ASYNC);
}
public static void runTask(@NotNull final ExternalSystemTaskExecutionSettings taskSettings,
@NotNull final String executorId,
@NotNull final Project project,
@NotNull final ProjectSystemId externalSystemId,
@Nullable final TaskCallback callback,
@NotNull final ProgressExecutionMode progressExecutionMode) {
runTask(taskSettings, executorId, project, externalSystemId, callback, progressExecutionMode, true);
}
public static void runTask(@NotNull final ExternalSystemTaskExecutionSettings taskSettings,
@NotNull final String executorId,
@NotNull final Project project,
@NotNull final ProjectSystemId externalSystemId,
@Nullable final TaskCallback callback,
@NotNull final ProgressExecutionMode progressExecutionMode,
boolean activateToolWindowBeforeRun) {
runTask(taskSettings, executorId, project, externalSystemId, callback, progressExecutionMode, activateToolWindowBeforeRun, null);
}
public static void runTask(@NotNull final ExternalSystemTaskExecutionSettings taskSettings,
@NotNull final String executorId,
@NotNull final Project project,
@NotNull final ProjectSystemId externalSystemId,
@Nullable final TaskCallback callback,
@NotNull final ProgressExecutionMode progressExecutionMode,
boolean activateToolWindowBeforeRun,
@Nullable UserDataHolderBase userData) {
ExecutionEnvironment environment = createExecutionEnvironment(project, externalSystemId, taskSettings, executorId);
if (environment == null) return;
RunnerAndConfigurationSettings runnerAndConfigurationSettings = environment.getRunnerAndConfigurationSettings();
assert runnerAndConfigurationSettings != null;
runnerAndConfigurationSettings.setActivateToolWindowBeforeRun(activateToolWindowBeforeRun);
if (userData != null) {
ExternalSystemRunConfiguration runConfiguration = (ExternalSystemRunConfiguration)runnerAndConfigurationSettings.getConfiguration();
userData.copyUserDataTo(runConfiguration);
}
final TaskUnderProgress task = new TaskUnderProgress() {
@Override
public void execute(@NotNull ProgressIndicator indicator) {
indicator.setIndeterminate(true);
final Semaphore targetDone = new Semaphore();
final Ref<Boolean> result = new Ref<>(false);
final Disposable disposable = Disposer.newDisposable();
project.getMessageBus().connect(disposable).subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionListener() {
@Override
public void processStartScheduled(@NotNull final String executorIdLocal, @NotNull final ExecutionEnvironment environmentLocal) {
if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
targetDone.down();
}
}
@Override
public void processNotStarted(@NotNull final String executorIdLocal, @NotNull final ExecutionEnvironment environmentLocal) {
if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
targetDone.up();
}
}
@Override
public void processStarted(@NotNull final String executorIdLocal,
@NotNull final ExecutionEnvironment environmentLocal,
@NotNull final ProcessHandler handler) {
if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
handler.addProcessListener(new ProcessAdapter() {
@Override
public void processTerminated(@NotNull ProcessEvent event) {
result.set(event.getExitCode() == 0);
targetDone.up();
}
});
}
}
});
try {
ApplicationManager.getApplication().invokeAndWait(() -> {
try {
environment.getRunner().execute(environment);
}
catch (ExecutionException e) {
targetDone.up();
LOG.error(e);
}
}, ModalityState.defaultModalityState());
}
catch (Exception e) {
LOG.error(e);
Disposer.dispose(disposable);
return;
}
targetDone.waitFor();
Disposer.dispose(disposable);
if (callback != null) {
if (result.get()) {
callback.onSuccess();
}
else {
callback.onFailure();
}
}
}
};
final String title = AbstractExternalSystemTaskConfigurationType.generateName(project, taskSettings);
switch (progressExecutionMode) {
case NO_PROGRESS_SYNC:
task.execute(new EmptyProgressIndicator());
break;
case MODAL_SYNC:
new Task.Modal(project, title, true) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
task.execute(indicator);
}
}.queue();
break;
case NO_PROGRESS_ASYNC:
ApplicationManager.getApplication().executeOnPooledThread(() -> task.execute(new EmptyProgressIndicator()));
break;
case IN_BACKGROUND_ASYNC:
new Task.Backgroundable(project, title) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
task.execute(indicator);
}
}.queue();
break;
case START_IN_FOREGROUND_ASYNC:
new Task.Backgroundable(project, title, true, PerformInBackgroundOption.DEAF) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
task.execute(indicator);
}
}.queue();
}
}
@Nullable
public static ExecutionEnvironment createExecutionEnvironment(@NotNull Project project,
@NotNull ProjectSystemId externalSystemId,
@NotNull ExternalSystemTaskExecutionSettings taskSettings,
@NotNull String executorId) {
Executor executor = ExecutorRegistry.getInstance().getExecutorById(executorId);
if (executor == null) return null;
String runnerId = getRunnerId(executorId);
if (runnerId == null) return null;
ProgramRunner runner = ProgramRunner.findRunnerById(runnerId);
if (runner == null) return null;
RunnerAndConfigurationSettings settings = createExternalSystemRunnerAndConfigurationSettings(taskSettings, project, externalSystemId);
if (settings == null) return null;
return new ExecutionEnvironment(executor, runner, settings, project);
}
@Nullable
public static RunnerAndConfigurationSettings createExternalSystemRunnerAndConfigurationSettings(@NotNull ExternalSystemTaskExecutionSettings taskSettings,
@NotNull Project project,
@NotNull ProjectSystemId externalSystemId) {
AbstractExternalSystemTaskConfigurationType configurationType = findConfigurationType(externalSystemId);
if (configurationType == null) {
return null;
}
String name = AbstractExternalSystemTaskConfigurationType.generateName(project, taskSettings);
RunnerAndConfigurationSettings settings = RunManager.getInstance(project).createConfiguration(name, configurationType.getFactory());
((ExternalSystemRunConfiguration)settings.getConfiguration()).getSettings().setFrom(taskSettings);
return settings;
}
@Nullable
public static AbstractExternalSystemTaskConfigurationType findConfigurationType(@NotNull ProjectSystemId externalSystemId) {
for (ConfigurationType type : ConfigurationType.CONFIGURATION_TYPE_EP.getExtensionList()) {
if (type instanceof AbstractExternalSystemTaskConfigurationType) {
AbstractExternalSystemTaskConfigurationType candidate = (AbstractExternalSystemTaskConfigurationType)type;
if (externalSystemId.equals(candidate.getExternalSystemId())) {
return candidate;
}
}
}
return null;
}
@Nullable
public static String getRunnerId(@NotNull String executorId) {
return RUNNER_IDS.get(executorId);
}
/**
* Tries to obtain external project info implied by the given settings and link that external project to the given ide project.
*
* @param externalSystemId target external system
* @param projectSettings settings of the external project to link
* @param project target ide project to link external project to
* @param executionResultCallback it might take a while to resolve external project info, that's why it's possible to provide
* a callback to be notified on processing result. It receives {@code true} if an external
* project has been successfully linked to the given ide project;
* {@code false} otherwise (note that corresponding notification with error details is expected
* to be shown to the end-user then)
* @param isPreviewMode flag which identifies if missing external project binaries should be downloaded
* @param progressExecutionMode identifies how progress bar will be represented for the current processing
*/
@SuppressWarnings("UnusedDeclaration")
public static void linkExternalProject(@NotNull final ProjectSystemId externalSystemId,
@NotNull final ExternalProjectSettings projectSettings,
@NotNull final Project project,
@Nullable final Consumer<? super Boolean> executionResultCallback,
boolean isPreviewMode,
@NotNull final ProgressExecutionMode progressExecutionMode) {
ExternalProjectRefreshCallback callback = new ExternalProjectRefreshCallback() {
@SuppressWarnings("unchecked")
@Override
public void onSuccess(@Nullable final DataNode<ProjectData> externalProject) {
if (externalProject == null) {
if (executionResultCallback != null) {
executionResultCallback.consume(false);
}
return;
}
AbstractExternalSystemSettings systemSettings = ExternalSystemApiUtil.getSettings(project, externalSystemId);
Set<ExternalProjectSettings> projects = ContainerUtilRt.newHashSet(systemSettings.getLinkedProjectsSettings());
projects.add(projectSettings);
systemSettings.setLinkedProjectsSettings(projects);
ensureToolWindowInitialized(project, externalSystemId);
ServiceManager.getService(ProjectDataManager.class).importData(externalProject, project, true);
if (executionResultCallback != null) {
executionResultCallback.consume(true);
}
}
@Override
public void onFailure(@NotNull String errorMessage, @Nullable String errorDetails) {
if (executionResultCallback != null) {
executionResultCallback.consume(false);
}
}
};
refreshProject(project, externalSystemId, projectSettings.getExternalProjectPath(), callback, isPreviewMode, progressExecutionMode);
}
@Nullable
public static VirtualFile refreshAndFindFileByIoFile(@NotNull final File file) {
final Application app = ApplicationManager.getApplication();
if (!app.isDispatchThread()) {
assert !((ApplicationEx)app).holdsReadLock();
}
return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
}
@Nullable
public static VirtualFile findLocalFileByPath(String path) {
VirtualFile result = StandardFileSystems.local().findFileByPath(path);
if (result != null) return result;
return !ApplicationManager.getApplication().isReadAccessAllowed()
? findLocalFileByPathUnderWriteAction(path)
: findLocalFileByPathUnderReadAction(path);
}
@Nullable
private static VirtualFile findLocalFileByPathUnderWriteAction(final String path) {
return doWriteAction(() -> StandardFileSystems.local().refreshAndFindFileByPath(path));
}
@Nullable
private static VirtualFile findLocalFileByPathUnderReadAction(final String path) {
return ReadAction.compute(() -> StandardFileSystems.local().findFileByPath(path));
}
public static void scheduleExternalViewStructureUpdate(@NotNull final Project project, @NotNull final ProjectSystemId systemId) {
ExternalProjectsView externalProjectsView = ExternalProjectsManagerImpl.getInstance(project).getExternalProjectsView(systemId);
if (externalProjectsView instanceof ExternalProjectsViewImpl) {
((ExternalProjectsViewImpl)externalProjectsView).scheduleStructureUpdate();
}
}
@Nullable
public static ExternalProjectInfo getExternalProjectInfo(@NotNull final Project project,
@NotNull final ProjectSystemId projectSystemId,
@NotNull final String externalProjectPath) {
final ExternalProjectSettings linkedProjectSettings =
ExternalSystemApiUtil.getSettings(project, projectSystemId).getLinkedProjectSettings(externalProjectPath);
if (linkedProjectSettings == null) return null;
return ProjectDataManagerImpl.getInstance().getExternalProjectData(
project, projectSystemId, linkedProjectSettings.getExternalProjectPath());
}
@NotNull
public static ExternalSystemExecutionConsoleManager<ExternalSystemRunConfiguration, ExecutionConsole, ProcessHandler>
getConsoleManagerFor(@NotNull ExternalSystemTask task) {
for (ExternalSystemExecutionConsoleManager executionConsoleManager : ExternalSystemExecutionConsoleManager.EP_NAME.getExtensions()) {
if (executionConsoleManager.isApplicableFor(task)) {
//noinspection unchecked
return executionConsoleManager;
}
}
return new DefaultExternalSystemExecutionConsoleManager();
}
public static void invokeLater(Project p, Runnable r) {
invokeLater(p, ModalityState.defaultModalityState(), r);
}
public static void invokeLater(final Project p, final ModalityState state, final Runnable r) {
if (isNoBackgroundMode()) {
r.run();
}
else {
ApplicationManager.getApplication().invokeLater(DisposeAwareRunnable.create(r, p), state);
}
}
public static boolean isNoBackgroundMode() {
return (ApplicationManager.getApplication().isUnitTestMode()
|| ApplicationManager.getApplication().isHeadlessEnvironment());
}
private interface TaskUnderProgress {
void execute(@NotNull ProgressIndicator indicator);
}
private static class MyMultiExternalProjectRefreshCallback implements ExternalProjectRefreshCallback {
private final Project myProject;
MyMultiExternalProjectRefreshCallback(Project project) {
myProject = project;
}
@Override
public void onSuccess(@Nullable final DataNode<ProjectData> externalProject) {
if (externalProject == null) {
return;
}
ServiceManager.getService(ProjectDataManager.class).importData(externalProject, myProject, true);
}
}
}
| apache-2.0 |
nikelin/Redshape-AS | servlet/src/main/java/com/redshape/servlet/core/SupportType.java | 787 | /*
* Copyright 2012 Cyril A. Karpenko
*
* 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.redshape.servlet.core;
/**
* @author nikelin
* @date 13:56
*/
public enum SupportType implements Comparable<SupportType> {
NO,
MAY,
SHOULD,
MUST;
}
| apache-2.0 |
multi-os-engine/moe-core | moe.apple/moe.platform.ios/src/main/java/apple/enums/clockid_t.java | 1328 | /*
Copyright 2014-2016 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apple.enums;
import org.moe.natj.general.ann.Generated;
@Generated
public final class clockid_t {
@Generated public static final int _CLOCK_REALTIME = 0x00000000;
@Generated public static final int _CLOCK_MONOTONIC = 0x00000006;
@Generated public static final int _CLOCK_MONOTONIC_RAW = 0x00000004;
@Generated public static final int _CLOCK_MONOTONIC_RAW_APPROX = 0x00000005;
@Generated public static final int _CLOCK_UPTIME_RAW = 0x00000008;
@Generated public static final int _CLOCK_UPTIME_RAW_APPROX = 0x00000009;
@Generated public static final int _CLOCK_PROCESS_CPUTIME_ID = 0x0000000C;
@Generated public static final int _CLOCK_THREAD_CPUTIME_ID = 0x00000010;
@Generated
private clockid_t() {
}
}
| apache-2.0 |
YY-ORG/yycloud | yy-core/yy-filesys/src/main/java/com/yy/cloud/core/filesys/config/SwaggerConfig.java | 1771 | package com.yy.cloud.core.filesys.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON. <br/>
* Date: 11/17/17 6:08 PM<br/>
*
* @author chenxj
* @see
* @since JDK 1.8
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket swaggerSpringMvcPlugin() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("Assess Management")
.apiInfo(apiInfo())
.genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(true)
.select()
.apis(RequestHandlerSelectors.basePackage("com.yy.cloud.core.filesys.controller"))
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("YouYin File System")
.description("YouYin File System Related APIs.")
.contact(new Contact("Chenxj", "http://www.google.com", "cxj_hit@126.com"))
.version("0.1")
.build();
}
}
| apache-2.0 |
rage28/Boothcamp | AndroidBoothcamp/AndroidBoothcamp/src/main/java/com/android/boothcamp/database/model/Scholar.java | 217 | package com.android.boothcamp.database.model;
public class Scholar {
public static final String TABLE_NAME = "SCHOLAR";
public static final String INO = "_id";
public static final String NAME = "NAME";
} | apache-2.0 |
ianache/didara-bpm | bpmengine-service/bpmengine-bpmn/src/main/java/com/bpm4sb/bpmn/TConversationAssociation.java | 2837 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.01.28 at 11:39:24 PM COT
//
package com.bpm4sb.bpmn;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
/**
* <p>Java class for tConversationAssociation complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="tConversationAssociation">
* <complexContent>
* <extension base="{http://www.omg.org/spec/BPMN/20100524/MODEL}tBaseElement">
* <attribute name="innerConversationNodeRef" use="required" type="{http://www.w3.org/2001/XMLSchema}QName" />
* <attribute name="outerConversationNodeRef" use="required" type="{http://www.w3.org/2001/XMLSchema}QName" />
* <anyAttribute processContents='lax' namespace='##other'/>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "tConversationAssociation")
public class TConversationAssociation
extends TBaseElement
{
@XmlAttribute(name = "innerConversationNodeRef", required = true)
protected QName innerConversationNodeRef;
@XmlAttribute(name = "outerConversationNodeRef", required = true)
protected QName outerConversationNodeRef;
/**
* Gets the value of the innerConversationNodeRef property.
*
* @return
* possible object is
* {@link QName }
*
*/
public QName getInnerConversationNodeRef() {
return innerConversationNodeRef;
}
/**
* Sets the value of the innerConversationNodeRef property.
*
* @param value
* allowed object is
* {@link QName }
*
*/
public void setInnerConversationNodeRef(QName value) {
this.innerConversationNodeRef = value;
}
/**
* Gets the value of the outerConversationNodeRef property.
*
* @return
* possible object is
* {@link QName }
*
*/
public QName getOuterConversationNodeRef() {
return outerConversationNodeRef;
}
/**
* Sets the value of the outerConversationNodeRef property.
*
* @param value
* allowed object is
* {@link QName }
*
*/
public void setOuterConversationNodeRef(QName value) {
this.outerConversationNodeRef = value;
}
}
| apache-2.0 |
ops4j/org.ops4j.pax.shiro | pax-shiro-cdi/src/test/java/org/ops4j/pax/shiro/cdi/ShiroFactoryTest.java | 858 | package org.ops4j.pax.shiro.cdi;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import javax.inject.Inject;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
public class ShiroFactoryTest extends AbstractCdiTest {
@Inject
private Subject subject;
@Inject
private SecurityManager securityManager;
@Inject
private Session session;
@Test
public void checkSubjectIsManaged() {
assertNotNull(subject);
assertFalse(subject.isAuthenticated());
}
@Test
public void checkSecurityManagerIsManaged() {
assertNotNull(securityManager);
}
@Test
public void checkSessionIsManaged() {
assertNotNull(session);
}
}
| apache-2.0 |
jt120/algorithm | new-alg/src/main/java/std/algs/TopM.java | 2578 | package std.algs;
import std.libs.*;
/*************************************************************************
* Compilation: javac TopM.java
* Execution: java TopM M < input.txt
* Dependencies: MinPQ.java Transaction.java StdIn.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/24pq/tinyBatch.txt
*
* Given an integer M from the command line and an input stream where
* each line contains a String and a long value, this MinPQ client
* prints the M lines whose numbers are the highest.
*
* % java TopM 5 < tinyBatch.txt
* Thompson 2/27/2000 4747.08
* vonNeumann 2/12/1994 4732.35
* vonNeumann 1/11/1999 4409.74
* Hoare 8/18/1992 4381.21
* vonNeumann 3/26/2002 4121.85
*
*************************************************************************/
/**
* The <tt>TopM</tt> class provides a client that reads a sequence of
* transactions from standard input and prints the <em>M</em> largest ones
* to standard output. This implementation uses a {@link std.algs.MinPQ} of size
* at most <em>M</em> + 1 to identify the <em>M</em> largest transactions
* and a {@link std.algs.Stack} to output them in the proper order.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/24pq">Section 2.4</a>
* of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class TopM {
// This class should not be instantiated.
private TopM() { }
/**
* Reads a sequence of transactions from standard input; takes a
* command-line integer M; prints to standard output the M largest
* transactions in descending order.
*/
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
MinPQ<Transaction> pq = new MinPQ<Transaction>(M+1);
while (StdIn.hasNextLine()) {
// Create an entry from the next line and put on the PQ.
String line = StdIn.readLine();
Transaction transaction = new Transaction(line);
pq.insert(transaction);
// remove minimum if M+1 entries on the PQ
if (pq.size() > M)
pq.delMin();
} // top M entries are on the PQ
// print entries on PQ in reverse order
Stack<Transaction> stack = new Stack<Transaction>();
for (Transaction transaction : pq)
stack.push(transaction);
for (Transaction transaction : stack)
StdOut.println(transaction);
}
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_7596.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_7596 {
}
| apache-2.0 |
amoudi87/asterixdb | asterix-om/src/main/java/org/apache/asterix/dataflow/data/nontagged/printers/json/clean/ABooleanPrinter.java | 1484 | /*
* 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.asterix.dataflow.data.nontagged.printers.json.clean;
import java.io.PrintStream;
import org.apache.asterix.dataflow.data.nontagged.serde.ABooleanSerializerDeserializer;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.data.IPrinter;
public class ABooleanPrinter implements IPrinter {
public static final ABooleanPrinter INSTANCE = new ABooleanPrinter();
@Override
public void init() {
}
@Override
public void print(byte[] b, int s, int l, PrintStream ps) throws AlgebricksException {
ps.print(ABooleanSerializerDeserializer.getBoolean(b, s + 1));
}
} | apache-2.0 |
LRMPUT/DiamentowyGrant | NavigationDG/src/org/dg/graphManager/Vertex.java | 1695 | // OpenAIL - Open Android Indoor Localization
// Copyright (C) 2015 Michal Nowicki (michal.nowicki@put.poznan.pl)
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dg.graphManager;
public class Vertex {
public int id;
public double X, Y, Z;
public Vertex(int id, double X, double Y, double Z) {
this.id = id;
this.X = X;
this.Y = Y;
this.Z = Z;
}
}
| apache-2.0 |
adamcin/net.adamcin.oakpal | cli/src/main/java/net/adamcin/oakpal/cli/DisposablePrinter.java | 290 | package net.adamcin.oakpal.cli;
import java.util.function.Function;
import net.adamcin.oakpal.api.Nothing;
/**
* Extension of simple IO printer function type to add a dispose() method.
*/
public interface DisposablePrinter extends Function<Object, IO<Nothing>> {
void dispose();
}
| apache-2.0 |
xiangxik/castle-platform | castle-framework/castle-repo/src/main/java/com/castle/repo/realm/NullDatabaseResolver.java | 332 | package com.castle.repo.realm;
public class NullDatabaseResolver implements DatabaseResolver {
@Override
public String resolveDatabaseName() {
return null;
}
@Override
public void setCurrentDatabase(String database) {
}
@Override
public void setDefaultDatabase() {
}
@Override
public void reset() {
}
}
| apache-2.0 |
zhgxun/cNotes | java/banana/src/main/java/github/banana/netty/EchoServer.java | 2716 | package github.banana.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
/**
* 启动一个echo服务器
*/
public class EchoServer {
// SSL
private static final boolean SSL = System.getProperty("ssl") != null;
// 指定绑定一个端口
private static final int PORT = Integer.parseInt(System.getProperty("port", "8080"));
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
} else {
sslCtx = null;
}
// Configure the server. mainReactor线程
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
// work 线程池
EventLoopGroup workerGroup = new NioEventLoopGroup();
final EchoServerHandler serverHandler = new EchoServerHandler();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
//p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(serverHandler);
}
});
// Start the server.
ChannelFuture f = b.bind(PORT).sync();
System.out.println("服务器端启动...");
// Wait until the server socket is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down all event loops to terminate all threads.
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
| apache-2.0 |
jormunmor/doctorado | optaplanner-distribution-6.2.0.Final/examples/sources/src/main/java/org/optaplanner/examples/vehiclerouting/domain/timewindowed/solver/ArrivalTimeUpdatingVariableListener.java | 3132 | package org.optaplanner.examples.vehiclerouting.domain.timewindowed.solver;
import org.apache.commons.lang.ObjectUtils;
import org.optaplanner.core.impl.domain.variable.listener.VariableListener;
import org.optaplanner.core.impl.score.director.ScoreDirector;
import org.optaplanner.examples.vehiclerouting.domain.Task;
import org.optaplanner.examples.vehiclerouting.domain.Standstill;
import org.optaplanner.examples.vehiclerouting.domain.timewindowed.TimeWindowedCustomer;
// TODO When this class is added only for TimeWindowedCustomer, use TimeWindowedCustomer instead of Task
public class ArrivalTimeUpdatingVariableListener implements VariableListener<Task> {
public void beforeEntityAdded(ScoreDirector scoreDirector, Task customer) {
// Do nothing
}
public void afterEntityAdded(ScoreDirector scoreDirector, Task customer) {
if (customer instanceof TimeWindowedCustomer) {
updateVehicle(scoreDirector, (TimeWindowedCustomer) customer);
}
}
public void beforeVariableChanged(ScoreDirector scoreDirector, Task customer) {
// Do nothing
}
public void afterVariableChanged(ScoreDirector scoreDirector, Task customer) {
if (customer instanceof TimeWindowedCustomer) {
updateVehicle(scoreDirector, (TimeWindowedCustomer) customer);
}
}
public void beforeEntityRemoved(ScoreDirector scoreDirector, Task customer) {
// Do nothing
}
public void afterEntityRemoved(ScoreDirector scoreDirector, Task customer) {
// Do nothing
}
protected void updateVehicle(ScoreDirector scoreDirector, TimeWindowedCustomer sourceCustomer) {
Standstill previousStandstill = sourceCustomer.getPreviousStandstill();
Integer departureTime = (previousStandstill instanceof TimeWindowedCustomer)
? ((TimeWindowedCustomer) previousStandstill).getDepartureTime() : null;
TimeWindowedCustomer shadowCustomer = sourceCustomer;
Integer arrivalTime = calculateArrivalTime(shadowCustomer, departureTime);
while (shadowCustomer != null && ObjectUtils.notEqual(shadowCustomer.getArrivalTime(), arrivalTime)) {
scoreDirector.beforeVariableChanged(shadowCustomer, "arrivalTime");
shadowCustomer.setArrivalTime(arrivalTime);
scoreDirector.afterVariableChanged(shadowCustomer, "arrivalTime");
departureTime = shadowCustomer.getDepartureTime();
shadowCustomer = shadowCustomer.getNextTask();
arrivalTime = calculateArrivalTime(shadowCustomer, departureTime);
}
}
private Integer calculateArrivalTime(TimeWindowedCustomer customer, Integer previousDepartureTime) {
if (customer == null) {
return null;
}
if (previousDepartureTime == null) {
// PreviousStandstill is the Vehicle, so we leave from the Depot at the best suitable time
return Math.max(customer.getReadyTime(), customer.getDistanceToPreviousStandstill());
}
return previousDepartureTime + customer.getDistanceToPreviousStandstill();
}
}
| apache-2.0 |
JoseRivas1998/miss-it | core/src/com/tcg/missit/managers/MyInput.java | 934 | package com.tcg.missit.managers;
public class MyInput {
private static boolean[] keys;
private static boolean[] pkeys;
private static final int NUM_KEYS = 7;
public static final int UP = 0;
public static final int DOWN = 1;
public static final int LEFT = 2;
public static final int RIGHT = 3;
public static final int ENTER = 4;
public static final int ESCAPE = 5;
public static final int ANY = 6;
static {
keys = new boolean[NUM_KEYS];
pkeys = new boolean[NUM_KEYS];
}
public static void update() {
for(int i = 0; i < NUM_KEYS; i++) {
pkeys[i] = keys[i];
}
}
public static void setKey(int k, boolean b) {
keys[k] = b;
}
public static boolean isDown(int k) {
return keys[k];
}
public static boolean isPressed(int k) {
return keys[k] && !pkeys[k];
}
public static boolean anyKeyDown() {
return isDown(ANY);
}
public static boolean anyKeyPressed() {
return isPressed(ANY);
}
}
| apache-2.0 |
stephenh/jOOL | src/main/java/org/jooq/lambda/tuple/Tuple4.java | 11623 | /**
* Copyright (c) 2014-2015, Data Geekery GmbH, contact@datageekery.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jooq.lambda.tuple;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import org.jooq.lambda.function.Function1;
import org.jooq.lambda.function.Function4;
/**
* A tuple of degree 4.
*
* @author Lukas Eder
*/
public class Tuple4<T1, T2, T3, T4> implements Tuple, Comparable<Tuple4<T1, T2, T3, T4>>, Serializable, Cloneable {
private static final long serialVersionUID = 1L;
public final T1 v1;
public final T2 v2;
public final T3 v3;
public final T4 v4;
public T1 v1() {
return v1;
}
public T2 v2() {
return v2;
}
public T3 v3() {
return v3;
}
public T4 v4() {
return v4;
}
public Tuple4(Tuple4<T1, T2, T3, T4> tuple) {
this.v1 = tuple.v1;
this.v2 = tuple.v2;
this.v3 = tuple.v3;
this.v4 = tuple.v4;
}
public Tuple4(T1 v1, T2 v2, T3 v3, T4 v4) {
this.v1 = v1;
this.v2 = v2;
this.v3 = v3;
this.v4 = v4;
}
/**
* Concatenate a value to this tuple.
*/
public final <T5> Tuple5<T1, T2, T3, T4, T5> concat(T5 value) {
return new Tuple5<>(v1, v2, v3, v4, value);
}
/**
* Concatenate a tuple to this tuple.
*/
public final <T5> Tuple5<T1, T2, T3, T4, T5> concat(Tuple1<T5> tuple) {
return new Tuple5<>(v1, v2, v3, v4, tuple.v1);
}
/**
* Concatenate a tuple to this tuple.
*/
public final <T5, T6> Tuple6<T1, T2, T3, T4, T5, T6> concat(Tuple2<T5, T6> tuple) {
return new Tuple6<>(v1, v2, v3, v4, tuple.v1, tuple.v2);
}
/**
* Concatenate a tuple to this tuple.
*/
public final <T5, T6, T7> Tuple7<T1, T2, T3, T4, T5, T6, T7> concat(Tuple3<T5, T6, T7> tuple) {
return new Tuple7<>(v1, v2, v3, v4, tuple.v1, tuple.v2, tuple.v3);
}
/**
* Concatenate a tuple to this tuple.
*/
public final <T5, T6, T7, T8> Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> concat(Tuple4<T5, T6, T7, T8> tuple) {
return new Tuple8<>(v1, v2, v3, v4, tuple.v1, tuple.v2, tuple.v3, tuple.v4);
}
/**
* Concatenate a tuple to this tuple.
*/
public final <T5, T6, T7, T8, T9> Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9> concat(Tuple5<T5, T6, T7, T8, T9> tuple) {
return new Tuple9<>(v1, v2, v3, v4, tuple.v1, tuple.v2, tuple.v3, tuple.v4, tuple.v5);
}
/**
* Concatenate a tuple to this tuple.
*/
public final <T5, T6, T7, T8, T9, T10> Tuple10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> concat(Tuple6<T5, T6, T7, T8, T9, T10> tuple) {
return new Tuple10<>(v1, v2, v3, v4, tuple.v1, tuple.v2, tuple.v3, tuple.v4, tuple.v5, tuple.v6);
}
/**
* Concatenate a tuple to this tuple.
*/
public final <T5, T6, T7, T8, T9, T10, T11> Tuple11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> concat(Tuple7<T5, T6, T7, T8, T9, T10, T11> tuple) {
return new Tuple11<>(v1, v2, v3, v4, tuple.v1, tuple.v2, tuple.v3, tuple.v4, tuple.v5, tuple.v6, tuple.v7);
}
/**
* Concatenate a tuple to this tuple.
*/
public final <T5, T6, T7, T8, T9, T10, T11, T12> Tuple12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> concat(Tuple8<T5, T6, T7, T8, T9, T10, T11, T12> tuple) {
return new Tuple12<>(v1, v2, v3, v4, tuple.v1, tuple.v2, tuple.v3, tuple.v4, tuple.v5, tuple.v6, tuple.v7, tuple.v8);
}
/**
* Concatenate a tuple to this tuple.
*/
public final <T5, T6, T7, T8, T9, T10, T11, T12, T13> Tuple13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> concat(Tuple9<T5, T6, T7, T8, T9, T10, T11, T12, T13> tuple) {
return new Tuple13<>(v1, v2, v3, v4, tuple.v1, tuple.v2, tuple.v3, tuple.v4, tuple.v5, tuple.v6, tuple.v7, tuple.v8, tuple.v9);
}
/**
* Concatenate a tuple to this tuple.
*/
public final <T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> Tuple14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> concat(Tuple10<T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> tuple) {
return new Tuple14<>(v1, v2, v3, v4, tuple.v1, tuple.v2, tuple.v3, tuple.v4, tuple.v5, tuple.v6, tuple.v7, tuple.v8, tuple.v9, tuple.v10);
}
/**
* Concatenate a tuple to this tuple.
*/
public final <T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> Tuple15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> concat(Tuple11<T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> tuple) {
return new Tuple15<>(v1, v2, v3, v4, tuple.v1, tuple.v2, tuple.v3, tuple.v4, tuple.v5, tuple.v6, tuple.v7, tuple.v8, tuple.v9, tuple.v10, tuple.v11);
}
/**
* Concatenate a tuple to this tuple.
*/
public final <T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> Tuple16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> concat(Tuple12<T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> tuple) {
return new Tuple16<>(v1, v2, v3, v4, tuple.v1, tuple.v2, tuple.v3, tuple.v4, tuple.v5, tuple.v6, tuple.v7, tuple.v8, tuple.v9, tuple.v10, tuple.v11, tuple.v12);
}
/**
* Split this tuple into two tuples of degree 0 and 4.
*/
public final Tuple2<Tuple0, Tuple4<T1, T2, T3, T4>> split0() {
return new Tuple2<>(limit0(), skip0());
}
/**
* Split this tuple into two tuples of degree 1 and 3.
*/
public final Tuple2<Tuple1<T1>, Tuple3<T2, T3, T4>> split1() {
return new Tuple2<>(limit1(), skip1());
}
/**
* Split this tuple into two tuples of degree 2 and 2.
*/
public final Tuple2<Tuple2<T1, T2>, Tuple2<T3, T4>> split2() {
return new Tuple2<>(limit2(), skip2());
}
/**
* Split this tuple into two tuples of degree 3 and 1.
*/
public final Tuple2<Tuple3<T1, T2, T3>, Tuple1<T4>> split3() {
return new Tuple2<>(limit3(), skip3());
}
/**
* Split this tuple into two tuples of degree 4 and 0.
*/
public final Tuple2<Tuple4<T1, T2, T3, T4>, Tuple0> split4() {
return new Tuple2<>(limit4(), skip4());
}
/**
* Limit this tuple to degree 0.
*/
public final Tuple0 limit0() {
return new Tuple0();
}
/**
* Limit this tuple to degree 1.
*/
public final Tuple1<T1> limit1() {
return new Tuple1<>(v1);
}
/**
* Limit this tuple to degree 2.
*/
public final Tuple2<T1, T2> limit2() {
return new Tuple2<>(v1, v2);
}
/**
* Limit this tuple to degree 3.
*/
public final Tuple3<T1, T2, T3> limit3() {
return new Tuple3<>(v1, v2, v3);
}
/**
* Limit this tuple to degree 4.
*/
public final Tuple4<T1, T2, T3, T4> limit4() {
return this;
}
/**
* Skip 0 degrees from this tuple.
*/
public final Tuple4<T1, T2, T3, T4> skip0() {
return this;
}
/**
* Skip 1 degrees from this tuple.
*/
public final Tuple3<T2, T3, T4> skip1() {
return new Tuple3<>(v2, v3, v4);
}
/**
* Skip 2 degrees from this tuple.
*/
public final Tuple2<T3, T4> skip2() {
return new Tuple2<>(v3, v4);
}
/**
* Skip 3 degrees from this tuple.
*/
public final Tuple1<T4> skip3() {
return new Tuple1<>(v4);
}
/**
* Skip 4 degrees from this tuple.
*/
public final Tuple0 skip4() {
return new Tuple0();
}
/**
* Apply this tuple as arguments to a function.
*/
public final <R> R map(Function4<T1, T2, T3, T4, R> function) {
return function.apply(this);
}
/**
* Apply attribute 1 as argument to a function and return a new tuple with the substituted argument.
*/
public final <U1> Tuple4<U1, T2, T3, T4> map1(Function1<? super T1, ? extends U1> function) {
return Tuple.tuple(function.apply(v1), v2, v3, v4);
}
/**
* Apply attribute 2 as argument to a function and return a new tuple with the substituted argument.
*/
public final <U2> Tuple4<T1, U2, T3, T4> map2(Function1<? super T2, ? extends U2> function) {
return Tuple.tuple(v1, function.apply(v2), v3, v4);
}
/**
* Apply attribute 3 as argument to a function and return a new tuple with the substituted argument.
*/
public final <U3> Tuple4<T1, T2, U3, T4> map3(Function1<? super T3, ? extends U3> function) {
return Tuple.tuple(v1, v2, function.apply(v3), v4);
}
/**
* Apply attribute 4 as argument to a function and return a new tuple with the substituted argument.
*/
public final <U4> Tuple4<T1, T2, T3, U4> map4(Function1<? super T4, ? extends U4> function) {
return Tuple.tuple(v1, v2, v3, function.apply(v4));
}
@Override
public final Object[] array() {
return new Object[] { v1, v2, v3, v4 };
}
@Override
public final List<?> list() {
return Arrays.asList(array());
}
/**
* The degree of this tuple: 4.
*/
@Override
public final int degree() {
return 4;
}
@Override
@SuppressWarnings("unchecked")
public final Iterator<Object> iterator() {
return (Iterator<Object>) list().iterator();
}
@Override
public int compareTo(Tuple4<T1, T2, T3, T4> other) {
int result = 0;
result = Tuples.compare(v1, other.v1); if (result != 0) return result;
result = Tuples.compare(v2, other.v2); if (result != 0) return result;
result = Tuples.compare(v3, other.v3); if (result != 0) return result;
result = Tuples.compare(v4, other.v4); if (result != 0) return result;
return result;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Tuple4))
return false;
@SuppressWarnings({ "unchecked", "rawtypes" })
final Tuple4<T1, T2, T3, T4> that = (Tuple4) o;
if (!Objects.equals(v1, that.v1)) return false;
if (!Objects.equals(v2, that.v2)) return false;
if (!Objects.equals(v3, that.v3)) return false;
if (!Objects.equals(v4, that.v4)) return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((v1 == null) ? 0 : v1.hashCode());
result = prime * result + ((v2 == null) ? 0 : v2.hashCode());
result = prime * result + ((v3 == null) ? 0 : v3.hashCode());
result = prime * result + ((v4 == null) ? 0 : v4.hashCode());
return result;
}
@Override
public String toString() {
return "("
+ v1
+ ", " + v2
+ ", " + v3
+ ", " + v4
+ ")";
}
@Override
public Tuple4<T1, T2, T3, T4> clone() {
return new Tuple4<>(this);
}
}
| apache-2.0 |
riveraj/subjectj | src/main/java/org/subjectj/compiler/ast/DirectoryExcludeNode.java | 534 | package org.subjectj.compiler.ast;
import java.nio.file.Path;
import org.subjectj.compiler.ast.visitor.ASTVisitor;
public class DirectoryExcludeNode implements ASTNode {
private final Path path;
private final ASTNode exclude;
public DirectoryExcludeNode(Path path, ASTNode exclude) {
this.path = path;
this.exclude = exclude;
}
@Override
public void accept(ASTVisitor visitor) {
visitor.visit(this);
}
public Path getPath() {
return this.path;
}
public ASTNode getExcludeNode() {
return this.exclude;
}
}
| apache-2.0 |
xuanwo11/YoutieApp | src/com/easemob/chatuidemo/activity/GroupDetailsActivity.java | 27482 | /**
* Copyright (C) 2013-2014 EaseMob Technologies. 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.easemob.chatuidemo.activity;
import java.util.ArrayList;
import java.util.List;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chatuidemo.utils.UserUtils;
import com.easemob.chatuidemo.widget.ExpandGridView;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.EMLog;
import com.easemob.util.NetUtils;
import com.hfp.youtie.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class GroupDetailsActivity extends BaseActivity implements OnClickListener {
private static final String TAG = "GroupDetailsActivity";
private static final int REQUEST_CODE_ADD_USER = 0;
private static final int REQUEST_CODE_EXIT = 1;
private static final int REQUEST_CODE_EXIT_DELETE = 2;
private static final int REQUEST_CODE_CLEAR_ALL_HISTORY = 3;
private static final int REQUEST_CODE_ADD_TO_BALCKLIST = 4;
private static final int REQUEST_CODE_EDIT_GROUPNAME = 5;
String longClickUsername = null;
private ExpandGridView userGridview;
private String groupId;
private ProgressBar loadingPB;
private Button exitBtn;
private Button deleteBtn;
private EMGroup group;
private GridAdapter adapter;
private int referenceWidth;
private int referenceHeight;
private ProgressDialog progressDialog;
private RelativeLayout rl_switch_block_groupmsg;
/**
* 屏蔽群消息imageView
*/
private ImageView iv_switch_block_groupmsg;
/**
* 关闭屏蔽群消息imageview
*/
private ImageView iv_switch_unblock_groupmsg;
public static GroupDetailsActivity instance;
String st = "";
// 清空所有聊天记录
private RelativeLayout clearAllHistory;
private RelativeLayout blacklistLayout;
private RelativeLayout changeGroupNameLayout;
private RelativeLayout idLayout;
private TextView idText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 获取传过来的groupid
groupId = getIntent().getStringExtra("groupId");
group = EMGroupManager.getInstance().getGroup(groupId);
// we are not supposed to show the group if we don't find the group
if(group == null){
finish();
return;
}
setContentView(R.layout.activity_group_details);
instance = this;
st = getResources().getString(R.string.people);
clearAllHistory = (RelativeLayout) findViewById(R.id.clear_all_history);
userGridview = (ExpandGridView) findViewById(R.id.gridview);
loadingPB = (ProgressBar) findViewById(R.id.progressBar);
exitBtn = (Button) findViewById(R.id.btn_exit_grp);
deleteBtn = (Button) findViewById(R.id.btn_exitdel_grp);
blacklistLayout = (RelativeLayout) findViewById(R.id.rl_blacklist);
changeGroupNameLayout = (RelativeLayout) findViewById(R.id.rl_change_group_name);
idLayout = (RelativeLayout) findViewById(R.id.rl_group_id);
idLayout.setVisibility(View.VISIBLE);
idText = (TextView) findViewById(R.id.tv_group_id_value);
rl_switch_block_groupmsg = (RelativeLayout) findViewById(R.id.rl_switch_block_groupmsg);
iv_switch_block_groupmsg = (ImageView) findViewById(R.id.iv_switch_block_groupmsg);
iv_switch_unblock_groupmsg = (ImageView) findViewById(R.id.iv_switch_unblock_groupmsg);
rl_switch_block_groupmsg.setOnClickListener(this);
Drawable referenceDrawable = getResources().getDrawable(R.drawable.smiley_add_btn);
referenceWidth = referenceDrawable.getIntrinsicWidth();
referenceHeight = referenceDrawable.getIntrinsicHeight();
idText.setText(groupId);
if (group.getOwner() == null || "".equals(group.getOwner())
|| !group.getOwner().equals(EMChatManager.getInstance().getCurrentUser())) {
exitBtn.setVisibility(View.GONE);
deleteBtn.setVisibility(View.GONE);
blacklistLayout.setVisibility(View.GONE);
changeGroupNameLayout.setVisibility(View.GONE);
}
// 如果自己是群主,显示解散按钮
if (EMChatManager.getInstance().getCurrentUser().equals(group.getOwner())) {
exitBtn.setVisibility(View.GONE);
deleteBtn.setVisibility(View.VISIBLE);
}
((TextView) findViewById(R.id.group_name)).setText(group.getGroupName() + "(" + group.getAffiliationsCount() + st);
List<String> members = new ArrayList<String>();
members.addAll(group.getMembers());
adapter = new GridAdapter(this, R.layout.grid, members);
userGridview.setAdapter(adapter);
// 保证每次进详情看到的都是最新的group
updateGroup();
// 设置OnTouchListener
userGridview.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (adapter.isInDeleteMode) {
adapter.isInDeleteMode = false;
adapter.notifyDataSetChanged();
return true;
}
break;
default:
break;
}
return false;
}
});
clearAllHistory.setOnClickListener(this);
blacklistLayout.setOnClickListener(this);
changeGroupNameLayout.setOnClickListener(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String st1 = getResources().getString(R.string.being_added);
String st2 = getResources().getString(R.string.is_quit_the_group_chat);
String st3 = getResources().getString(R.string.chatting_is_dissolution);
String st4 = getResources().getString(R.string.are_empty_group_of_news);
String st5 = getResources().getString(R.string.is_modify_the_group_name);
final String st6 = getResources().getString(R.string.Modify_the_group_name_successful);
final String st7 = getResources().getString(R.string.change_the_group_name_failed_please);
String st8 = getResources().getString(R.string.Are_moving_to_blacklist);
final String st9 = getResources().getString(R.string.failed_to_move_into);
final String stsuccess = getResources().getString(R.string.Move_into_blacklist_success);
if (resultCode == RESULT_OK) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(GroupDetailsActivity.this);
progressDialog.setMessage(st1);
progressDialog.setCanceledOnTouchOutside(false);
}
switch (requestCode) {
case REQUEST_CODE_ADD_USER:// 添加群成员
final String[] newmembers = data.getStringArrayExtra("newmembers");
progressDialog.setMessage(st1);
progressDialog.show();
addMembersToGroup(newmembers);
break;
case REQUEST_CODE_EXIT: // 退出群
progressDialog.setMessage(st2);
progressDialog.show();
exitGrop();
break;
case REQUEST_CODE_EXIT_DELETE: // 解散群
progressDialog.setMessage(st3);
progressDialog.show();
deleteGrop();
break;
case REQUEST_CODE_CLEAR_ALL_HISTORY:
// 清空此群聊的聊天记录
progressDialog.setMessage(st4);
progressDialog.show();
clearGroupHistory();
break;
case REQUEST_CODE_EDIT_GROUPNAME: //修改群名称
final String returnData = data.getStringExtra("data");
if(!TextUtils.isEmpty(returnData)){
progressDialog.setMessage(st5);
progressDialog.show();
new Thread(new Runnable() {
public void run() {
try {
EMGroupManager.getInstance().changeGroupName(groupId, returnData);
runOnUiThread(new Runnable() {
public void run() {
((TextView) findViewById(R.id.group_name)).setText(returnData + "(" + group.getAffiliationsCount()
+ st);
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), st6, 0).show();
}
});
} catch (EaseMobException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), st7, 0).show();
}
});
}
}
}).start();
}
break;
case REQUEST_CODE_ADD_TO_BALCKLIST:
progressDialog.setMessage(st8);
progressDialog.show();
new Thread(new Runnable() {
public void run() {
try {
EMGroupManager.getInstance().blockUser(groupId, longClickUsername);
runOnUiThread(new Runnable() {
public void run() {
refreshMembers();
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), stsuccess, 0).show();
}
});
} catch (EaseMobException e) {
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), st9, 0).show();
}
});
}
}
}).start();
break;
default:
break;
}
}
}
private void refreshMembers(){
adapter.clear();
List<String> members = new ArrayList<String>();
members.addAll(group.getMembers());
adapter.addAll(members);
adapter.notifyDataSetChanged();
}
/**
* 点击退出群组按钮
*
* @param view
*/
public void exitGroup(View view) {
startActivityForResult(new Intent(this, ExitGroupDialog.class), REQUEST_CODE_EXIT);
}
/**
* 点击解散群组按钮
*
* @param view
*/
public void exitDeleteGroup(View view) {
startActivityForResult(new Intent(this, ExitGroupDialog.class).putExtra("deleteToast", getString(R.string.dissolution_group_hint)),
REQUEST_CODE_EXIT_DELETE);
}
/**
* 清空群聊天记录
*/
public void clearGroupHistory() {
EMChatManager.getInstance().clearConversation(group.getGroupId());
progressDialog.dismiss();
// adapter.refresh(EMChatManager.getInstance().getConversation(toChatUsername));
}
/**
* 退出群组
*
* @param groupId
*/
private void exitGrop() {
String st1 = getResources().getString(R.string.Exit_the_group_chat_failure);
new Thread(new Runnable() {
public void run() {
try {
EMGroupManager.getInstance().exitFromGroup(groupId);
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
setResult(RESULT_OK);
finish();
if(ChatActivity.activityInstance != null)
ChatActivity.activityInstance.finish();
}
});
} catch (final Exception e) {
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), getResources().getString(R.string.Exit_the_group_chat_failure) + " " + e.getMessage(), 1).show();
}
});
}
}
}).start();
}
/**
* 解散群组
*
* @param groupId
*/
private void deleteGrop() {
final String st5 = getResources().getString(R.string.Dissolve_group_chat_tofail);
new Thread(new Runnable() {
public void run() {
try {
EMGroupManager.getInstance().exitAndDeleteGroup(groupId);
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
setResult(RESULT_OK);
finish();
if(ChatActivity.activityInstance != null)
ChatActivity.activityInstance.finish();
}
});
} catch (final Exception e) {
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), st5 + e.getMessage(), 1).show();
}
});
}
}
}).start();
}
/**
* 增加群成员
*
* @param newmembers
*/
private void addMembersToGroup(final String[] newmembers) {
final String st6 = getResources().getString(R.string.Add_group_members_fail);
new Thread(new Runnable() {
public void run() {
try {
// 创建者调用add方法
if (EMChatManager.getInstance().getCurrentUser().equals(group.getOwner())) {
EMGroupManager.getInstance().addUsersToGroup(groupId, newmembers);
} else {
// 一般成员调用invite方法
EMGroupManager.getInstance().inviteUser(groupId, newmembers, null);
}
runOnUiThread(new Runnable() {
public void run() {
refreshMembers();
((TextView) findViewById(R.id.group_name)).setText(group.getGroupName() + "(" + group.getAffiliationsCount()
+ st);
progressDialog.dismiss();
}
});
} catch (final Exception e) {
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), st6 + e.getMessage(), 1).show();
}
});
}
}
}).start();
}
@Override
public void onClick(View v) {
String st6 = getResources().getString(R.string.Is_unblock);
final String st7 = getResources().getString(R.string.remove_group_of);
switch (v.getId()) {
case R.id.rl_switch_block_groupmsg: // 屏蔽群组
if (iv_switch_block_groupmsg.getVisibility() == View.VISIBLE) {
EMLog.d(TAG, "change to unblock group msg");
if (progressDialog == null) {
progressDialog = new ProgressDialog(GroupDetailsActivity.this);
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.setMessage(st6);
progressDialog.show();
new Thread(new Runnable() {
public void run() {
try {
EMGroupManager.getInstance().unblockGroupMessage(groupId);
runOnUiThread(new Runnable() {
public void run() {
iv_switch_block_groupmsg.setVisibility(View.INVISIBLE);
iv_switch_unblock_groupmsg.setVisibility(View.VISIBLE);
progressDialog.dismiss();
}
});
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), st7, 1).show();
}
});
}
}
}).start();
} else {
String st8 = getResources().getString(R.string.group_is_blocked);
final String st9 = getResources().getString(R.string.group_of_shielding);
EMLog.d(TAG, "change to block group msg");
if (progressDialog == null) {
progressDialog = new ProgressDialog(GroupDetailsActivity.this);
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.setMessage(st8);
progressDialog.show();
new Thread(new Runnable() {
public void run() {
try {
EMGroupManager.getInstance().blockGroupMessage(groupId);
runOnUiThread(new Runnable() {
public void run() {
iv_switch_block_groupmsg.setVisibility(View.VISIBLE);
iv_switch_unblock_groupmsg.setVisibility(View.INVISIBLE);
progressDialog.dismiss();
}
});
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), st9, 1).show();
}
});
}
}
}).start();
}
break;
case R.id.clear_all_history: // 清空聊天记录
String st9 = getResources().getString(R.string.sure_to_empty_this);
Intent intent = new Intent(GroupDetailsActivity.this, AlertDialog.class);
intent.putExtra("cancel", true);
intent.putExtra("titleIsCancel", true);
intent.putExtra("msg", st9);
startActivityForResult(intent, REQUEST_CODE_CLEAR_ALL_HISTORY);
break;
case R.id.rl_blacklist: // 黑名单列表
startActivity(new Intent(GroupDetailsActivity.this, GroupBlacklistActivity.class).putExtra("groupId", groupId));
break;
case R.id.rl_change_group_name:
startActivityForResult(new Intent(this, EditActivity.class).putExtra("data", group.getGroupName()), REQUEST_CODE_EDIT_GROUPNAME);
break;
default:
break;
}
}
/**
* 群组成员gridadapter
*
* @author admin_new
*
*/
private class GridAdapter extends ArrayAdapter<String> {
private int res;
public boolean isInDeleteMode;
private List<String> objects;
public GridAdapter(Context context, int textViewResourceId, List<String> objects) {
super(context, textViewResourceId, objects);
this.objects = objects;
res = textViewResourceId;
isInDeleteMode = false;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(res, null);
holder.imageView = (ImageView) convertView.findViewById(R.id.iv_avatar);
holder.textView = (TextView) convertView.findViewById(R.id.tv_name);
holder.badgeDeleteView = (ImageView) convertView.findViewById(R.id.badge_delete);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
final LinearLayout button = (LinearLayout) convertView.findViewById(R.id.button_avatar);
// 最后一个item,减人按钮
if (position == getCount() - 1) {
holder.textView.setText("");
// 设置成删除按钮
holder.imageView.setImageResource(R.drawable.smiley_minus_btn);
// button.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.smiley_minus_btn, 0, 0);
// 如果不是创建者或者没有相应权限,不提供加减人按钮
if (!group.getOwner().equals(EMChatManager.getInstance().getCurrentUser())) {
// if current user is not group admin, hide add/remove btn
convertView.setVisibility(View.INVISIBLE);
} else { // 显示删除按钮
if (isInDeleteMode) {
// 正处于删除模式下,隐藏删除按钮
convertView.setVisibility(View.INVISIBLE);
} else {
// 正常模式
convertView.setVisibility(View.VISIBLE);
convertView.findViewById(R.id.badge_delete).setVisibility(View.INVISIBLE);
}
final String st10 = getResources().getString(R.string.The_delete_button_is_clicked);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EMLog.d(TAG, st10);
isInDeleteMode = true;
notifyDataSetChanged();
}
});
}
} else if (position == getCount() - 2) { // 添加群组成员按钮
holder.textView.setText("");
holder.imageView.setImageResource(R.drawable.smiley_add_btn);
// button.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.smiley_add_btn, 0, 0);
// 如果不是创建者或者没有相应权限
if (!group.isAllowInvites() && !group.getOwner().equals(EMChatManager.getInstance().getCurrentUser())) {
// if current user is not group admin, hide add/remove btn
convertView.setVisibility(View.INVISIBLE);
} else {
// 正处于删除模式下,隐藏添加按钮
if (isInDeleteMode) {
convertView.setVisibility(View.INVISIBLE);
} else {
convertView.setVisibility(View.VISIBLE);
convertView.findViewById(R.id.badge_delete).setVisibility(View.INVISIBLE);
}
final String st11 = getResources().getString(R.string.Add_a_button_was_clicked);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EMLog.d(TAG, st11);
// 进入选人页面
startActivityForResult(
(new Intent(GroupDetailsActivity.this, GroupPickContactsActivity.class).putExtra("groupId", groupId)),
REQUEST_CODE_ADD_USER);
}
});
}
} else { // 普通item,显示群组成员
final String username = getItem(position);
convertView.setVisibility(View.VISIBLE);
button.setVisibility(View.VISIBLE);
// Drawable avatar = getResources().getDrawable(R.drawable.default_avatar);
// avatar.setBounds(0, 0, referenceWidth, referenceHeight);
// button.setCompoundDrawables(null, avatar, null, null);
holder.textView.setText(username);
UserUtils.setUserAvatar(getContext(), username, holder.imageView);
// demo群组成员的头像都用默认头像,需由开发者自己去设置头像
if (isInDeleteMode) {
// 如果是删除模式下,显示减人图标
convertView.findViewById(R.id.badge_delete).setVisibility(View.VISIBLE);
} else {
convertView.findViewById(R.id.badge_delete).setVisibility(View.INVISIBLE);
}
final String st12 = getResources().getString(R.string.not_delete_myself);
final String st13 = getResources().getString(R.string.Are_removed);
final String st14 = getResources().getString(R.string.Delete_failed);
final String st15 = getResources().getString(R.string.confirm_the_members);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (isInDeleteMode) {
// 如果是删除自己,return
if (EMChatManager.getInstance().getCurrentUser().equals(username)) {
startActivity(new Intent(GroupDetailsActivity.this, AlertDialog.class).putExtra("msg", st12));
return;
}
if (!NetUtils.hasNetwork(getApplicationContext())) {
Toast.makeText(getApplicationContext(), getString(R.string.network_unavailable), 0).show();
return;
}
EMLog.d("group", "remove user from group:" + username);
deleteMembersFromGroup(username);
} else {
// 正常情况下点击user,可以进入用户详情或者聊天页面等等
// startActivity(new
// Intent(GroupDetailsActivity.this,
// ChatActivity.class).putExtra("userId",
// user.getUsername()));
}
}
/**
* 删除群成员
*
* @param username
*/
protected void deleteMembersFromGroup(final String username) {
final ProgressDialog deleteDialog = new ProgressDialog(GroupDetailsActivity.this);
deleteDialog.setMessage(st13);
deleteDialog.setCanceledOnTouchOutside(false);
deleteDialog.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
// 删除被选中的成员
EMGroupManager.getInstance().removeUserFromGroup(groupId, username);
isInDeleteMode = false;
runOnUiThread(new Runnable() {
@Override
public void run() {
deleteDialog.dismiss();
refreshMembers();
((TextView) findViewById(R.id.group_name)).setText(group.getGroupName() + "("
+ group.getAffiliationsCount() + st);
}
});
} catch (final Exception e) {
deleteDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), st14 + e.getMessage(), 1).show();
}
});
}
}
}).start();
}
});
button.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if(EMChatManager.getInstance().getCurrentUser().equals(username))
return true;
if (group.getOwner().equals(EMChatManager.getInstance().getCurrentUser())) {
Intent intent = new Intent(GroupDetailsActivity.this, AlertDialog.class);
intent.putExtra("msg", st15);
intent.putExtra("cancel", true);
startActivityForResult(intent, REQUEST_CODE_ADD_TO_BALCKLIST);
longClickUsername = username;
}
return false;
}
});
}
return convertView;
}
@Override
public int getCount() {
return super.getCount() + 2;
}
}
protected void updateGroup() {
new Thread(new Runnable() {
public void run() {
try {
final EMGroup returnGroup = EMGroupManager.getInstance().getGroupFromServer(groupId);
// 更新本地数据
EMGroupManager.getInstance().createOrUpdateLocalGroup(returnGroup);
runOnUiThread(new Runnable() {
public void run() {
((TextView) findViewById(R.id.group_name)).setText(group.getGroupName() + "(" + group.getAffiliationsCount()
+ ")");
loadingPB.setVisibility(View.INVISIBLE);
refreshMembers();
if (EMChatManager.getInstance().getCurrentUser().equals(group.getOwner())) {
// 显示解散按钮
exitBtn.setVisibility(View.GONE);
deleteBtn.setVisibility(View.VISIBLE);
} else {
// 显示退出按钮
exitBtn.setVisibility(View.VISIBLE);
deleteBtn.setVisibility(View.GONE);
}
// update block
EMLog.d(TAG, "group msg is blocked:" + group.getMsgBlocked());
if (group.isMsgBlocked()) {
iv_switch_block_groupmsg.setVisibility(View.VISIBLE);
iv_switch_unblock_groupmsg.setVisibility(View.INVISIBLE);
} else {
iv_switch_block_groupmsg.setVisibility(View.INVISIBLE);
iv_switch_unblock_groupmsg.setVisibility(View.VISIBLE);
}
}
});
} catch (Exception e) {
runOnUiThread(new Runnable() {
public void run() {
loadingPB.setVisibility(View.INVISIBLE);
}
});
}
}
}).start();
}
public void back(View view) {
setResult(RESULT_OK);
finish();
}
@Override
public void onBackPressed() {
setResult(RESULT_OK);
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
instance = null;
}
private static class ViewHolder{
ImageView imageView;
TextView textView;
ImageView badgeDeleteView;
}
}
| apache-2.0 |
moosbusch/xbLIDO | src/net/opengis/gml/RectangleType.java | 9149 | /*
* Copyright 2013 Gunnar Kappei.
*
* 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.opengis.gml;
/**
* An XML RectangleType(@http://www.opengis.net/gml).
*
* This is a complex type.
*/
public interface RectangleType extends net.opengis.gml.AbstractSurfacePatchType
{
public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(RectangleType.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("rectangletype4864type");
/**
* Gets the "exterior" element
*/
net.opengis.gml.AbstractRingPropertyType getExterior();
/**
* Sets the "exterior" element
*/
void setExterior(net.opengis.gml.AbstractRingPropertyType exterior);
/**
* Appends and returns a new empty "exterior" element
*/
net.opengis.gml.AbstractRingPropertyType addNewExterior();
/**
* Gets the "interpolation" attribute
*/
net.opengis.gml.SurfaceInterpolationType.Enum getInterpolation();
/**
* Gets (as xml) the "interpolation" attribute
*/
net.opengis.gml.SurfaceInterpolationType xgetInterpolation();
/**
* True if has "interpolation" attribute
*/
boolean isSetInterpolation();
/**
* Sets the "interpolation" attribute
*/
void setInterpolation(net.opengis.gml.SurfaceInterpolationType.Enum interpolation);
/**
* Sets (as xml) the "interpolation" attribute
*/
void xsetInterpolation(net.opengis.gml.SurfaceInterpolationType interpolation);
/**
* Unsets the "interpolation" attribute
*/
void unsetInterpolation();
/**
* A factory class with static methods for creating instances
* of this type.
*/
public static final class Factory
{
public static net.opengis.gml.RectangleType newInstance() {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }
public static net.opengis.gml.RectangleType newInstance(org.apache.xmlbeans.XmlOptions options) {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }
/** @param xmlAsString the string value to parse */
public static net.opengis.gml.RectangleType parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }
public static net.opengis.gml.RectangleType parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }
/** @param file the file from which to load an xml document */
public static net.opengis.gml.RectangleType parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }
public static net.opengis.gml.RectangleType parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }
public static net.opengis.gml.RectangleType parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }
public static net.opengis.gml.RectangleType parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }
public static net.opengis.gml.RectangleType parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }
public static net.opengis.gml.RectangleType parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }
public static net.opengis.gml.RectangleType parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }
public static net.opengis.gml.RectangleType parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }
public static net.opengis.gml.RectangleType parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }
public static net.opengis.gml.RectangleType parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }
public static net.opengis.gml.RectangleType parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }
public static net.opengis.gml.RectangleType parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.RectangleType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.RectangleType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.RectangleType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }
private Factory() { } // No instance of this class allowed
}
}
| apache-2.0 |
404neko/jandan_plus | app/src/main/java/com/socks/jandan/cache/BaseCache.java | 444 | package com.socks.jandan.cache;
import com.socks.greendao.DaoSession;
import java.util.ArrayList;
/**
* Created by zhaokaiqiang on 15/5/12.
*/
public abstract class BaseCache<T> {
public static final String DB_NAME = "jandan-db";
protected static DaoSession mDaoSession;
public abstract void clearAllCache();
public abstract ArrayList<T> getCacheByPage(int page);
public abstract void addResultCache(String result, int page);
}
| apache-2.0 |
termsuite/termsuite-ui | bundles/fr.univnantes.termsuite.ui/src/fr/univnantes/termsuite/ui/util/treeviewer/TreePart.java | 165 | package fr.univnantes.termsuite.ui.util.treeviewer;
import org.eclipse.jface.viewers.TreeViewer;
public interface TreePart {
public TreeViewer getTreeViewer();
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-blogger/v3/1.31.0/com/google/api/services/blogger/Blogger.java | 186139 | /*
* 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.blogger;
/**
* Service definition for Blogger (v3).
*
* <p>
* The Blogger API provides access to posts, comments and pages of a Blogger blog.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://developers.google.com/blogger/docs/3.0/getting_started" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link BloggerRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class Blogger 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 >= 32 ||
(com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION == 31 &&
com.google.api.client.googleapis.GoogleUtils.BUGFIX_VERSION >= 1)),
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.31.1 of google-api-client to run version " +
"1.32.1 of the Blogger API v3 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://blogger.googleapis.com/";
/**
* The default encoded mTLS root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.31
*/
public static final String DEFAULT_MTLS_ROOT_URL = "https://blogger.mtls.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 = "";
/**
* 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";
/**
* 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 Blogger(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
*/
Blogger(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 BlogUserInfos collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Blogger blogger = new Blogger(...);}
* {@code Blogger.BlogUserInfos.List request = blogger.blogUserInfos().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public BlogUserInfos blogUserInfos() {
return new BlogUserInfos();
}
/**
* The "blogUserInfos" collection of methods.
*/
public class BlogUserInfos {
/**
* Gets one blog and user info pair by blog id and user id.
*
* Create a request for the method "blogUserInfos.get".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param userId
* @param blogId
* @return the request
*/
public Get get(java.lang.String userId, java.lang.String blogId) throws java.io.IOException {
Get result = new Get(userId, blogId);
initialize(result);
return result;
}
public class Get extends BloggerRequest<com.google.api.services.blogger.model.BlogUserInfo> {
private static final String REST_PATH = "v3/users/{userId}/blogs/{blogId}";
/**
* Gets one blog and user info pair by blog id and user id.
*
* Create a request for the method "blogUserInfos.get".
*
* This request holds the parameters needed by the the blogger 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 userId
* @param blogId
* @since 1.13
*/
protected Get(java.lang.String userId, java.lang.String blogId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.BlogUserInfo.class);
this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified.");
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId 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 set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String userId;
/**
*/
public java.lang.String getUserId() {
return userId;
}
public Get setUserId(java.lang.String userId) {
this.userId = userId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Get setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.Long maxPosts;
/**
*/
public java.lang.Long getMaxPosts() {
return maxPosts;
}
public Get setMaxPosts(java.lang.Long maxPosts) {
this.maxPosts = maxPosts;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the Blogs collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Blogger blogger = new Blogger(...);}
* {@code Blogger.Blogs.List request = blogger.blogs().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Blogs blogs() {
return new Blogs();
}
/**
* The "blogs" collection of methods.
*/
public class Blogs {
/**
* Gets a blog by id.
*
* Create a request for the method "blogs.get".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param blogId
* @return the request
*/
public Get get(java.lang.String blogId) throws java.io.IOException {
Get result = new Get(blogId);
initialize(result);
return result;
}
public class Get extends BloggerRequest<com.google.api.services.blogger.model.Blog> {
private static final String REST_PATH = "v3/blogs/{blogId}";
/**
* Gets a blog by id.
*
* Create a request for the method "blogs.get".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @since 1.13
*/
protected Get(java.lang.String blogId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.Blog.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId 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 set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Get setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.Long maxPosts;
/**
*/
public java.lang.Long getMaxPosts() {
return maxPosts;
}
public Get setMaxPosts(java.lang.Long maxPosts) {
this.maxPosts = maxPosts;
return this;
}
@com.google.api.client.util.Key
private java.lang.String view;
/**
*/
public java.lang.String getView() {
return view;
}
public Get setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Gets a blog by url.
*
* Create a request for the method "blogs.getByUrl".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link GetByUrl#execute()} method to invoke the remote operation.
*
* @param url
* @return the request
*/
public GetByUrl getByUrl(java.lang.String url) throws java.io.IOException {
GetByUrl result = new GetByUrl(url);
initialize(result);
return result;
}
public class GetByUrl extends BloggerRequest<com.google.api.services.blogger.model.Blog> {
private static final String REST_PATH = "v3/blogs/byurl";
/**
* Gets a blog by url.
*
* Create a request for the method "blogs.getByUrl".
*
* This request holds the parameters needed by the the blogger server. After setting any optional
* parameters, call the {@link GetByUrl#execute()} method to invoke the remote operation. <p>
* {@link
* GetByUrl#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param url
* @since 1.13
*/
protected GetByUrl(java.lang.String url) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.Blog.class);
this.url = com.google.api.client.util.Preconditions.checkNotNull(url, "Required parameter url 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 GetByUrl set$Xgafv(java.lang.String $Xgafv) {
return (GetByUrl) super.set$Xgafv($Xgafv);
}
@Override
public GetByUrl setAccessToken(java.lang.String accessToken) {
return (GetByUrl) super.setAccessToken(accessToken);
}
@Override
public GetByUrl setAlt(java.lang.String alt) {
return (GetByUrl) super.setAlt(alt);
}
@Override
public GetByUrl setCallback(java.lang.String callback) {
return (GetByUrl) super.setCallback(callback);
}
@Override
public GetByUrl setFields(java.lang.String fields) {
return (GetByUrl) super.setFields(fields);
}
@Override
public GetByUrl setKey(java.lang.String key) {
return (GetByUrl) super.setKey(key);
}
@Override
public GetByUrl setOauthToken(java.lang.String oauthToken) {
return (GetByUrl) super.setOauthToken(oauthToken);
}
@Override
public GetByUrl setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GetByUrl) super.setPrettyPrint(prettyPrint);
}
@Override
public GetByUrl setQuotaUser(java.lang.String quotaUser) {
return (GetByUrl) super.setQuotaUser(quotaUser);
}
@Override
public GetByUrl setUploadType(java.lang.String uploadType) {
return (GetByUrl) super.setUploadType(uploadType);
}
@Override
public GetByUrl setUploadProtocol(java.lang.String uploadProtocol) {
return (GetByUrl) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String url;
/**
*/
public java.lang.String getUrl() {
return url;
}
public GetByUrl setUrl(java.lang.String url) {
this.url = url;
return this;
}
@com.google.api.client.util.Key
private java.lang.String view;
/**
*/
public java.lang.String getView() {
return view;
}
public GetByUrl setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public GetByUrl set(String parameterName, Object value) {
return (GetByUrl) super.set(parameterName, value);
}
}
/**
* Lists blogs by user.
*
* Create a request for the method "blogs.listByUser".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link ListByUser#execute()} method to invoke the remote operation.
*
* @param userId
* @return the request
*/
public ListByUser listByUser(java.lang.String userId) throws java.io.IOException {
ListByUser result = new ListByUser(userId);
initialize(result);
return result;
}
public class ListByUser extends BloggerRequest<com.google.api.services.blogger.model.BlogList> {
private static final String REST_PATH = "v3/users/{userId}/blogs";
/**
* Lists blogs by user.
*
* Create a request for the method "blogs.listByUser".
*
* This request holds the parameters needed by the the blogger server. After setting any optional
* parameters, call the {@link ListByUser#execute()} method to invoke the remote operation. <p>
* {@link
* ListByUser#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param userId
* @since 1.13
*/
protected ListByUser(java.lang.String userId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.BlogList.class);
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 ListByUser set$Xgafv(java.lang.String $Xgafv) {
return (ListByUser) super.set$Xgafv($Xgafv);
}
@Override
public ListByUser setAccessToken(java.lang.String accessToken) {
return (ListByUser) super.setAccessToken(accessToken);
}
@Override
public ListByUser setAlt(java.lang.String alt) {
return (ListByUser) super.setAlt(alt);
}
@Override
public ListByUser setCallback(java.lang.String callback) {
return (ListByUser) super.setCallback(callback);
}
@Override
public ListByUser setFields(java.lang.String fields) {
return (ListByUser) super.setFields(fields);
}
@Override
public ListByUser setKey(java.lang.String key) {
return (ListByUser) super.setKey(key);
}
@Override
public ListByUser setOauthToken(java.lang.String oauthToken) {
return (ListByUser) super.setOauthToken(oauthToken);
}
@Override
public ListByUser setPrettyPrint(java.lang.Boolean prettyPrint) {
return (ListByUser) super.setPrettyPrint(prettyPrint);
}
@Override
public ListByUser setQuotaUser(java.lang.String quotaUser) {
return (ListByUser) super.setQuotaUser(quotaUser);
}
@Override
public ListByUser setUploadType(java.lang.String uploadType) {
return (ListByUser) super.setUploadType(uploadType);
}
@Override
public ListByUser setUploadProtocol(java.lang.String uploadProtocol) {
return (ListByUser) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String userId;
/**
*/
public java.lang.String getUserId() {
return userId;
}
public ListByUser setUserId(java.lang.String userId) {
this.userId = userId;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchUserInfo;
/**
*/
public java.lang.Boolean getFetchUserInfo() {
return fetchUserInfo;
}
public ListByUser setFetchUserInfo(java.lang.Boolean fetchUserInfo) {
this.fetchUserInfo = fetchUserInfo;
return this;
}
@com.google.api.client.util.Key
private java.util.List<java.lang.String> role;
/**
*/
public java.util.List<java.lang.String> getRole() {
return role;
}
public ListByUser setRole(java.util.List<java.lang.String> role) {
this.role = role;
return this;
}
/** Default value of status is LIVE. */
@com.google.api.client.util.Key
private java.util.List<java.lang.String> status;
/** Default value of status is LIVE. [default: LIVE]
*/
public java.util.List<java.lang.String> getStatus() {
return status;
}
/** Default value of status is LIVE. */
public ListByUser setStatus(java.util.List<java.lang.String> status) {
this.status = status;
return this;
}
@com.google.api.client.util.Key
private java.lang.String view;
/**
*/
public java.lang.String getView() {
return view;
}
public ListByUser setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public ListByUser set(String parameterName, Object value) {
return (ListByUser) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the Comments collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Blogger blogger = new Blogger(...);}
* {@code Blogger.Comments.List request = blogger.comments().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Comments comments() {
return new Comments();
}
/**
* The "comments" collection of methods.
*/
public class Comments {
/**
* Marks a comment as not spam by blog id, post id and comment id.
*
* Create a request for the method "comments.approve".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Approve#execute()} method to invoke the remote operation.
*
* @param blogId
* @param postId
* @param commentId
* @return the request
*/
public Approve approve(java.lang.String blogId, java.lang.String postId, java.lang.String commentId) throws java.io.IOException {
Approve result = new Approve(blogId, postId, commentId);
initialize(result);
return result;
}
public class Approve extends BloggerRequest<com.google.api.services.blogger.model.Comment> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/{postId}/comments/{commentId}/approve";
/**
* Marks a comment as not spam by blog id, post id and comment id.
*
* Create a request for the method "comments.approve".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param postId
* @param commentId
* @since 1.13
*/
protected Approve(java.lang.String blogId, java.lang.String postId, java.lang.String commentId) {
super(Blogger.this, "POST", REST_PATH, null, com.google.api.services.blogger.model.Comment.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.postId = com.google.api.client.util.Preconditions.checkNotNull(postId, "Required parameter postId must be specified.");
this.commentId = com.google.api.client.util.Preconditions.checkNotNull(commentId, "Required parameter commentId must be specified.");
}
@Override
public Approve set$Xgafv(java.lang.String $Xgafv) {
return (Approve) super.set$Xgafv($Xgafv);
}
@Override
public Approve setAccessToken(java.lang.String accessToken) {
return (Approve) super.setAccessToken(accessToken);
}
@Override
public Approve setAlt(java.lang.String alt) {
return (Approve) super.setAlt(alt);
}
@Override
public Approve setCallback(java.lang.String callback) {
return (Approve) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Approve) super.setUploadType(uploadType);
}
@Override
public Approve setUploadProtocol(java.lang.String uploadProtocol) {
return (Approve) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Approve setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String postId;
/**
*/
public java.lang.String getPostId() {
return postId;
}
public Approve setPostId(java.lang.String postId) {
this.postId = postId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String commentId;
/**
*/
public java.lang.String getCommentId() {
return commentId;
}
public Approve setCommentId(java.lang.String commentId) {
this.commentId = commentId;
return this;
}
@Override
public Approve set(String parameterName, Object value) {
return (Approve) super.set(parameterName, value);
}
}
/**
* Deletes a comment by blog id, post id and comment id.
*
* Create a request for the method "comments.delete".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Delete#execute()} method to invoke the remote operation.
*
* @param blogId
* @param postId
* @param commentId
* @return the request
*/
public Delete delete(java.lang.String blogId, java.lang.String postId, java.lang.String commentId) throws java.io.IOException {
Delete result = new Delete(blogId, postId, commentId);
initialize(result);
return result;
}
public class Delete extends BloggerRequest<Void> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/{postId}/comments/{commentId}";
/**
* Deletes a comment by blog id, post id and comment id.
*
* Create a request for the method "comments.delete".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param postId
* @param commentId
* @since 1.13
*/
protected Delete(java.lang.String blogId, java.lang.String postId, java.lang.String commentId) {
super(Blogger.this, "DELETE", REST_PATH, null, Void.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.postId = com.google.api.client.util.Preconditions.checkNotNull(postId, "Required parameter postId must be specified.");
this.commentId = com.google.api.client.util.Preconditions.checkNotNull(commentId, "Required parameter commentId must be specified.");
}
@Override
public Delete set$Xgafv(java.lang.String $Xgafv) {
return (Delete) super.set$Xgafv($Xgafv);
}
@Override
public Delete setAccessToken(java.lang.String accessToken) {
return (Delete) super.setAccessToken(accessToken);
}
@Override
public Delete setAlt(java.lang.String alt) {
return (Delete) super.setAlt(alt);
}
@Override
public Delete setCallback(java.lang.String callback) {
return (Delete) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Delete) super.setUploadType(uploadType);
}
@Override
public Delete setUploadProtocol(java.lang.String uploadProtocol) {
return (Delete) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Delete setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String postId;
/**
*/
public java.lang.String getPostId() {
return postId;
}
public Delete setPostId(java.lang.String postId) {
this.postId = postId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String commentId;
/**
*/
public java.lang.String getCommentId() {
return commentId;
}
public Delete setCommentId(java.lang.String commentId) {
this.commentId = commentId;
return this;
}
@Override
public Delete set(String parameterName, Object value) {
return (Delete) super.set(parameterName, value);
}
}
/**
* Gets a comment by id.
*
* Create a request for the method "comments.get".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param blogId
* @param postId
* @param commentId
* @return the request
*/
public Get get(java.lang.String blogId, java.lang.String postId, java.lang.String commentId) throws java.io.IOException {
Get result = new Get(blogId, postId, commentId);
initialize(result);
return result;
}
public class Get extends BloggerRequest<com.google.api.services.blogger.model.Comment> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/{postId}/comments/{commentId}";
/**
* Gets a comment by id.
*
* Create a request for the method "comments.get".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param postId
* @param commentId
* @since 1.13
*/
protected Get(java.lang.String blogId, java.lang.String postId, java.lang.String commentId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.Comment.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.postId = com.google.api.client.util.Preconditions.checkNotNull(postId, "Required parameter postId must be specified.");
this.commentId = com.google.api.client.util.Preconditions.checkNotNull(commentId, "Required parameter commentId 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 set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Get setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String postId;
/**
*/
public java.lang.String getPostId() {
return postId;
}
public Get setPostId(java.lang.String postId) {
this.postId = postId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String commentId;
/**
*/
public java.lang.String getCommentId() {
return commentId;
}
public Get setCommentId(java.lang.String commentId) {
this.commentId = commentId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String view;
/**
*/
public java.lang.String getView() {
return view;
}
public Get setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Lists comments.
*
* Create a request for the method "comments.list".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param blogId
* @param postId
* @return the request
*/
public List list(java.lang.String blogId, java.lang.String postId) throws java.io.IOException {
List result = new List(blogId, postId);
initialize(result);
return result;
}
public class List extends BloggerRequest<com.google.api.services.blogger.model.CommentList> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/{postId}/comments";
/**
* Lists comments.
*
* Create a request for the method "comments.list".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param postId
* @since 1.13
*/
protected List(java.lang.String blogId, java.lang.String postId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.CommentList.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.postId = com.google.api.client.util.Preconditions.checkNotNull(postId, "Required parameter postId 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 set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public List setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String postId;
/**
*/
public java.lang.String getPostId() {
return postId;
}
public List setPostId(java.lang.String postId) {
this.postId = postId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String endDate;
/**
*/
public java.lang.String getEndDate() {
return endDate;
}
public List setEndDate(java.lang.String endDate) {
this.endDate = endDate;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchBodies;
/**
*/
public java.lang.Boolean getFetchBodies() {
return fetchBodies;
}
public List setFetchBodies(java.lang.Boolean fetchBodies) {
this.fetchBodies = fetchBodies;
return this;
}
@com.google.api.client.util.Key
private java.lang.Long maxResults;
/**
*/
public java.lang.Long getMaxResults() {
return maxResults;
}
public List setMaxResults(java.lang.Long maxResults) {
this.maxResults = maxResults;
return this;
}
@com.google.api.client.util.Key
private java.lang.String pageToken;
/**
*/
public java.lang.String getPageToken() {
return pageToken;
}
public List setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
@com.google.api.client.util.Key
private java.lang.String startDate;
/**
*/
public java.lang.String getStartDate() {
return startDate;
}
public List setStartDate(java.lang.String startDate) {
this.startDate = startDate;
return this;
}
@com.google.api.client.util.Key
private java.lang.String status;
/**
*/
public java.lang.String getStatus() {
return status;
}
public List setStatus(java.lang.String status) {
this.status = status;
return this;
}
@com.google.api.client.util.Key
private java.lang.String view;
/**
*/
public java.lang.String getView() {
return view;
}
public List setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
/**
* Lists comments by blog.
*
* Create a request for the method "comments.listByBlog".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link ListByBlog#execute()} method to invoke the remote operation.
*
* @param blogId
* @return the request
*/
public ListByBlog listByBlog(java.lang.String blogId) throws java.io.IOException {
ListByBlog result = new ListByBlog(blogId);
initialize(result);
return result;
}
public class ListByBlog extends BloggerRequest<com.google.api.services.blogger.model.CommentList> {
private static final String REST_PATH = "v3/blogs/{blogId}/comments";
/**
* Lists comments by blog.
*
* Create a request for the method "comments.listByBlog".
*
* This request holds the parameters needed by the the blogger server. After setting any optional
* parameters, call the {@link ListByBlog#execute()} method to invoke the remote operation. <p>
* {@link
* ListByBlog#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param blogId
* @since 1.13
*/
protected ListByBlog(java.lang.String blogId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.CommentList.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId 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 ListByBlog set$Xgafv(java.lang.String $Xgafv) {
return (ListByBlog) super.set$Xgafv($Xgafv);
}
@Override
public ListByBlog setAccessToken(java.lang.String accessToken) {
return (ListByBlog) super.setAccessToken(accessToken);
}
@Override
public ListByBlog setAlt(java.lang.String alt) {
return (ListByBlog) super.setAlt(alt);
}
@Override
public ListByBlog setCallback(java.lang.String callback) {
return (ListByBlog) super.setCallback(callback);
}
@Override
public ListByBlog setFields(java.lang.String fields) {
return (ListByBlog) super.setFields(fields);
}
@Override
public ListByBlog setKey(java.lang.String key) {
return (ListByBlog) super.setKey(key);
}
@Override
public ListByBlog setOauthToken(java.lang.String oauthToken) {
return (ListByBlog) super.setOauthToken(oauthToken);
}
@Override
public ListByBlog setPrettyPrint(java.lang.Boolean prettyPrint) {
return (ListByBlog) super.setPrettyPrint(prettyPrint);
}
@Override
public ListByBlog setQuotaUser(java.lang.String quotaUser) {
return (ListByBlog) super.setQuotaUser(quotaUser);
}
@Override
public ListByBlog setUploadType(java.lang.String uploadType) {
return (ListByBlog) super.setUploadType(uploadType);
}
@Override
public ListByBlog setUploadProtocol(java.lang.String uploadProtocol) {
return (ListByBlog) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public ListByBlog setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String endDate;
/**
*/
public java.lang.String getEndDate() {
return endDate;
}
public ListByBlog setEndDate(java.lang.String endDate) {
this.endDate = endDate;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchBodies;
/**
*/
public java.lang.Boolean getFetchBodies() {
return fetchBodies;
}
public ListByBlog setFetchBodies(java.lang.Boolean fetchBodies) {
this.fetchBodies = fetchBodies;
return this;
}
@com.google.api.client.util.Key
private java.lang.Long maxResults;
/**
*/
public java.lang.Long getMaxResults() {
return maxResults;
}
public ListByBlog setMaxResults(java.lang.Long maxResults) {
this.maxResults = maxResults;
return this;
}
@com.google.api.client.util.Key
private java.lang.String pageToken;
/**
*/
public java.lang.String getPageToken() {
return pageToken;
}
public ListByBlog setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
@com.google.api.client.util.Key
private java.lang.String startDate;
/**
*/
public java.lang.String getStartDate() {
return startDate;
}
public ListByBlog setStartDate(java.lang.String startDate) {
this.startDate = startDate;
return this;
}
@com.google.api.client.util.Key
private java.util.List<java.lang.String> status;
/**
*/
public java.util.List<java.lang.String> getStatus() {
return status;
}
public ListByBlog setStatus(java.util.List<java.lang.String> status) {
this.status = status;
return this;
}
@Override
public ListByBlog set(String parameterName, Object value) {
return (ListByBlog) super.set(parameterName, value);
}
}
/**
* Marks a comment as spam by blog id, post id and comment id.
*
* Create a request for the method "comments.markAsSpam".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link MarkAsSpam#execute()} method to invoke the remote operation.
*
* @param blogId
* @param postId
* @param commentId
* @return the request
*/
public MarkAsSpam markAsSpam(java.lang.String blogId, java.lang.String postId, java.lang.String commentId) throws java.io.IOException {
MarkAsSpam result = new MarkAsSpam(blogId, postId, commentId);
initialize(result);
return result;
}
public class MarkAsSpam extends BloggerRequest<com.google.api.services.blogger.model.Comment> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/{postId}/comments/{commentId}/spam";
/**
* Marks a comment as spam by blog id, post id and comment id.
*
* Create a request for the method "comments.markAsSpam".
*
* This request holds the parameters needed by the the blogger server. After setting any optional
* parameters, call the {@link MarkAsSpam#execute()} method to invoke the remote operation. <p>
* {@link
* MarkAsSpam#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param blogId
* @param postId
* @param commentId
* @since 1.13
*/
protected MarkAsSpam(java.lang.String blogId, java.lang.String postId, java.lang.String commentId) {
super(Blogger.this, "POST", REST_PATH, null, com.google.api.services.blogger.model.Comment.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.postId = com.google.api.client.util.Preconditions.checkNotNull(postId, "Required parameter postId must be specified.");
this.commentId = com.google.api.client.util.Preconditions.checkNotNull(commentId, "Required parameter commentId must be specified.");
}
@Override
public MarkAsSpam set$Xgafv(java.lang.String $Xgafv) {
return (MarkAsSpam) super.set$Xgafv($Xgafv);
}
@Override
public MarkAsSpam setAccessToken(java.lang.String accessToken) {
return (MarkAsSpam) super.setAccessToken(accessToken);
}
@Override
public MarkAsSpam setAlt(java.lang.String alt) {
return (MarkAsSpam) super.setAlt(alt);
}
@Override
public MarkAsSpam setCallback(java.lang.String callback) {
return (MarkAsSpam) super.setCallback(callback);
}
@Override
public MarkAsSpam setFields(java.lang.String fields) {
return (MarkAsSpam) super.setFields(fields);
}
@Override
public MarkAsSpam setKey(java.lang.String key) {
return (MarkAsSpam) super.setKey(key);
}
@Override
public MarkAsSpam setOauthToken(java.lang.String oauthToken) {
return (MarkAsSpam) super.setOauthToken(oauthToken);
}
@Override
public MarkAsSpam setPrettyPrint(java.lang.Boolean prettyPrint) {
return (MarkAsSpam) super.setPrettyPrint(prettyPrint);
}
@Override
public MarkAsSpam setQuotaUser(java.lang.String quotaUser) {
return (MarkAsSpam) super.setQuotaUser(quotaUser);
}
@Override
public MarkAsSpam setUploadType(java.lang.String uploadType) {
return (MarkAsSpam) super.setUploadType(uploadType);
}
@Override
public MarkAsSpam setUploadProtocol(java.lang.String uploadProtocol) {
return (MarkAsSpam) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public MarkAsSpam setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String postId;
/**
*/
public java.lang.String getPostId() {
return postId;
}
public MarkAsSpam setPostId(java.lang.String postId) {
this.postId = postId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String commentId;
/**
*/
public java.lang.String getCommentId() {
return commentId;
}
public MarkAsSpam setCommentId(java.lang.String commentId) {
this.commentId = commentId;
return this;
}
@Override
public MarkAsSpam set(String parameterName, Object value) {
return (MarkAsSpam) super.set(parameterName, value);
}
}
/**
* Removes the content of a comment by blog id, post id and comment id.
*
* Create a request for the method "comments.removeContent".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link RemoveContent#execute()} method to invoke the remote operation.
*
* @param blogId
* @param postId
* @param commentId
* @return the request
*/
public RemoveContent removeContent(java.lang.String blogId, java.lang.String postId, java.lang.String commentId) throws java.io.IOException {
RemoveContent result = new RemoveContent(blogId, postId, commentId);
initialize(result);
return result;
}
public class RemoveContent extends BloggerRequest<com.google.api.services.blogger.model.Comment> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/{postId}/comments/{commentId}/removecontent";
/**
* Removes the content of a comment by blog id, post id and comment id.
*
* Create a request for the method "comments.removeContent".
*
* This request holds the parameters needed by the the blogger server. After setting any optional
* parameters, call the {@link RemoveContent#execute()} method to invoke the remote operation. <p>
* {@link RemoveContent#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientR
* equest)} must be called to initialize this instance immediately after invoking the constructor.
* </p>
*
* @param blogId
* @param postId
* @param commentId
* @since 1.13
*/
protected RemoveContent(java.lang.String blogId, java.lang.String postId, java.lang.String commentId) {
super(Blogger.this, "POST", REST_PATH, null, com.google.api.services.blogger.model.Comment.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.postId = com.google.api.client.util.Preconditions.checkNotNull(postId, "Required parameter postId must be specified.");
this.commentId = com.google.api.client.util.Preconditions.checkNotNull(commentId, "Required parameter commentId must be specified.");
}
@Override
public RemoveContent set$Xgafv(java.lang.String $Xgafv) {
return (RemoveContent) super.set$Xgafv($Xgafv);
}
@Override
public RemoveContent setAccessToken(java.lang.String accessToken) {
return (RemoveContent) super.setAccessToken(accessToken);
}
@Override
public RemoveContent setAlt(java.lang.String alt) {
return (RemoveContent) super.setAlt(alt);
}
@Override
public RemoveContent setCallback(java.lang.String callback) {
return (RemoveContent) super.setCallback(callback);
}
@Override
public RemoveContent setFields(java.lang.String fields) {
return (RemoveContent) super.setFields(fields);
}
@Override
public RemoveContent setKey(java.lang.String key) {
return (RemoveContent) super.setKey(key);
}
@Override
public RemoveContent setOauthToken(java.lang.String oauthToken) {
return (RemoveContent) super.setOauthToken(oauthToken);
}
@Override
public RemoveContent setPrettyPrint(java.lang.Boolean prettyPrint) {
return (RemoveContent) super.setPrettyPrint(prettyPrint);
}
@Override
public RemoveContent setQuotaUser(java.lang.String quotaUser) {
return (RemoveContent) super.setQuotaUser(quotaUser);
}
@Override
public RemoveContent setUploadType(java.lang.String uploadType) {
return (RemoveContent) super.setUploadType(uploadType);
}
@Override
public RemoveContent setUploadProtocol(java.lang.String uploadProtocol) {
return (RemoveContent) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public RemoveContent setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String postId;
/**
*/
public java.lang.String getPostId() {
return postId;
}
public RemoveContent setPostId(java.lang.String postId) {
this.postId = postId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String commentId;
/**
*/
public java.lang.String getCommentId() {
return commentId;
}
public RemoveContent setCommentId(java.lang.String commentId) {
this.commentId = commentId;
return this;
}
@Override
public RemoveContent set(String parameterName, Object value) {
return (RemoveContent) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the PageViews collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Blogger blogger = new Blogger(...);}
* {@code Blogger.PageViews.List request = blogger.pageViews().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public PageViews pageViews() {
return new PageViews();
}
/**
* The "pageViews" collection of methods.
*/
public class PageViews {
/**
* Gets page views by blog id.
*
* Create a request for the method "pageViews.get".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param blogId
* @return the request
*/
public Get get(java.lang.String blogId) throws java.io.IOException {
Get result = new Get(blogId);
initialize(result);
return result;
}
public class Get extends BloggerRequest<com.google.api.services.blogger.model.Pageviews> {
private static final String REST_PATH = "v3/blogs/{blogId}/pageviews";
/**
* Gets page views by blog id.
*
* Create a request for the method "pageViews.get".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @since 1.13
*/
protected Get(java.lang.String blogId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.Pageviews.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId 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 set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Get setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.util.List<java.lang.String> range;
/**
*/
public java.util.List<java.lang.String> getRange() {
return range;
}
public Get setRange(java.util.List<java.lang.String> range) {
this.range = range;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the Pages collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Blogger blogger = new Blogger(...);}
* {@code Blogger.Pages.List request = blogger.pages().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Pages pages() {
return new Pages();
}
/**
* The "pages" collection of methods.
*/
public class Pages {
/**
* Deletes a page by blog id and page id.
*
* Create a request for the method "pages.delete".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Delete#execute()} method to invoke the remote operation.
*
* @param blogId
* @param pageId
* @return the request
*/
public Delete delete(java.lang.String blogId, java.lang.String pageId) throws java.io.IOException {
Delete result = new Delete(blogId, pageId);
initialize(result);
return result;
}
public class Delete extends BloggerRequest<Void> {
private static final String REST_PATH = "v3/blogs/{blogId}/pages/{pageId}";
/**
* Deletes a page by blog id and page id.
*
* Create a request for the method "pages.delete".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param pageId
* @since 1.13
*/
protected Delete(java.lang.String blogId, java.lang.String pageId) {
super(Blogger.this, "DELETE", REST_PATH, null, Void.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified.");
}
@Override
public Delete set$Xgafv(java.lang.String $Xgafv) {
return (Delete) super.set$Xgafv($Xgafv);
}
@Override
public Delete setAccessToken(java.lang.String accessToken) {
return (Delete) super.setAccessToken(accessToken);
}
@Override
public Delete setAlt(java.lang.String alt) {
return (Delete) super.setAlt(alt);
}
@Override
public Delete setCallback(java.lang.String callback) {
return (Delete) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Delete) super.setUploadType(uploadType);
}
@Override
public Delete setUploadProtocol(java.lang.String uploadProtocol) {
return (Delete) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Delete setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String pageId;
/**
*/
public java.lang.String getPageId() {
return pageId;
}
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);
}
}
/**
* Gets a page by blog id and page id.
*
* Create a request for the method "pages.get".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param blogId
* @param pageId
* @return the request
*/
public Get get(java.lang.String blogId, java.lang.String pageId) throws java.io.IOException {
Get result = new Get(blogId, pageId);
initialize(result);
return result;
}
public class Get extends BloggerRequest<com.google.api.services.blogger.model.Page> {
private static final String REST_PATH = "v3/blogs/{blogId}/pages/{pageId}";
/**
* Gets a page by blog id and page id.
*
* Create a request for the method "pages.get".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param pageId
* @since 1.13
*/
protected Get(java.lang.String blogId, java.lang.String pageId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.Page.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId 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 set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Get setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String pageId;
/**
*/
public java.lang.String getPageId() {
return pageId;
}
public Get setPageId(java.lang.String pageId) {
this.pageId = pageId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String view;
/**
*/
public java.lang.String getView() {
return view;
}
public Get setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Inserts a page.
*
* Create a request for the method "pages.insert".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Insert#execute()} method to invoke the remote operation.
*
* @param blogId
* @param content the {@link com.google.api.services.blogger.model.Page}
* @return the request
*/
public Insert insert(java.lang.String blogId, com.google.api.services.blogger.model.Page content) throws java.io.IOException {
Insert result = new Insert(blogId, content);
initialize(result);
return result;
}
public class Insert extends BloggerRequest<com.google.api.services.blogger.model.Page> {
private static final String REST_PATH = "v3/blogs/{blogId}/pages";
/**
* Inserts a page.
*
* Create a request for the method "pages.insert".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param content the {@link com.google.api.services.blogger.model.Page}
* @since 1.13
*/
protected Insert(java.lang.String blogId, com.google.api.services.blogger.model.Page content) {
super(Blogger.this, "POST", REST_PATH, content, com.google.api.services.blogger.model.Page.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
}
@Override
public Insert set$Xgafv(java.lang.String $Xgafv) {
return (Insert) super.set$Xgafv($Xgafv);
}
@Override
public Insert setAccessToken(java.lang.String accessToken) {
return (Insert) super.setAccessToken(accessToken);
}
@Override
public Insert setAlt(java.lang.String alt) {
return (Insert) super.setAlt(alt);
}
@Override
public Insert setCallback(java.lang.String callback) {
return (Insert) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Insert) super.setUploadType(uploadType);
}
@Override
public Insert setUploadProtocol(java.lang.String uploadProtocol) {
return (Insert) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Insert setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean isDraft;
/**
*/
public java.lang.Boolean getIsDraft() {
return isDraft;
}
public Insert setIsDraft(java.lang.Boolean isDraft) {
this.isDraft = isDraft;
return this;
}
@Override
public Insert set(String parameterName, Object value) {
return (Insert) super.set(parameterName, value);
}
}
/**
* Lists pages.
*
* Create a request for the method "pages.list".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param blogId
* @return the request
*/
public List list(java.lang.String blogId) throws java.io.IOException {
List result = new List(blogId);
initialize(result);
return result;
}
public class List extends BloggerRequest<com.google.api.services.blogger.model.PageList> {
private static final String REST_PATH = "v3/blogs/{blogId}/pages";
/**
* Lists pages.
*
* Create a request for the method "pages.list".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @since 1.13
*/
protected List(java.lang.String blogId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.PageList.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId 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 set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public List setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchBodies;
/**
*/
public java.lang.Boolean getFetchBodies() {
return fetchBodies;
}
public List setFetchBodies(java.lang.Boolean fetchBodies) {
this.fetchBodies = fetchBodies;
return this;
}
@com.google.api.client.util.Key
private java.lang.Long maxResults;
/**
*/
public java.lang.Long getMaxResults() {
return maxResults;
}
public List setMaxResults(java.lang.Long maxResults) {
this.maxResults = maxResults;
return this;
}
@com.google.api.client.util.Key
private java.lang.String pageToken;
/**
*/
public java.lang.String getPageToken() {
return pageToken;
}
public List setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
@com.google.api.client.util.Key
private java.util.List<java.lang.String> status;
/**
*/
public java.util.List<java.lang.String> getStatus() {
return status;
}
public List setStatus(java.util.List<java.lang.String> status) {
this.status = status;
return this;
}
@com.google.api.client.util.Key
private java.lang.String view;
/**
*/
public java.lang.String getView() {
return view;
}
public List setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
/**
* Patches a page.
*
* Create a request for the method "pages.patch".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Patch#execute()} method to invoke the remote operation.
*
* @param blogId
* @param pageId
* @param content the {@link com.google.api.services.blogger.model.Page}
* @return the request
*/
public Patch patch(java.lang.String blogId, java.lang.String pageId, com.google.api.services.blogger.model.Page content) throws java.io.IOException {
Patch result = new Patch(blogId, pageId, content);
initialize(result);
return result;
}
public class Patch extends BloggerRequest<com.google.api.services.blogger.model.Page> {
private static final String REST_PATH = "v3/blogs/{blogId}/pages/{pageId}";
/**
* Patches a page.
*
* Create a request for the method "pages.patch".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param pageId
* @param content the {@link com.google.api.services.blogger.model.Page}
* @since 1.13
*/
protected Patch(java.lang.String blogId, java.lang.String pageId, com.google.api.services.blogger.model.Page content) {
super(Blogger.this, "PATCH", REST_PATH, content, com.google.api.services.blogger.model.Page.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified.");
}
@Override
public Patch set$Xgafv(java.lang.String $Xgafv) {
return (Patch) super.set$Xgafv($Xgafv);
}
@Override
public Patch setAccessToken(java.lang.String accessToken) {
return (Patch) super.setAccessToken(accessToken);
}
@Override
public Patch setAlt(java.lang.String alt) {
return (Patch) super.setAlt(alt);
}
@Override
public Patch setCallback(java.lang.String callback) {
return (Patch) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Patch) super.setUploadType(uploadType);
}
@Override
public Patch setUploadProtocol(java.lang.String uploadProtocol) {
return (Patch) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Patch setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String pageId;
/**
*/
public java.lang.String getPageId() {
return pageId;
}
public Patch setPageId(java.lang.String pageId) {
this.pageId = pageId;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean publish;
/**
*/
public java.lang.Boolean getPublish() {
return publish;
}
public Patch setPublish(java.lang.Boolean publish) {
this.publish = publish;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean revert;
/**
*/
public java.lang.Boolean getRevert() {
return revert;
}
public Patch setRevert(java.lang.Boolean revert) {
this.revert = revert;
return this;
}
@Override
public Patch set(String parameterName, Object value) {
return (Patch) super.set(parameterName, value);
}
}
/**
* Publishes a page.
*
* Create a request for the method "pages.publish".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Publish#execute()} method to invoke the remote operation.
*
* @param blogId
* @param pageId
* @return the request
*/
public Publish publish(java.lang.String blogId, java.lang.String pageId) throws java.io.IOException {
Publish result = new Publish(blogId, pageId);
initialize(result);
return result;
}
public class Publish extends BloggerRequest<com.google.api.services.blogger.model.Page> {
private static final String REST_PATH = "v3/blogs/{blogId}/pages/{pageId}/publish";
/**
* Publishes a page.
*
* Create a request for the method "pages.publish".
*
* This request holds the parameters needed by the the blogger server. After setting any optional
* parameters, call the {@link Publish#execute()} method to invoke the remote operation. <p>
* {@link
* Publish#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param blogId
* @param pageId
* @since 1.13
*/
protected Publish(java.lang.String blogId, java.lang.String pageId) {
super(Blogger.this, "POST", REST_PATH, null, com.google.api.services.blogger.model.Page.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified.");
}
@Override
public Publish set$Xgafv(java.lang.String $Xgafv) {
return (Publish) super.set$Xgafv($Xgafv);
}
@Override
public Publish setAccessToken(java.lang.String accessToken) {
return (Publish) super.setAccessToken(accessToken);
}
@Override
public Publish setAlt(java.lang.String alt) {
return (Publish) super.setAlt(alt);
}
@Override
public Publish setCallback(java.lang.String callback) {
return (Publish) super.setCallback(callback);
}
@Override
public Publish setFields(java.lang.String fields) {
return (Publish) super.setFields(fields);
}
@Override
public Publish setKey(java.lang.String key) {
return (Publish) super.setKey(key);
}
@Override
public Publish setOauthToken(java.lang.String oauthToken) {
return (Publish) super.setOauthToken(oauthToken);
}
@Override
public Publish setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Publish) super.setPrettyPrint(prettyPrint);
}
@Override
public Publish setQuotaUser(java.lang.String quotaUser) {
return (Publish) super.setQuotaUser(quotaUser);
}
@Override
public Publish setUploadType(java.lang.String uploadType) {
return (Publish) super.setUploadType(uploadType);
}
@Override
public Publish setUploadProtocol(java.lang.String uploadProtocol) {
return (Publish) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Publish setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String pageId;
/**
*/
public java.lang.String getPageId() {
return pageId;
}
public Publish setPageId(java.lang.String pageId) {
this.pageId = pageId;
return this;
}
@Override
public Publish set(String parameterName, Object value) {
return (Publish) super.set(parameterName, value);
}
}
/**
* Reverts a published or scheduled page to draft state.
*
* Create a request for the method "pages.revert".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Revert#execute()} method to invoke the remote operation.
*
* @param blogId
* @param pageId
* @return the request
*/
public Revert revert(java.lang.String blogId, java.lang.String pageId) throws java.io.IOException {
Revert result = new Revert(blogId, pageId);
initialize(result);
return result;
}
public class Revert extends BloggerRequest<com.google.api.services.blogger.model.Page> {
private static final String REST_PATH = "v3/blogs/{blogId}/pages/{pageId}/revert";
/**
* Reverts a published or scheduled page to draft state.
*
* Create a request for the method "pages.revert".
*
* This request holds the parameters needed by the the blogger server. After setting any optional
* parameters, call the {@link Revert#execute()} method to invoke the remote operation. <p> {@link
* Revert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param blogId
* @param pageId
* @since 1.13
*/
protected Revert(java.lang.String blogId, java.lang.String pageId) {
super(Blogger.this, "POST", REST_PATH, null, com.google.api.services.blogger.model.Page.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified.");
}
@Override
public Revert set$Xgafv(java.lang.String $Xgafv) {
return (Revert) super.set$Xgafv($Xgafv);
}
@Override
public Revert setAccessToken(java.lang.String accessToken) {
return (Revert) super.setAccessToken(accessToken);
}
@Override
public Revert setAlt(java.lang.String alt) {
return (Revert) super.setAlt(alt);
}
@Override
public Revert setCallback(java.lang.String callback) {
return (Revert) super.setCallback(callback);
}
@Override
public Revert setFields(java.lang.String fields) {
return (Revert) super.setFields(fields);
}
@Override
public Revert setKey(java.lang.String key) {
return (Revert) super.setKey(key);
}
@Override
public Revert setOauthToken(java.lang.String oauthToken) {
return (Revert) super.setOauthToken(oauthToken);
}
@Override
public Revert setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Revert) super.setPrettyPrint(prettyPrint);
}
@Override
public Revert setQuotaUser(java.lang.String quotaUser) {
return (Revert) super.setQuotaUser(quotaUser);
}
@Override
public Revert setUploadType(java.lang.String uploadType) {
return (Revert) super.setUploadType(uploadType);
}
@Override
public Revert setUploadProtocol(java.lang.String uploadProtocol) {
return (Revert) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Revert setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String pageId;
/**
*/
public java.lang.String getPageId() {
return pageId;
}
public Revert setPageId(java.lang.String pageId) {
this.pageId = pageId;
return this;
}
@Override
public Revert set(String parameterName, Object value) {
return (Revert) super.set(parameterName, value);
}
}
/**
* Updates a page by blog id and page id.
*
* Create a request for the method "pages.update".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Update#execute()} method to invoke the remote operation.
*
* @param blogId
* @param pageId
* @param content the {@link com.google.api.services.blogger.model.Page}
* @return the request
*/
public Update update(java.lang.String blogId, java.lang.String pageId, com.google.api.services.blogger.model.Page content) throws java.io.IOException {
Update result = new Update(blogId, pageId, content);
initialize(result);
return result;
}
public class Update extends BloggerRequest<com.google.api.services.blogger.model.Page> {
private static final String REST_PATH = "v3/blogs/{blogId}/pages/{pageId}";
/**
* Updates a page by blog id and page id.
*
* Create a request for the method "pages.update".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param pageId
* @param content the {@link com.google.api.services.blogger.model.Page}
* @since 1.13
*/
protected Update(java.lang.String blogId, java.lang.String pageId, com.google.api.services.blogger.model.Page content) {
super(Blogger.this, "PUT", REST_PATH, content, com.google.api.services.blogger.model.Page.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.pageId = com.google.api.client.util.Preconditions.checkNotNull(pageId, "Required parameter pageId must be specified.");
}
@Override
public Update set$Xgafv(java.lang.String $Xgafv) {
return (Update) super.set$Xgafv($Xgafv);
}
@Override
public Update setAccessToken(java.lang.String accessToken) {
return (Update) super.setAccessToken(accessToken);
}
@Override
public Update setAlt(java.lang.String alt) {
return (Update) super.setAlt(alt);
}
@Override
public Update setCallback(java.lang.String callback) {
return (Update) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Update) super.setUploadType(uploadType);
}
@Override
public Update setUploadProtocol(java.lang.String uploadProtocol) {
return (Update) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Update setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String pageId;
/**
*/
public java.lang.String getPageId() {
return pageId;
}
public Update setPageId(java.lang.String pageId) {
this.pageId = pageId;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean publish;
/**
*/
public java.lang.Boolean getPublish() {
return publish;
}
public Update setPublish(java.lang.Boolean publish) {
this.publish = publish;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean revert;
/**
*/
public java.lang.Boolean getRevert() {
return revert;
}
public Update setRevert(java.lang.Boolean revert) {
this.revert = revert;
return this;
}
@Override
public Update set(String parameterName, Object value) {
return (Update) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the PostUserInfos collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Blogger blogger = new Blogger(...);}
* {@code Blogger.PostUserInfos.List request = blogger.postUserInfos().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public PostUserInfos postUserInfos() {
return new PostUserInfos();
}
/**
* The "postUserInfos" collection of methods.
*/
public class PostUserInfos {
/**
* Gets one post and user info pair, by post_id and user_id.
*
* Create a request for the method "postUserInfos.get".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param userId
* @param blogId
* @param postId
* @return the request
*/
public Get get(java.lang.String userId, java.lang.String blogId, java.lang.String postId) throws java.io.IOException {
Get result = new Get(userId, blogId, postId);
initialize(result);
return result;
}
public class Get extends BloggerRequest<com.google.api.services.blogger.model.PostUserInfo> {
private static final String REST_PATH = "v3/users/{userId}/blogs/{blogId}/posts/{postId}";
/**
* Gets one post and user info pair, by post_id and user_id.
*
* Create a request for the method "postUserInfos.get".
*
* This request holds the parameters needed by the the blogger 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 userId
* @param blogId
* @param postId
* @since 1.13
*/
protected Get(java.lang.String userId, java.lang.String blogId, java.lang.String postId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.PostUserInfo.class);
this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified.");
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.postId = com.google.api.client.util.Preconditions.checkNotNull(postId, "Required parameter postId 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 set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String userId;
/**
*/
public java.lang.String getUserId() {
return userId;
}
public Get setUserId(java.lang.String userId) {
this.userId = userId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Get setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String postId;
/**
*/
public java.lang.String getPostId() {
return postId;
}
public Get setPostId(java.lang.String postId) {
this.postId = postId;
return this;
}
@com.google.api.client.util.Key
private java.lang.Long maxComments;
/**
*/
public java.lang.Long getMaxComments() {
return maxComments;
}
public Get setMaxComments(java.lang.Long maxComments) {
this.maxComments = maxComments;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Lists post and user info pairs.
*
* Create a request for the method "postUserInfos.list".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param userId
* @param blogId
* @return the request
*/
public List list(java.lang.String userId, java.lang.String blogId) throws java.io.IOException {
List result = new List(userId, blogId);
initialize(result);
return result;
}
public class List extends BloggerRequest<com.google.api.services.blogger.model.PostUserInfosList> {
private static final String REST_PATH = "v3/users/{userId}/blogs/{blogId}/posts";
/**
* Lists post and user info pairs.
*
* Create a request for the method "postUserInfos.list".
*
* This request holds the parameters needed by the the blogger 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 userId
* @param blogId
* @since 1.13
*/
protected List(java.lang.String userId, java.lang.String blogId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.PostUserInfosList.class);
this.userId = com.google.api.client.util.Preconditions.checkNotNull(userId, "Required parameter userId must be specified.");
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId 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 set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String userId;
/**
*/
public java.lang.String getUserId() {
return userId;
}
public List setUserId(java.lang.String userId) {
this.userId = userId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public List setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String endDate;
/**
*/
public java.lang.String getEndDate() {
return endDate;
}
public List setEndDate(java.lang.String endDate) {
this.endDate = endDate;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchBodies;
/**
[ default: false]
[
*/
public java.lang.Boolean getFetchBodies() {
return fetchBodies;
}
public List setFetchBodies(java.lang.Boolean fetchBodies) {
this.fetchBodies = fetchBodies;
return this;
}
/**
* Convenience method that returns only {@link Boolean#TRUE} or {@link Boolean#FALSE}.
*
* <p>
* Boolean properties can have four possible values:
* {@code null}, {@link com.google.api.client.util.Data#NULL_BOOLEAN}, {@link Boolean#TRUE}
* or {@link Boolean#FALSE}.
* </p>
*
* <p>
* This method returns {@link Boolean#TRUE} if the default of the property is {@link Boolean#TRUE}
* and it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* {@link Boolean#FALSE} is returned if the default of the property is {@link Boolean#FALSE} and
* it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* </p>
*
* <p>
*
* </p>
*/
public boolean isFetchBodies() {
if (fetchBodies == null || fetchBodies == com.google.api.client.util.Data.NULL_BOOLEAN) {
return false;
}
return fetchBodies;
}
@com.google.api.client.util.Key
private java.lang.String labels;
/**
*/
public java.lang.String getLabels() {
return labels;
}
public List setLabels(java.lang.String labels) {
this.labels = labels;
return this;
}
@com.google.api.client.util.Key
private java.lang.Long maxResults;
/**
*/
public java.lang.Long getMaxResults() {
return maxResults;
}
public List setMaxResults(java.lang.Long maxResults) {
this.maxResults = maxResults;
return this;
}
@com.google.api.client.util.Key
private java.lang.String orderBy;
/**
[ default: PUBLISHED]
[
*/
public java.lang.String getOrderBy() {
return orderBy;
}
public List setOrderBy(java.lang.String orderBy) {
this.orderBy = orderBy;
return this;
}
@com.google.api.client.util.Key
private java.lang.String pageToken;
/**
*/
public java.lang.String getPageToken() {
return pageToken;
}
public List setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
@com.google.api.client.util.Key
private java.lang.String startDate;
/**
*/
public java.lang.String getStartDate() {
return startDate;
}
public List setStartDate(java.lang.String startDate) {
this.startDate = startDate;
return this;
}
@com.google.api.client.util.Key
private java.util.List<java.lang.String> status;
/**
*/
public java.util.List<java.lang.String> getStatus() {
return status;
}
public List setStatus(java.util.List<java.lang.String> status) {
this.status = status;
return this;
}
@com.google.api.client.util.Key
private java.lang.String view;
/**
*/
public java.lang.String getView() {
return view;
}
public List setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the Posts collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Blogger blogger = new Blogger(...);}
* {@code Blogger.Posts.List request = blogger.posts().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Posts posts() {
return new Posts();
}
/**
* The "posts" collection of methods.
*/
public class Posts {
/**
* Deletes a post by blog id and post id.
*
* Create a request for the method "posts.delete".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Delete#execute()} method to invoke the remote operation.
*
* @param blogId
* @param postId
* @return the request
*/
public Delete delete(java.lang.String blogId, java.lang.String postId) throws java.io.IOException {
Delete result = new Delete(blogId, postId);
initialize(result);
return result;
}
public class Delete extends BloggerRequest<Void> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/{postId}";
/**
* Deletes a post by blog id and post id.
*
* Create a request for the method "posts.delete".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param postId
* @since 1.13
*/
protected Delete(java.lang.String blogId, java.lang.String postId) {
super(Blogger.this, "DELETE", REST_PATH, null, Void.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.postId = com.google.api.client.util.Preconditions.checkNotNull(postId, "Required parameter postId must be specified.");
}
@Override
public Delete set$Xgafv(java.lang.String $Xgafv) {
return (Delete) super.set$Xgafv($Xgafv);
}
@Override
public Delete setAccessToken(java.lang.String accessToken) {
return (Delete) super.setAccessToken(accessToken);
}
@Override
public Delete setAlt(java.lang.String alt) {
return (Delete) super.setAlt(alt);
}
@Override
public Delete setCallback(java.lang.String callback) {
return (Delete) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Delete) super.setUploadType(uploadType);
}
@Override
public Delete setUploadProtocol(java.lang.String uploadProtocol) {
return (Delete) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Delete setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String postId;
/**
*/
public java.lang.String getPostId() {
return postId;
}
public Delete setPostId(java.lang.String postId) {
this.postId = postId;
return this;
}
@Override
public Delete set(String parameterName, Object value) {
return (Delete) super.set(parameterName, value);
}
}
/**
* Gets a post by blog id and post id
*
* Create a request for the method "posts.get".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param blogId
* @param postId
* @return the request
*/
public Get get(java.lang.String blogId, java.lang.String postId) throws java.io.IOException {
Get result = new Get(blogId, postId);
initialize(result);
return result;
}
public class Get extends BloggerRequest<com.google.api.services.blogger.model.Post> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/{postId}";
/**
* Gets a post by blog id and post id
*
* Create a request for the method "posts.get".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param postId
* @since 1.13
*/
protected Get(java.lang.String blogId, java.lang.String postId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.Post.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.postId = com.google.api.client.util.Preconditions.checkNotNull(postId, "Required parameter postId 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 set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Get setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String postId;
/**
*/
public java.lang.String getPostId() {
return postId;
}
public Get setPostId(java.lang.String postId) {
this.postId = postId;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchBody;
/**
[ default: true]
[
*/
public java.lang.Boolean getFetchBody() {
return fetchBody;
}
public Get setFetchBody(java.lang.Boolean fetchBody) {
this.fetchBody = fetchBody;
return this;
}
/**
* Convenience method that returns only {@link Boolean#TRUE} or {@link Boolean#FALSE}.
*
* <p>
* Boolean properties can have four possible values:
* {@code null}, {@link com.google.api.client.util.Data#NULL_BOOLEAN}, {@link Boolean#TRUE}
* or {@link Boolean#FALSE}.
* </p>
*
* <p>
* This method returns {@link Boolean#TRUE} if the default of the property is {@link Boolean#TRUE}
* and it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* {@link Boolean#FALSE} is returned if the default of the property is {@link Boolean#FALSE} and
* it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* </p>
*
* <p>
*
* </p>
*/
public boolean isFetchBody() {
if (fetchBody == null || fetchBody == com.google.api.client.util.Data.NULL_BOOLEAN) {
return true;
}
return fetchBody;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchImages;
/**
*/
public java.lang.Boolean getFetchImages() {
return fetchImages;
}
public Get setFetchImages(java.lang.Boolean fetchImages) {
this.fetchImages = fetchImages;
return this;
}
@com.google.api.client.util.Key
private java.lang.Long maxComments;
/**
*/
public java.lang.Long getMaxComments() {
return maxComments;
}
public Get setMaxComments(java.lang.Long maxComments) {
this.maxComments = maxComments;
return this;
}
@com.google.api.client.util.Key
private java.lang.String view;
/**
*/
public java.lang.String getView() {
return view;
}
public Get setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Gets a post by path.
*
* Create a request for the method "posts.getByPath".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link GetByPath#execute()} method to invoke the remote operation.
*
* @param blogId
* @param path
* @return the request
*/
public GetByPath getByPath(java.lang.String blogId, java.lang.String path) throws java.io.IOException {
GetByPath result = new GetByPath(blogId, path);
initialize(result);
return result;
}
public class GetByPath extends BloggerRequest<com.google.api.services.blogger.model.Post> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/bypath";
/**
* Gets a post by path.
*
* Create a request for the method "posts.getByPath".
*
* This request holds the parameters needed by the the blogger server. After setting any optional
* parameters, call the {@link GetByPath#execute()} method to invoke the remote operation. <p>
* {@link
* GetByPath#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param blogId
* @param path
* @since 1.13
*/
protected GetByPath(java.lang.String blogId, java.lang.String path) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.Post.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.path = com.google.api.client.util.Preconditions.checkNotNull(path, "Required parameter path 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 GetByPath set$Xgafv(java.lang.String $Xgafv) {
return (GetByPath) super.set$Xgafv($Xgafv);
}
@Override
public GetByPath setAccessToken(java.lang.String accessToken) {
return (GetByPath) super.setAccessToken(accessToken);
}
@Override
public GetByPath setAlt(java.lang.String alt) {
return (GetByPath) super.setAlt(alt);
}
@Override
public GetByPath setCallback(java.lang.String callback) {
return (GetByPath) super.setCallback(callback);
}
@Override
public GetByPath setFields(java.lang.String fields) {
return (GetByPath) super.setFields(fields);
}
@Override
public GetByPath setKey(java.lang.String key) {
return (GetByPath) super.setKey(key);
}
@Override
public GetByPath setOauthToken(java.lang.String oauthToken) {
return (GetByPath) super.setOauthToken(oauthToken);
}
@Override
public GetByPath setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GetByPath) super.setPrettyPrint(prettyPrint);
}
@Override
public GetByPath setQuotaUser(java.lang.String quotaUser) {
return (GetByPath) super.setQuotaUser(quotaUser);
}
@Override
public GetByPath setUploadType(java.lang.String uploadType) {
return (GetByPath) super.setUploadType(uploadType);
}
@Override
public GetByPath setUploadProtocol(java.lang.String uploadProtocol) {
return (GetByPath) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public GetByPath setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String path;
/**
*/
public java.lang.String getPath() {
return path;
}
public GetByPath setPath(java.lang.String path) {
this.path = path;
return this;
}
@com.google.api.client.util.Key
private java.lang.Long maxComments;
/**
*/
public java.lang.Long getMaxComments() {
return maxComments;
}
public GetByPath setMaxComments(java.lang.Long maxComments) {
this.maxComments = maxComments;
return this;
}
@com.google.api.client.util.Key
private java.lang.String view;
/**
*/
public java.lang.String getView() {
return view;
}
public GetByPath setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public GetByPath set(String parameterName, Object value) {
return (GetByPath) super.set(parameterName, value);
}
}
/**
* Inserts a post.
*
* Create a request for the method "posts.insert".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Insert#execute()} method to invoke the remote operation.
*
* @param blogId
* @param content the {@link com.google.api.services.blogger.model.Post}
* @return the request
*/
public Insert insert(java.lang.String blogId, com.google.api.services.blogger.model.Post content) throws java.io.IOException {
Insert result = new Insert(blogId, content);
initialize(result);
return result;
}
public class Insert extends BloggerRequest<com.google.api.services.blogger.model.Post> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts";
/**
* Inserts a post.
*
* Create a request for the method "posts.insert".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param content the {@link com.google.api.services.blogger.model.Post}
* @since 1.13
*/
protected Insert(java.lang.String blogId, com.google.api.services.blogger.model.Post content) {
super(Blogger.this, "POST", REST_PATH, content, com.google.api.services.blogger.model.Post.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
}
@Override
public Insert set$Xgafv(java.lang.String $Xgafv) {
return (Insert) super.set$Xgafv($Xgafv);
}
@Override
public Insert setAccessToken(java.lang.String accessToken) {
return (Insert) super.setAccessToken(accessToken);
}
@Override
public Insert setAlt(java.lang.String alt) {
return (Insert) super.setAlt(alt);
}
@Override
public Insert setCallback(java.lang.String callback) {
return (Insert) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Insert) super.setUploadType(uploadType);
}
@Override
public Insert setUploadProtocol(java.lang.String uploadProtocol) {
return (Insert) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Insert setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchBody;
/**
[ default: true]
[
*/
public java.lang.Boolean getFetchBody() {
return fetchBody;
}
public Insert setFetchBody(java.lang.Boolean fetchBody) {
this.fetchBody = fetchBody;
return this;
}
/**
* Convenience method that returns only {@link Boolean#TRUE} or {@link Boolean#FALSE}.
*
* <p>
* Boolean properties can have four possible values:
* {@code null}, {@link com.google.api.client.util.Data#NULL_BOOLEAN}, {@link Boolean#TRUE}
* or {@link Boolean#FALSE}.
* </p>
*
* <p>
* This method returns {@link Boolean#TRUE} if the default of the property is {@link Boolean#TRUE}
* and it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* {@link Boolean#FALSE} is returned if the default of the property is {@link Boolean#FALSE} and
* it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* </p>
*
* <p>
*
* </p>
*/
public boolean isFetchBody() {
if (fetchBody == null || fetchBody == com.google.api.client.util.Data.NULL_BOOLEAN) {
return true;
}
return fetchBody;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchImages;
/**
*/
public java.lang.Boolean getFetchImages() {
return fetchImages;
}
public Insert setFetchImages(java.lang.Boolean fetchImages) {
this.fetchImages = fetchImages;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean isDraft;
/**
*/
public java.lang.Boolean getIsDraft() {
return isDraft;
}
public Insert setIsDraft(java.lang.Boolean isDraft) {
this.isDraft = isDraft;
return this;
}
@Override
public Insert set(String parameterName, Object value) {
return (Insert) super.set(parameterName, value);
}
}
/**
* Lists posts.
*
* Create a request for the method "posts.list".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param blogId
* @return the request
*/
public List list(java.lang.String blogId) throws java.io.IOException {
List result = new List(blogId);
initialize(result);
return result;
}
public class List extends BloggerRequest<com.google.api.services.blogger.model.PostList> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts";
/**
* Lists posts.
*
* Create a request for the method "posts.list".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @since 1.13
*/
protected List(java.lang.String blogId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.PostList.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId 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 set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public List setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String endDate;
/**
*/
public java.lang.String getEndDate() {
return endDate;
}
public List setEndDate(java.lang.String endDate) {
this.endDate = endDate;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchBodies;
/**
[ default: true]
[
*/
public java.lang.Boolean getFetchBodies() {
return fetchBodies;
}
public List setFetchBodies(java.lang.Boolean fetchBodies) {
this.fetchBodies = fetchBodies;
return this;
}
/**
* Convenience method that returns only {@link Boolean#TRUE} or {@link Boolean#FALSE}.
*
* <p>
* Boolean properties can have four possible values:
* {@code null}, {@link com.google.api.client.util.Data#NULL_BOOLEAN}, {@link Boolean#TRUE}
* or {@link Boolean#FALSE}.
* </p>
*
* <p>
* This method returns {@link Boolean#TRUE} if the default of the property is {@link Boolean#TRUE}
* and it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* {@link Boolean#FALSE} is returned if the default of the property is {@link Boolean#FALSE} and
* it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* </p>
*
* <p>
*
* </p>
*/
public boolean isFetchBodies() {
if (fetchBodies == null || fetchBodies == com.google.api.client.util.Data.NULL_BOOLEAN) {
return true;
}
return fetchBodies;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchImages;
/**
*/
public java.lang.Boolean getFetchImages() {
return fetchImages;
}
public List setFetchImages(java.lang.Boolean fetchImages) {
this.fetchImages = fetchImages;
return this;
}
@com.google.api.client.util.Key
private java.lang.String labels;
/**
*/
public java.lang.String getLabels() {
return labels;
}
public List setLabels(java.lang.String labels) {
this.labels = labels;
return this;
}
@com.google.api.client.util.Key
private java.lang.Long maxResults;
/**
*/
public java.lang.Long getMaxResults() {
return maxResults;
}
public List setMaxResults(java.lang.Long maxResults) {
this.maxResults = maxResults;
return this;
}
@com.google.api.client.util.Key
private java.lang.String orderBy;
/**
[ default: PUBLISHED]
[
*/
public java.lang.String getOrderBy() {
return orderBy;
}
public List setOrderBy(java.lang.String orderBy) {
this.orderBy = orderBy;
return this;
}
@com.google.api.client.util.Key
private java.lang.String pageToken;
/**
*/
public java.lang.String getPageToken() {
return pageToken;
}
public List setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
@com.google.api.client.util.Key
private java.lang.String startDate;
/**
*/
public java.lang.String getStartDate() {
return startDate;
}
public List setStartDate(java.lang.String startDate) {
this.startDate = startDate;
return this;
}
@com.google.api.client.util.Key
private java.util.List<java.lang.String> status;
/**
*/
public java.util.List<java.lang.String> getStatus() {
return status;
}
public List setStatus(java.util.List<java.lang.String> status) {
this.status = status;
return this;
}
@com.google.api.client.util.Key
private java.lang.String view;
/**
*/
public java.lang.String getView() {
return view;
}
public List setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
/**
* Patches a post.
*
* Create a request for the method "posts.patch".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Patch#execute()} method to invoke the remote operation.
*
* @param blogId
* @param postId
* @param content the {@link com.google.api.services.blogger.model.Post}
* @return the request
*/
public Patch patch(java.lang.String blogId, java.lang.String postId, com.google.api.services.blogger.model.Post content) throws java.io.IOException {
Patch result = new Patch(blogId, postId, content);
initialize(result);
return result;
}
public class Patch extends BloggerRequest<com.google.api.services.blogger.model.Post> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/{postId}";
/**
* Patches a post.
*
* Create a request for the method "posts.patch".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param postId
* @param content the {@link com.google.api.services.blogger.model.Post}
* @since 1.13
*/
protected Patch(java.lang.String blogId, java.lang.String postId, com.google.api.services.blogger.model.Post content) {
super(Blogger.this, "PATCH", REST_PATH, content, com.google.api.services.blogger.model.Post.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.postId = com.google.api.client.util.Preconditions.checkNotNull(postId, "Required parameter postId must be specified.");
}
@Override
public Patch set$Xgafv(java.lang.String $Xgafv) {
return (Patch) super.set$Xgafv($Xgafv);
}
@Override
public Patch setAccessToken(java.lang.String accessToken) {
return (Patch) super.setAccessToken(accessToken);
}
@Override
public Patch setAlt(java.lang.String alt) {
return (Patch) super.setAlt(alt);
}
@Override
public Patch setCallback(java.lang.String callback) {
return (Patch) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Patch) super.setUploadType(uploadType);
}
@Override
public Patch setUploadProtocol(java.lang.String uploadProtocol) {
return (Patch) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Patch setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String postId;
/**
*/
public java.lang.String getPostId() {
return postId;
}
public Patch setPostId(java.lang.String postId) {
this.postId = postId;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchBody;
/**
[ default: true]
[
*/
public java.lang.Boolean getFetchBody() {
return fetchBody;
}
public Patch setFetchBody(java.lang.Boolean fetchBody) {
this.fetchBody = fetchBody;
return this;
}
/**
* Convenience method that returns only {@link Boolean#TRUE} or {@link Boolean#FALSE}.
*
* <p>
* Boolean properties can have four possible values:
* {@code null}, {@link com.google.api.client.util.Data#NULL_BOOLEAN}, {@link Boolean#TRUE}
* or {@link Boolean#FALSE}.
* </p>
*
* <p>
* This method returns {@link Boolean#TRUE} if the default of the property is {@link Boolean#TRUE}
* and it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* {@link Boolean#FALSE} is returned if the default of the property is {@link Boolean#FALSE} and
* it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* </p>
*
* <p>
*
* </p>
*/
public boolean isFetchBody() {
if (fetchBody == null || fetchBody == com.google.api.client.util.Data.NULL_BOOLEAN) {
return true;
}
return fetchBody;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchImages;
/**
*/
public java.lang.Boolean getFetchImages() {
return fetchImages;
}
public Patch setFetchImages(java.lang.Boolean fetchImages) {
this.fetchImages = fetchImages;
return this;
}
@com.google.api.client.util.Key
private java.lang.Long maxComments;
/**
*/
public java.lang.Long getMaxComments() {
return maxComments;
}
public Patch setMaxComments(java.lang.Long maxComments) {
this.maxComments = maxComments;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean publish;
/**
*/
public java.lang.Boolean getPublish() {
return publish;
}
public Patch setPublish(java.lang.Boolean publish) {
this.publish = publish;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean revert;
/**
*/
public java.lang.Boolean getRevert() {
return revert;
}
public Patch setRevert(java.lang.Boolean revert) {
this.revert = revert;
return this;
}
@Override
public Patch set(String parameterName, Object value) {
return (Patch) super.set(parameterName, value);
}
}
/**
* Publishes a post.
*
* Create a request for the method "posts.publish".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Publish#execute()} method to invoke the remote operation.
*
* @param blogId
* @param postId
* @return the request
*/
public Publish publish(java.lang.String blogId, java.lang.String postId) throws java.io.IOException {
Publish result = new Publish(blogId, postId);
initialize(result);
return result;
}
public class Publish extends BloggerRequest<com.google.api.services.blogger.model.Post> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/{postId}/publish";
/**
* Publishes a post.
*
* Create a request for the method "posts.publish".
*
* This request holds the parameters needed by the the blogger server. After setting any optional
* parameters, call the {@link Publish#execute()} method to invoke the remote operation. <p>
* {@link
* Publish#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param blogId
* @param postId
* @since 1.13
*/
protected Publish(java.lang.String blogId, java.lang.String postId) {
super(Blogger.this, "POST", REST_PATH, null, com.google.api.services.blogger.model.Post.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.postId = com.google.api.client.util.Preconditions.checkNotNull(postId, "Required parameter postId must be specified.");
}
@Override
public Publish set$Xgafv(java.lang.String $Xgafv) {
return (Publish) super.set$Xgafv($Xgafv);
}
@Override
public Publish setAccessToken(java.lang.String accessToken) {
return (Publish) super.setAccessToken(accessToken);
}
@Override
public Publish setAlt(java.lang.String alt) {
return (Publish) super.setAlt(alt);
}
@Override
public Publish setCallback(java.lang.String callback) {
return (Publish) super.setCallback(callback);
}
@Override
public Publish setFields(java.lang.String fields) {
return (Publish) super.setFields(fields);
}
@Override
public Publish setKey(java.lang.String key) {
return (Publish) super.setKey(key);
}
@Override
public Publish setOauthToken(java.lang.String oauthToken) {
return (Publish) super.setOauthToken(oauthToken);
}
@Override
public Publish setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Publish) super.setPrettyPrint(prettyPrint);
}
@Override
public Publish setQuotaUser(java.lang.String quotaUser) {
return (Publish) super.setQuotaUser(quotaUser);
}
@Override
public Publish setUploadType(java.lang.String uploadType) {
return (Publish) super.setUploadType(uploadType);
}
@Override
public Publish setUploadProtocol(java.lang.String uploadProtocol) {
return (Publish) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Publish setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String postId;
/**
*/
public java.lang.String getPostId() {
return postId;
}
public Publish setPostId(java.lang.String postId) {
this.postId = postId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String publishDate;
/**
*/
public java.lang.String getPublishDate() {
return publishDate;
}
public Publish setPublishDate(java.lang.String publishDate) {
this.publishDate = publishDate;
return this;
}
@Override
public Publish set(String parameterName, Object value) {
return (Publish) super.set(parameterName, value);
}
}
/**
* Reverts a published or scheduled post to draft state.
*
* Create a request for the method "posts.revert".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Revert#execute()} method to invoke the remote operation.
*
* @param blogId
* @param postId
* @return the request
*/
public Revert revert(java.lang.String blogId, java.lang.String postId) throws java.io.IOException {
Revert result = new Revert(blogId, postId);
initialize(result);
return result;
}
public class Revert extends BloggerRequest<com.google.api.services.blogger.model.Post> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/{postId}/revert";
/**
* Reverts a published or scheduled post to draft state.
*
* Create a request for the method "posts.revert".
*
* This request holds the parameters needed by the the blogger server. After setting any optional
* parameters, call the {@link Revert#execute()} method to invoke the remote operation. <p> {@link
* Revert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param blogId
* @param postId
* @since 1.13
*/
protected Revert(java.lang.String blogId, java.lang.String postId) {
super(Blogger.this, "POST", REST_PATH, null, com.google.api.services.blogger.model.Post.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.postId = com.google.api.client.util.Preconditions.checkNotNull(postId, "Required parameter postId must be specified.");
}
@Override
public Revert set$Xgafv(java.lang.String $Xgafv) {
return (Revert) super.set$Xgafv($Xgafv);
}
@Override
public Revert setAccessToken(java.lang.String accessToken) {
return (Revert) super.setAccessToken(accessToken);
}
@Override
public Revert setAlt(java.lang.String alt) {
return (Revert) super.setAlt(alt);
}
@Override
public Revert setCallback(java.lang.String callback) {
return (Revert) super.setCallback(callback);
}
@Override
public Revert setFields(java.lang.String fields) {
return (Revert) super.setFields(fields);
}
@Override
public Revert setKey(java.lang.String key) {
return (Revert) super.setKey(key);
}
@Override
public Revert setOauthToken(java.lang.String oauthToken) {
return (Revert) super.setOauthToken(oauthToken);
}
@Override
public Revert setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Revert) super.setPrettyPrint(prettyPrint);
}
@Override
public Revert setQuotaUser(java.lang.String quotaUser) {
return (Revert) super.setQuotaUser(quotaUser);
}
@Override
public Revert setUploadType(java.lang.String uploadType) {
return (Revert) super.setUploadType(uploadType);
}
@Override
public Revert setUploadProtocol(java.lang.String uploadProtocol) {
return (Revert) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Revert setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String postId;
/**
*/
public java.lang.String getPostId() {
return postId;
}
public Revert setPostId(java.lang.String postId) {
this.postId = postId;
return this;
}
@Override
public Revert set(String parameterName, Object value) {
return (Revert) super.set(parameterName, value);
}
}
/**
* Searches for posts matching given query terms in the specified blog.
*
* Create a request for the method "posts.search".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Search#execute()} method to invoke the remote operation.
*
* @param blogId
* @param q
* @return the request
*/
public Search search(java.lang.String blogId, java.lang.String q) throws java.io.IOException {
Search result = new Search(blogId, q);
initialize(result);
return result;
}
public class Search extends BloggerRequest<com.google.api.services.blogger.model.PostList> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/search";
/**
* Searches for posts matching given query terms in the specified blog.
*
* Create a request for the method "posts.search".
*
* This request holds the parameters needed by the the blogger server. After setting any optional
* parameters, call the {@link Search#execute()} method to invoke the remote operation. <p> {@link
* Search#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param blogId
* @param q
* @since 1.13
*/
protected Search(java.lang.String blogId, java.lang.String q) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.PostList.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.q = com.google.api.client.util.Preconditions.checkNotNull(q, "Required parameter q 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 Search set$Xgafv(java.lang.String $Xgafv) {
return (Search) super.set$Xgafv($Xgafv);
}
@Override
public Search setAccessToken(java.lang.String accessToken) {
return (Search) super.setAccessToken(accessToken);
}
@Override
public Search setAlt(java.lang.String alt) {
return (Search) super.setAlt(alt);
}
@Override
public Search setCallback(java.lang.String callback) {
return (Search) super.setCallback(callback);
}
@Override
public Search setFields(java.lang.String fields) {
return (Search) super.setFields(fields);
}
@Override
public Search setKey(java.lang.String key) {
return (Search) super.setKey(key);
}
@Override
public Search setOauthToken(java.lang.String oauthToken) {
return (Search) super.setOauthToken(oauthToken);
}
@Override
public Search setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Search) super.setPrettyPrint(prettyPrint);
}
@Override
public Search setQuotaUser(java.lang.String quotaUser) {
return (Search) super.setQuotaUser(quotaUser);
}
@Override
public Search setUploadType(java.lang.String uploadType) {
return (Search) super.setUploadType(uploadType);
}
@Override
public Search setUploadProtocol(java.lang.String uploadProtocol) {
return (Search) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Search setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String q;
/**
*/
public java.lang.String getQ() {
return q;
}
public Search setQ(java.lang.String q) {
this.q = q;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchBodies;
/**
[ default: true]
[
*/
public java.lang.Boolean getFetchBodies() {
return fetchBodies;
}
public Search setFetchBodies(java.lang.Boolean fetchBodies) {
this.fetchBodies = fetchBodies;
return this;
}
/**
* Convenience method that returns only {@link Boolean#TRUE} or {@link Boolean#FALSE}.
*
* <p>
* Boolean properties can have four possible values:
* {@code null}, {@link com.google.api.client.util.Data#NULL_BOOLEAN}, {@link Boolean#TRUE}
* or {@link Boolean#FALSE}.
* </p>
*
* <p>
* This method returns {@link Boolean#TRUE} if the default of the property is {@link Boolean#TRUE}
* and it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* {@link Boolean#FALSE} is returned if the default of the property is {@link Boolean#FALSE} and
* it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* </p>
*
* <p>
*
* </p>
*/
public boolean isFetchBodies() {
if (fetchBodies == null || fetchBodies == com.google.api.client.util.Data.NULL_BOOLEAN) {
return true;
}
return fetchBodies;
}
@com.google.api.client.util.Key
private java.lang.String orderBy;
/**
[ default: PUBLISHED]
[
*/
public java.lang.String getOrderBy() {
return orderBy;
}
public Search setOrderBy(java.lang.String orderBy) {
this.orderBy = orderBy;
return this;
}
@Override
public Search set(String parameterName, Object value) {
return (Search) super.set(parameterName, value);
}
}
/**
* Updates a post by blog id and post id.
*
* Create a request for the method "posts.update".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Update#execute()} method to invoke the remote operation.
*
* @param blogId
* @param postId
* @param content the {@link com.google.api.services.blogger.model.Post}
* @return the request
*/
public Update update(java.lang.String blogId, java.lang.String postId, com.google.api.services.blogger.model.Post content) throws java.io.IOException {
Update result = new Update(blogId, postId, content);
initialize(result);
return result;
}
public class Update extends BloggerRequest<com.google.api.services.blogger.model.Post> {
private static final String REST_PATH = "v3/blogs/{blogId}/posts/{postId}";
/**
* Updates a post by blog id and post id.
*
* Create a request for the method "posts.update".
*
* This request holds the parameters needed by the the blogger 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 blogId
* @param postId
* @param content the {@link com.google.api.services.blogger.model.Post}
* @since 1.13
*/
protected Update(java.lang.String blogId, java.lang.String postId, com.google.api.services.blogger.model.Post content) {
super(Blogger.this, "PUT", REST_PATH, content, com.google.api.services.blogger.model.Post.class);
this.blogId = com.google.api.client.util.Preconditions.checkNotNull(blogId, "Required parameter blogId must be specified.");
this.postId = com.google.api.client.util.Preconditions.checkNotNull(postId, "Required parameter postId must be specified.");
}
@Override
public Update set$Xgafv(java.lang.String $Xgafv) {
return (Update) super.set$Xgafv($Xgafv);
}
@Override
public Update setAccessToken(java.lang.String accessToken) {
return (Update) super.setAccessToken(accessToken);
}
@Override
public Update setAlt(java.lang.String alt) {
return (Update) super.setAlt(alt);
}
@Override
public Update setCallback(java.lang.String callback) {
return (Update) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Update) super.setUploadType(uploadType);
}
@Override
public Update setUploadProtocol(java.lang.String uploadProtocol) {
return (Update) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String blogId;
/**
*/
public java.lang.String getBlogId() {
return blogId;
}
public Update setBlogId(java.lang.String blogId) {
this.blogId = blogId;
return this;
}
@com.google.api.client.util.Key
private java.lang.String postId;
/**
*/
public java.lang.String getPostId() {
return postId;
}
public Update setPostId(java.lang.String postId) {
this.postId = postId;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchBody;
/**
[ default: true]
[
*/
public java.lang.Boolean getFetchBody() {
return fetchBody;
}
public Update setFetchBody(java.lang.Boolean fetchBody) {
this.fetchBody = fetchBody;
return this;
}
/**
* Convenience method that returns only {@link Boolean#TRUE} or {@link Boolean#FALSE}.
*
* <p>
* Boolean properties can have four possible values:
* {@code null}, {@link com.google.api.client.util.Data#NULL_BOOLEAN}, {@link Boolean#TRUE}
* or {@link Boolean#FALSE}.
* </p>
*
* <p>
* This method returns {@link Boolean#TRUE} if the default of the property is {@link Boolean#TRUE}
* and it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* {@link Boolean#FALSE} is returned if the default of the property is {@link Boolean#FALSE} and
* it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* </p>
*
* <p>
*
* </p>
*/
public boolean isFetchBody() {
if (fetchBody == null || fetchBody == com.google.api.client.util.Data.NULL_BOOLEAN) {
return true;
}
return fetchBody;
}
@com.google.api.client.util.Key
private java.lang.Boolean fetchImages;
/**
*/
public java.lang.Boolean getFetchImages() {
return fetchImages;
}
public Update setFetchImages(java.lang.Boolean fetchImages) {
this.fetchImages = fetchImages;
return this;
}
@com.google.api.client.util.Key
private java.lang.Long maxComments;
/**
*/
public java.lang.Long getMaxComments() {
return maxComments;
}
public Update setMaxComments(java.lang.Long maxComments) {
this.maxComments = maxComments;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean publish;
/**
*/
public java.lang.Boolean getPublish() {
return publish;
}
public Update setPublish(java.lang.Boolean publish) {
this.publish = publish;
return this;
}
@com.google.api.client.util.Key
private java.lang.Boolean revert;
/**
*/
public java.lang.Boolean getRevert() {
return revert;
}
public Update setRevert(java.lang.Boolean revert) {
this.revert = revert;
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 Blogger blogger = new Blogger(...);}
* {@code Blogger.Users.List request = blogger.users().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Users users() {
return new Users();
}
/**
* The "users" collection of methods.
*/
public class Users {
/**
* Gets one user by user_id.
*
* Create a request for the method "users.get".
*
* This request holds the parameters needed by the blogger server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param userId
* @return the request
*/
public Get get(java.lang.String userId) throws java.io.IOException {
Get result = new Get(userId);
initialize(result);
return result;
}
public class Get extends BloggerRequest<com.google.api.services.blogger.model.User> {
private static final String REST_PATH = "v3/users/{userId}";
/**
* Gets one user by user_id.
*
* Create a request for the method "users.get".
*
* This request holds the parameters needed by the the blogger 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 userId
* @since 1.13
*/
protected Get(java.lang.String userId) {
super(Blogger.this, "GET", REST_PATH, null, com.google.api.services.blogger.model.User.class);
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 set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@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 setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
@com.google.api.client.util.Key
private java.lang.String userId;
/**
*/
public java.lang.String getUserId() {
return userId;
}
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);
}
}
}
/**
* Builder for {@link Blogger}.
*
* <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 {
private static String chooseEndpoint(com.google.api.client.http.HttpTransport transport) {
// If the GOOGLE_API_USE_MTLS_ENDPOINT environment variable value is "always", use mTLS endpoint.
// If the env variable is "auto", use mTLS endpoint if and only if the transport is mTLS.
// Use the regular endpoint for all other cases.
String useMtlsEndpoint = System.getenv("GOOGLE_API_USE_MTLS_ENDPOINT");
useMtlsEndpoint = useMtlsEndpoint == null ? "auto" : useMtlsEndpoint;
if ("always".equals(useMtlsEndpoint) || ("auto".equals(useMtlsEndpoint) && transport != null && transport.isMtls())) {
return DEFAULT_MTLS_ROOT_URL;
}
return DEFAULT_ROOT_URL;
}
/**
* 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,
Builder.chooseEndpoint(transport),
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link Blogger}. */
@Override
public Blogger build() {
return new Blogger(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 BloggerRequestInitializer}.
*
* @since 1.12
*/
public Builder setBloggerRequestInitializer(
BloggerRequestInitializer bloggerRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(bloggerRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
| apache-2.0 |
suhothayan/siddhi | modules/siddhi-core/src/main/java/io/siddhi/core/aggregation/IncrementalExecutorsInitialiser.java | 9867 | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.siddhi.core.aggregation;
import io.siddhi.core.config.SiddhiAppContext;
import io.siddhi.core.event.ComplexEventChunk;
import io.siddhi.core.event.Event;
import io.siddhi.core.event.stream.MetaStreamEvent;
import io.siddhi.core.event.stream.StreamEvent;
import io.siddhi.core.event.stream.StreamEventFactory;
import io.siddhi.core.query.OnDemandQueryRuntime;
import io.siddhi.core.table.Table;
import io.siddhi.core.util.IncrementalTimeConverterUtil;
import io.siddhi.core.util.parser.OnDemandQueryParser;
import io.siddhi.core.window.Window;
import io.siddhi.query.api.aggregation.TimePeriod;
import io.siddhi.query.api.execution.query.OnDemandQuery;
import io.siddhi.query.api.execution.query.input.store.InputStore;
import io.siddhi.query.api.execution.query.selection.OrderByAttribute;
import io.siddhi.query.api.execution.query.selection.Selector;
import io.siddhi.query.api.expression.Expression;
import io.siddhi.query.api.expression.condition.Compare;
import java.util.List;
import java.util.Map;
import static io.siddhi.core.util.SiddhiConstants.AGG_SHARD_ID_COL;
import static io.siddhi.core.util.SiddhiConstants.AGG_START_TIMESTAMP_COL;
/**
* This class is used to recreate in-memory data from the tables (Such as RDBMS) in incremental aggregation.
* This ensures that the aggregation calculations are done correctly in case of server restart
*/
public class IncrementalExecutorsInitialiser {
private final List<TimePeriod.Duration> incrementalDurations;
private final Map<TimePeriod.Duration, Table> aggregationTables;
private final Map<TimePeriod.Duration, IncrementalExecutor> incrementalExecutorMap;
private final boolean isDistributed;
private final String shardId;
private final StreamEventFactory streamEventFactory;
private final SiddhiAppContext siddhiAppContext;
private final Map<String, Table> tableMap;
private final Map<String, Window> windowMap;
private final Map<String, AggregationRuntime> aggregationMap;
private boolean isInitialised;
public IncrementalExecutorsInitialiser(List<TimePeriod.Duration> incrementalDurations,
Map<TimePeriod.Duration, Table> aggregationTables,
Map<TimePeriod.Duration, IncrementalExecutor> incrementalExecutorMap,
boolean isDistributed, String shardId, SiddhiAppContext siddhiAppContext,
MetaStreamEvent metaStreamEvent, Map<String, Table> tableMap,
Map<String, Window> windowMap,
Map<String, AggregationRuntime> aggregationMap) {
this.incrementalDurations = incrementalDurations;
this.aggregationTables = aggregationTables;
this.incrementalExecutorMap = incrementalExecutorMap;
this.isDistributed = isDistributed;
this.shardId = shardId;
this.streamEventFactory = new StreamEventFactory(metaStreamEvent);
this.siddhiAppContext = siddhiAppContext;
this.tableMap = tableMap;
this.windowMap = windowMap;
this.aggregationMap = aggregationMap;
this.isInitialised = false;
}
public synchronized void initialiseExecutors() {
if (this.isInitialised) {
// Only cleared when executors change from reading to processing state in one node deployment
return;
}
Event[] events;
Long endOFLatestEventTimestamp = null;
// Get max(AGG_TIMESTAMP) from table corresponding to max duration
Table tableForMaxDuration = aggregationTables.get(incrementalDurations.get(incrementalDurations.size() - 1));
OnDemandQuery onDemandQuery = getOnDemandQuery(tableForMaxDuration, true, endOFLatestEventTimestamp);
onDemandQuery.setType(OnDemandQuery.OnDemandQueryType.FIND);
OnDemandQueryRuntime onDemandQueryRuntime = OnDemandQueryParser.parse(onDemandQuery, null,
siddhiAppContext, tableMap, windowMap, aggregationMap);
// Get latest event timestamp in tableForMaxDuration and get the end time of the aggregation record
events = onDemandQueryRuntime.execute();
if (events != null) {
Long lastData = (Long) events[events.length - 1].getData(0);
endOFLatestEventTimestamp = IncrementalTimeConverterUtil
.getNextEmitTime(lastData, incrementalDurations.get(incrementalDurations.size() - 1), null);
}
for (int i = incrementalDurations.size() - 1; i > 0; i--) {
TimePeriod.Duration recreateForDuration = incrementalDurations.get(i);
IncrementalExecutor incrementalExecutor = incrementalExecutorMap.get(recreateForDuration);
// Get the table previous to the duration for which we need to recreate (e.g. if we want to recreate
// for minute duration, take the second table [provided that aggregation is done for seconds])
// This lookup is filtered by endOFLatestEventTimestamp
Table recreateFromTable = aggregationTables.get(incrementalDurations.get(i - 1));
onDemandQuery = getOnDemandQuery(recreateFromTable, false, endOFLatestEventTimestamp);
onDemandQuery.setType(OnDemandQuery.OnDemandQueryType.FIND);
onDemandQueryRuntime = OnDemandQueryParser.parse(onDemandQuery, null, siddhiAppContext,
tableMap, windowMap,
aggregationMap);
events = onDemandQueryRuntime.execute();
if (events != null) {
long referenceToNextLatestEvent = (Long) events[events.length - 1].getData(0);
endOFLatestEventTimestamp = IncrementalTimeConverterUtil
.getNextEmitTime(referenceToNextLatestEvent, incrementalDurations.get(i - 1), null);
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<>();
for (Event event : events) {
StreamEvent streamEvent = streamEventFactory.newInstance();
streamEvent.setOutputData(event.getData());
complexEventChunk.add(streamEvent);
}
incrementalExecutor.execute(complexEventChunk);
if (i == 1) {
TimePeriod.Duration rootDuration = incrementalDurations.get(0);
IncrementalExecutor rootIncrementalExecutor = incrementalExecutorMap.get(rootDuration);
long emitTimeOfLatestEventInTable = IncrementalTimeConverterUtil.getNextEmitTime(
referenceToNextLatestEvent, rootDuration, null);
rootIncrementalExecutor.setEmitTime(emitTimeOfLatestEventInTable);
}
}
}
this.isInitialised = true;
}
private OnDemandQuery getOnDemandQuery(Table table, boolean isLargestGranularity, Long endOFLatestEventTimestamp) {
Selector selector = Selector.selector();
if (isLargestGranularity) {
selector = selector
.orderBy(
Expression.variable(AGG_START_TIMESTAMP_COL), OrderByAttribute.Order.DESC)
.limit(Expression.value(1));
} else {
selector = selector.orderBy(Expression.variable(AGG_START_TIMESTAMP_COL));
}
InputStore inputStore;
if (!this.isDistributed) {
if (endOFLatestEventTimestamp == null) {
inputStore = InputStore.store(table.getTableDefinition().getId());
} else {
inputStore = InputStore.store(table.getTableDefinition().getId())
.on(Expression.compare(
Expression.variable(AGG_START_TIMESTAMP_COL),
Compare.Operator.GREATER_THAN_EQUAL,
Expression.value(endOFLatestEventTimestamp)
));
}
} else {
if (endOFLatestEventTimestamp == null) {
inputStore = InputStore.store(table.getTableDefinition().getId()).on(
Expression.compare(Expression.variable(AGG_SHARD_ID_COL), Compare.Operator.EQUAL,
Expression.value(shardId)));
} else {
inputStore = InputStore.store(table.getTableDefinition().getId()).on(
Expression.and(
Expression.compare(
Expression.variable(AGG_SHARD_ID_COL),
Compare.Operator.EQUAL,
Expression.value(shardId)),
Expression.compare(
Expression.variable(AGG_START_TIMESTAMP_COL),
Compare.Operator.GREATER_THAN_EQUAL,
Expression.value(endOFLatestEventTimestamp))));
}
}
return OnDemandQuery.query().from(inputStore).select(selector);
}
}
| apache-2.0 |
adamrduffy/trinidad-1.0.x | trinidad-api/src/test/java/org/apache/myfaces/trinidad/bean/SubTypeBean.java | 1311 | /*
* 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.myfaces.trinidad.bean;
import org.apache.myfaces.trinidad.bean.PropertyKey;
public class SubTypeBean extends TestBean
{
static public final Type TYPE = new Type(TestBean.TYPE);
static public final PropertyKey SUB_KEY =
TYPE.registerKey("sub");
@Override
public Type getType()
{
return TYPE;
}
public String getSub()
{
return (String) getProperty(SUB_KEY);
}
public void setSub(String sub)
{
setProperty(SUB_KEY, sub);
}
}
| apache-2.0 |
magical-l/magicall-db | src/main/java/me/magicall/db/FieldFilter.java | 223 | package me.magicall.db;
import me.magicall.db.meta.DbColumn;
import me.magicall.db.meta.TableMeta;
@FunctionalInterface
public interface FieldFilter {
boolean accept(final TableMeta tableMeta, final DbColumn column);
}
| apache-2.0 |
vinitraj10/Java | Java/Constructors/Tuna.java | 214 | public class Tuna{
private int sum;
private final int NUMBER;
public Tuna(int x){
NUMBER =x;
}
public void add(){
sum+=NUMBER;
}
public String toString(){
return String.format("sum = %d \n",sum);
}
} | apache-2.0 |
DmitryMalkovich/popular-movies-app | app/src/main/java/com/dmitrymalkovich/android/popularmoviesapp/data/MoviesProvider.java | 5338 | /*
* Copyright 2016. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.popularmoviesapp.data;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class MoviesProvider extends ContentProvider {
private static final UriMatcher sUriMatcher = buildUriMatcher();
static final int MOVIES = 300;
private MoviesDBHelper mOpenHelper;
private static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = MovieContract.CONTENT_AUTHORITY;
matcher.addURI(authority, MovieContract.PATH_MOVIE, MOVIES);
return matcher;
}
@Override
public boolean onCreate() {
mOpenHelper = new MoviesDBHelper(getContext());
return true;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Cursor cursor;
switch (sUriMatcher.match(uri)) {
case MOVIES: {
cursor = mOpenHelper.getReadableDatabase().query(
MovieContract.MovieEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
if (getContext() != null) {
cursor.setNotificationUri(getContext().getContentResolver(), uri);
}
return cursor;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match) {
case MOVIES:
return MovieContract.MovieEntry.CONTENT_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
Uri returnUri;
switch (match) {
case MOVIES: {
long id = db.insert(MovieContract.MovieEntry.TABLE_NAME, null, values);
if (id > 0) {
returnUri = MovieContract.MovieEntry.buildMovieUri(id);
} else {
throw new android.database.SQLException("Failed to insert row into " + uri);
}
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
if (getContext() != null) {
getContext().getContentResolver().notifyChange(uri, null);
}
return returnUri;
}
@Override
public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int rowsDeleted;
if (null == selection) {
selection = "1";
}
switch (match) {
case MOVIES:
rowsDeleted = db.delete(
MovieContract.MovieEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
if (rowsDeleted != 0 && getContext() != null) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsDeleted;
}
@Override
public int update(@NonNull Uri uri, ContentValues values, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int rowsUpdated;
switch (match) {
case MOVIES:
rowsUpdated = db.update(MovieContract.MovieEntry.TABLE_NAME, values, selection,
selectionArgs);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
if (rowsUpdated != 0 && getContext() != null) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsUpdated;
}
}
| apache-2.0 |
Gaonaifeng/eLong-OpenAPI-H5-demo | nb_demo_h5/src/main/java/com/elong/nb/model/elong/CreateOrderRoom.java | 1894 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.10.09 at 10:10:23 AM CST
//
package com.elong.nb.model.elong;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import java.util.List;
import com.alibaba.fastjson.annotation.JSONField;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CreateOrderRoom complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="CreateOrderRoom">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Customers" type="{}ArrayOfCustomer" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CreateOrderRoom", propOrder = {
"customers"
})
public class CreateOrderRoom {
@JSONField(name = "Customers")
protected List<Customer> customers;
/**
* Gets the value of the customers property.
*
* @return
* possible object is
* {@link List<Customer> }
*
*/
public List<Customer> getCustomers() {
return customers;
}
/**
* Sets the value of the customers property.
*
* @param value
* allowed object is
* {@link List<Customer> }
*
*/
public void setCustomers(List<Customer> value) {
this.customers = value;
}
}
| apache-2.0 |
KiddoThe2B/nomothesia-api | src/main/java/com/di/nomothesia/model/Case.java | 1799 |
package com.di.nomothesia.model;
import java.util.ArrayList;
import java.util.List;
public class Case implements Fragment {
private String uri;
private int id;
private List<Passage> passages;
private List<Case> caseList;
private int status;
private String type;
private Modification modification;
public Case() {
passages = new ArrayList<>();
//pas.add(new Passage());
caseList = new ArrayList<>();
//casel.add(new Case());
}
//Setters-Getters for Case
@Override
public void setType(String t) {
this.type = t;
}
@Override
public String getType() {
return type;
}
@Override
public int getStatus() {
return status;
}
@Override
public void setStatus(int s) {
this.status = s;
}
@Override
public String getURI() {
return uri;
}
public void setURI(String uri) {
this.uri = uri;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<Passage> getPassages() {
return passages;
}
public void setPassages(List<Passage> passages) {
this.passages = passages;
}
public List<Case> getCaseList() {
return caseList;
}
public void setCaseList(List<Case> caseList) {
this.caseList = caseList;
}
public Modification getModification() {
return modification;
}
public void setModification(Modification modification) {
this.modification = modification;
}
}
| apache-2.0 |
shzisg/wechat-java-sdk | wechat-java-miniapp/src/main/java/cn/binarywang/wx/miniapp/api/WxMaQrcodeService.java | 875 | package cn.binarywang.wx.miniapp.api;
import me.chanjar.weixin.common.exception.WxErrorException;
import java.io.File;
/**
* <pre>
* 二维码相关操作接口
* 文档地址:https://mp.weixin.qq.com/debug/wxadoc/dev/api/qrcode.html
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
public interface WxMaQrcodeService {
/**
* <pre>
* 获取小程序页面二维码
* 适用于需要的码数量较少的业务场景
* 通过该接口,仅能生成已发布的小程序的二维码。
* 可以在开发者工具预览时生成开发版的带参二维码。
* 带参二维码只有 100000 个,请谨慎调用。
* </pre>
*
* @param path 不能为空,最大长度 128 字节
* @param width 默认430 二维码的宽度
*/
File createQrcode(String path, int width) throws WxErrorException;
}
| apache-2.0 |
FJplant/AntIDE | src/com/antsoft/ant/designer/classdesigner/CDAttrInfo.java | 6885 | /*
* Ant ( JDK wrapper Java IDE )
* Version 1.0
* Copyright (c) 1998-1999 Antsoft Co. All rights reserved.
* This program and source file is protected by Korea and international
* Copyright laws.
*
* $Header: /usr/cvsroot/AntIDE/source/com/antsoft/ant/designer/classdesigner/CDAttrInfo.java,v 1.3 1999/07/22 03:37:36 multipia Exp $
* $Revision: 1.3 $
* Part : Class Designer Attribute Information.
* Author: Kim, Sung-hoon(kahn@antj.com)
* Dated at 1999.1.20.21.22.
*/
package com.antsoft.ant.designer.classdesigner;
/**
@author Kim, Sung-hoon.
*/
public class CDAttrInfo
{
public static final String PUBLIC="public";
public static final String PROTECTED="protected";
public static final String PRIVATE="private";
public static final String NOMODIFIER="";
private String accessType=NOMODIFIER; // It's value is PUBLIC,PROTECTED,PRIVATE,NOMODIFIER
private String type=null;
private String attrName=null;
private String initValue=null;
private boolean getterAttr;
private boolean setterAttr;
private boolean staticAttr;
private boolean finalAttr;
private boolean transientAttr;
private boolean volatileAttr;
private String description=null;
//private JavaDocInfo javaDocInfo=null;
//private StringBuffer tabString=new StringBuffer();
/**
setting the access type of the attribute.
@param accessType the access type(public, protected, private)
*/
public void setAccessType(String accessType) {
this.accessType=accessType;
}
/**
setting the attribute type(int,float..., classname or interfacename...).
@param type the string of the type.
*/
public void setType(String type) {
this.type=type;
}
/**
setting the attribute name as the string.
@param name the string of the name.
*/
public void setAttrName(String name) {
attrName=name;
}
/**
setting the initial value as the string.
@param value the string of initial value
*/
public void setInitValue(String value) {
initValue=value;
}
/**
switching the Getter method on/off
@param flag ON/OFF flag
*/
public void setGetter(boolean flag) {
getterAttr=flag;
}
/**
switching the Setter method on/off
@param flag ON/OFF flag
*/
public void setSetter(boolean flag) {
setterAttr=flag;
}
/**
switching the attribute is static or not.
@param flag static ON/OFF flag
*/
public void setStatic(boolean flag) {
staticAttr=flag;
}
/**
switching the attribute is final or not.
@param flag final ON/OFF flag
*/
public void setFinal(boolean flag) {
finalAttr=flag;
}
/**
switching the attribute is transient or not.
@param flag transient ON/OFF flag
*/
public void setTransient(boolean flag) {
transientAttr=flag;
}
/**
switching the attribute is volatile or not.
@param flag volatile ON/OFF flag
*/
public void setVolatile(boolean flag) {
volatileAttr=flag;
}
/**
getting the access type of the attribute.
@return access type as the String value.
*/
public String getAccessType() {
return accessType;
}
/**
getting the type of the attribute.
@return type as the string value.
*/
public String getType() {
return type;
}
/**
getting the name of the attribute.
@return attribute name as the string value.
*/
public String getAttrName() {
return attrName;
}
/**
getting the initial value of the attribute.
@return initial value as the string value.
*/
public String getInitValue() {
if (initValue==null) return null;
else return initValue;
}
/**
getting the getter flag.
@return getter flag as the boolean value.
*/
public boolean isGetter() {
return getterAttr;
}
/**
getting the setter flag.
@return setter flag as the boolean value.
*/
public boolean isSetter() {
return setterAttr;
}
/**
getting the static flag.
@return static flag as the boolean value.
*/
public boolean isStatic() {
return staticAttr;
}
/**
getting the final flag.
@return final flag as the boolean value.
*/
public boolean isFinal() {
return finalAttr;
}
/**
getting the transient flag.
@return transient flag as the boolean value.
*/
public boolean isTransient() {
return transientAttr;
}
/**
getting the volatile flag.
@return volatile flag as the boolean value.
*/
public boolean isVolatile() {
return volatileAttr;
}
private String comment=null;
/**
setting the java documentain information of the attribute.
@param java documentain information as the String value.
*/
public void setJavaDoc(String doc) {
comment=doc;
}
/**
getting the java documentain information of the attribute.
@return java documentain information as the String value.
*/
public String getJavaDoc() {
return comment;
}
/**
Returns the string representation of the object. In general, It
returns a string that "textually represents" this object.
@return a string representation of the object.
*/
public String toString() {
StringBuffer theCode=new StringBuffer("");
String str=null;
String blank=" ";
String endLine="\n";
String tab="\t";
String startComment="/** ";
if (comment!=null) {
//theCode.append(tab+"/**"+endLine+tab);
//theCode.append(tab+" * "+comment);
//theCode.append(endLine+tab+"*/"+endLine);
if (getAccessType().equals("private")) theCode.append(tab+"/* "+comment+" */"+endLine);
else theCode.append(tab+startComment+comment+" */"+endLine);
}
theCode.append(tab);
str=getAccessType();
if (str.length()>3) theCode.append(str+blank);
if (isStatic()) theCode.append("static ");
if (isFinal()) theCode.append("final ");
//if (isSynchronous()) theCode.append("synchronized ");
if (isTransient()) theCode.append("transient ");
if (isVolatile()) theCode.append("volatile ");
theCode.append(getType()+blank);
theCode.append(getAttrName()+blank);
str=getInitValue();
if (str!=null&&!str.equals("")) theCode.append("= "+str);
theCode.append(";"+endLine+endLine);
/*
if (isGetter()) {
theCode.append("public "+getType()+" get"+getAttrName()+"() {"+endLine);
theCode.append(TabString+"return "+getAttrName()+";"+endLine);
theCode.append("}"+endLine);
}
if (isSetter()) {
theCode.append("public void set"+getAttrName()+"("+getType()+blank+"formalParam) {"+endLine);
theCode.append(TabString+getAttrName()+"=formalParam;"+endLine);
theCode.append("}"+endLine);
}
*/
//System.out.println("the attr info==== "+theCode.toString());
return theCode.toString();
}
}
| apache-2.0 |
nate-rcl/irplus | file_db/src/edu/ur/file/db/FileDatabase.java | 5165 | /**
Copyright 2008 University of Rochester
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 edu.ur.file.db;
import edu.ur.file.IllegalFileSystemNameException;
import edu.ur.persistent.LongPersistentId;
import edu.ur.persistent.PersistentVersioned;
import java.io.InputStream;
import java.io.Serializable;
import java.io.File;
import java.util.Set;
/**
* An interface for a file database which holds files. This interface
* has no knowledge of how the file database stores files. This interface
* is only for basic file storage.
*
* It is expected that if a file database has versioning capabilities, this
* can still be handled with this interface using the uniqueFileName and FileInfo
* object.
*
* It is expected any implementation of this interface will produce unique ids for
* all files added to the system and this id will be unique across all added files.
*
* @author Nathan Sarr
*
*/
public interface FileDatabase extends LongPersistentId, PersistentVersioned,
Serializable {
/**
* Add a file to this file database. The file should have a size
* greater than zero. If not see <code>addFile(String uniqueName)</code>
*
* @param f file to add to this file database
* @param uniqueFileName - unique file name identifier. This name
* should be unique across all files and folders in the database.
*
* @return the file information
* @throws IllegalFileSystemNameException
*/
public FileInfo addFile(File f, String uniqueFileName) throws IllegalFileSystemNameException;
/**
* Create a new empty file with the specified name.
*
* @param uniqueName - name of the file which is unique.
* @return the file information.
* @throws IllegalFileSystemNameException
*/
public FileInfo addFile(String uniqueName) throws IllegalFileSystemNameException;
/**
* Remove the file from the file database.
*
* @param unique file name to remove.
* @return true if the file is removed from the system.
*/
public boolean removeFile(String uniqueFileName);
/**
* Remove a file using it's unique id.
*
* @param id - id of the file
* @return true if the fileinfo has been removed from the system.
*/
public boolean removeFile(Long id);
/**
* Get the file information for the specified file.
*
* @param id - Unique id of the file.
* @return The file information or null if the file is not found.
*/
public FileInfo getFile(Long id);
/**
* Get the file information for the specified file.
*
* @param uniqueFileName - Unique file name
* @return The file information or null if the file is not found.
*/
public FileInfo getFile(String uniqueFileName);
/**
* Get the file input stream.
*
* @param id - unique id for the file
* @return an input stream for the file or null if the file does not exist.
*/
public InputStream getInputStream(Long id);
/**
* Get the input stream for the file.
*
* @param uniqueFileName - name of the file
* @return an input stream for the file or null if the file does not exist.
*/
public InputStream getInputStream(String uniqueFileName);
/**
* Name displayed to the user for this file database.
*
* @return display name
*/
public String getDisplayName();
/**
* Get the description for this file database.
*
* @return the description.
*/
public String getDescription();
/**
* Set the description of the file database.
*
*/
public void setDescription(String description);
/**
* Get the name of this file database
*
* @return name of the file database
*/
public String getName();
/**
* Create a folder in the file database.
*
* @param uniqueName
* @return - the created folder.
* @throws LocationAlreadyExistsException - if location already exists
*/
public FolderInfo createFolder(String uniqueName) throws LocationAlreadyExistsException;
/**
* Get the folder with the specified name
*
* @param uniqueName - unique name of the folder
*
* @return - the found folder information or null if not found.
*/
public FolderInfo getFolder(String uniqueName);
/**
* Set the default folder to store all the files.
*
* @param folderName
* @return true if the file store is changed
*/
public boolean setCurrentFileStore(String folderName);
/**
* Get the set of root folders for the file database FolderInfo
* objects.
*
* @return
*/
@SuppressWarnings("unchecked")
public Set getRootFolders();
}
| apache-2.0 |
echalkpad/t4f-data | structure/core/src/test/java/io/datalayer/data/list/ArrayListTest.java | 2199 | /****************************************************************
* Licensed to the AOS Community (AOS) under one or more *
* contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The AOS 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.datalayer.data.list;
import io.datalayer.data.list.ArrayList;
import io.datalayer.data.list.List;
/**
* Concrete tests for {@link ArrayList}.
*
*/
public class ArrayListTest extends AbstractListTestCase {
protected List createList() {
return new ArrayList();
}
public void testResizeBeyondInitialCapacity() {
List list = new ArrayList(1);
list.add(VALUE_A);
list.add(VALUE_A);
list.add(VALUE_A);
assertEquals(3, list.size());
assertSame(VALUE_A, list.get(0));
assertSame(VALUE_A, list.get(1));
assertSame(VALUE_A, list.get(2));
}
public void testDeleteFromFirstElementOfListAtFullCapacity() {
List list = new ArrayList(3);
list.add(VALUE_A);
list.add(VALUE_B);
list.add(VALUE_C);
list.delete(0);
}
public void testDeleteFromLastElementInArray() {
List list = new ArrayList(1);
list.add(VALUE_A);
list.delete(0);
}
}
| apache-2.0 |
flyhero/flyapi | src/main/java/cn/iflyapi/blog/util/IPUtils.java | 1165 | package cn.iflyapi.blog.util;
import javax.servlet.http.HttpServletRequest;
/**
*
* author flyhero
* date 2018/12/15 5:42 PM
*/
public class IPUtils {
public static String getIP(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unkonwn".equalsIgnoreCase(ip)) {
ip = request.getHeader("PRoxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unkonwn".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unkonwn".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip == null || ip.length() == 0 || "unkonwn".equalsIgnoreCase(ip)) {
ip = request.getHeader("http_client_ip");
}
if (ip == null || ip.length() == 0 || "unkonwn".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDEC_FOR");
}
if (ip != null && ip.indexOf(",") != -1) {
ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
}
return ip;
}
}
| apache-2.0 |
myjoybar/JavaExercise | src/designpattern/singleton/Singleton6.java | 105 | package designpattern.singleton;
/**
* Created by joybar on 29/05/17.
*/
public class Singleton6 {
}
| apache-2.0 |
spring-projects/spring-framework | spring-aop/src/main/java/org/springframework/aop/config/AspectEntry.java | 1410 | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.config;
import org.springframework.beans.factory.parsing.ParseState;
import org.springframework.util.StringUtils;
/**
* {@link ParseState} entry representing an aspect.
*
* @author Mark Fisher
* @author Juergen Hoeller
* @since 2.0
*/
public class AspectEntry implements ParseState.Entry {
private final String id;
private final String ref;
/**
* Create a new {@code AspectEntry} instance.
* @param id the id of the aspect element
* @param ref the bean name referenced by this aspect element
*/
public AspectEntry(String id, String ref) {
this.id = id;
this.ref = ref;
}
@Override
public String toString() {
return "Aspect: " + (StringUtils.hasLength(this.id) ? "id='" + this.id + "'" : "ref='" + this.ref + "'");
}
}
| apache-2.0 |
davido/buck | src-gen/com/facebook/buck/artifact_cache/thrift/BuckCacheRequest.java | 25780 | /**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.facebook.buck.artifact_cache.thrift;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2017-03-03")
public class BuckCacheRequest implements org.apache.thrift.TBase<BuckCacheRequest, BuckCacheRequest._Fields>, java.io.Serializable, Cloneable, Comparable<BuckCacheRequest> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("BuckCacheRequest");
private static final org.apache.thrift.protocol.TField TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("type", org.apache.thrift.protocol.TType.I32, (short)1);
private static final org.apache.thrift.protocol.TField PAYLOADS_FIELD_DESC = new org.apache.thrift.protocol.TField("payloads", org.apache.thrift.protocol.TType.LIST, (short)100);
private static final org.apache.thrift.protocol.TField FETCH_REQUEST_FIELD_DESC = new org.apache.thrift.protocol.TField("fetchRequest", org.apache.thrift.protocol.TType.STRUCT, (short)101);
private static final org.apache.thrift.protocol.TField STORE_REQUEST_FIELD_DESC = new org.apache.thrift.protocol.TField("storeRequest", org.apache.thrift.protocol.TType.STRUCT, (short)102);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new BuckCacheRequestStandardSchemeFactory());
schemes.put(TupleScheme.class, new BuckCacheRequestTupleSchemeFactory());
}
/**
*
* @see BuckCacheRequestType
*/
public BuckCacheRequestType type; // optional
public List<PayloadInfo> payloads; // optional
public BuckCacheFetchRequest fetchRequest; // optional
public BuckCacheStoreRequest storeRequest; // optional
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
/**
*
* @see BuckCacheRequestType
*/
TYPE((short)1, "type"),
PAYLOADS((short)100, "payloads"),
FETCH_REQUEST((short)101, "fetchRequest"),
STORE_REQUEST((short)102, "storeRequest");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // TYPE
return TYPE;
case 100: // PAYLOADS
return PAYLOADS;
case 101: // FETCH_REQUEST
return FETCH_REQUEST;
case 102: // STORE_REQUEST
return STORE_REQUEST;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final _Fields optionals[] = {_Fields.TYPE,_Fields.PAYLOADS,_Fields.FETCH_REQUEST,_Fields.STORE_REQUEST};
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.TYPE, new org.apache.thrift.meta_data.FieldMetaData("type", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, BuckCacheRequestType.class)));
tmpMap.put(_Fields.PAYLOADS, new org.apache.thrift.meta_data.FieldMetaData("payloads", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, PayloadInfo.class))));
tmpMap.put(_Fields.FETCH_REQUEST, new org.apache.thrift.meta_data.FieldMetaData("fetchRequest", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, BuckCacheFetchRequest.class)));
tmpMap.put(_Fields.STORE_REQUEST, new org.apache.thrift.meta_data.FieldMetaData("storeRequest", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, BuckCacheStoreRequest.class)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(BuckCacheRequest.class, metaDataMap);
}
public BuckCacheRequest() {
this.type = com.facebook.buck.artifact_cache.thrift.BuckCacheRequestType.UNKNOWN;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public BuckCacheRequest(BuckCacheRequest other) {
if (other.isSetType()) {
this.type = other.type;
}
if (other.isSetPayloads()) {
List<PayloadInfo> __this__payloads = new ArrayList<PayloadInfo>(other.payloads.size());
for (PayloadInfo other_element : other.payloads) {
__this__payloads.add(new PayloadInfo(other_element));
}
this.payloads = __this__payloads;
}
if (other.isSetFetchRequest()) {
this.fetchRequest = new BuckCacheFetchRequest(other.fetchRequest);
}
if (other.isSetStoreRequest()) {
this.storeRequest = new BuckCacheStoreRequest(other.storeRequest);
}
}
public BuckCacheRequest deepCopy() {
return new BuckCacheRequest(this);
}
@Override
public void clear() {
this.type = com.facebook.buck.artifact_cache.thrift.BuckCacheRequestType.UNKNOWN;
this.payloads = null;
this.fetchRequest = null;
this.storeRequest = null;
}
/**
*
* @see BuckCacheRequestType
*/
public BuckCacheRequestType getType() {
return this.type;
}
/**
*
* @see BuckCacheRequestType
*/
public BuckCacheRequest setType(BuckCacheRequestType type) {
this.type = type;
return this;
}
public void unsetType() {
this.type = null;
}
/** Returns true if field type is set (has been assigned a value) and false otherwise */
public boolean isSetType() {
return this.type != null;
}
public void setTypeIsSet(boolean value) {
if (!value) {
this.type = null;
}
}
public int getPayloadsSize() {
return (this.payloads == null) ? 0 : this.payloads.size();
}
public java.util.Iterator<PayloadInfo> getPayloadsIterator() {
return (this.payloads == null) ? null : this.payloads.iterator();
}
public void addToPayloads(PayloadInfo elem) {
if (this.payloads == null) {
this.payloads = new ArrayList<PayloadInfo>();
}
this.payloads.add(elem);
}
public List<PayloadInfo> getPayloads() {
return this.payloads;
}
public BuckCacheRequest setPayloads(List<PayloadInfo> payloads) {
this.payloads = payloads;
return this;
}
public void unsetPayloads() {
this.payloads = null;
}
/** Returns true if field payloads is set (has been assigned a value) and false otherwise */
public boolean isSetPayloads() {
return this.payloads != null;
}
public void setPayloadsIsSet(boolean value) {
if (!value) {
this.payloads = null;
}
}
public BuckCacheFetchRequest getFetchRequest() {
return this.fetchRequest;
}
public BuckCacheRequest setFetchRequest(BuckCacheFetchRequest fetchRequest) {
this.fetchRequest = fetchRequest;
return this;
}
public void unsetFetchRequest() {
this.fetchRequest = null;
}
/** Returns true if field fetchRequest is set (has been assigned a value) and false otherwise */
public boolean isSetFetchRequest() {
return this.fetchRequest != null;
}
public void setFetchRequestIsSet(boolean value) {
if (!value) {
this.fetchRequest = null;
}
}
public BuckCacheStoreRequest getStoreRequest() {
return this.storeRequest;
}
public BuckCacheRequest setStoreRequest(BuckCacheStoreRequest storeRequest) {
this.storeRequest = storeRequest;
return this;
}
public void unsetStoreRequest() {
this.storeRequest = null;
}
/** Returns true if field storeRequest is set (has been assigned a value) and false otherwise */
public boolean isSetStoreRequest() {
return this.storeRequest != null;
}
public void setStoreRequestIsSet(boolean value) {
if (!value) {
this.storeRequest = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case TYPE:
if (value == null) {
unsetType();
} else {
setType((BuckCacheRequestType)value);
}
break;
case PAYLOADS:
if (value == null) {
unsetPayloads();
} else {
setPayloads((List<PayloadInfo>)value);
}
break;
case FETCH_REQUEST:
if (value == null) {
unsetFetchRequest();
} else {
setFetchRequest((BuckCacheFetchRequest)value);
}
break;
case STORE_REQUEST:
if (value == null) {
unsetStoreRequest();
} else {
setStoreRequest((BuckCacheStoreRequest)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case TYPE:
return getType();
case PAYLOADS:
return getPayloads();
case FETCH_REQUEST:
return getFetchRequest();
case STORE_REQUEST:
return getStoreRequest();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case TYPE:
return isSetType();
case PAYLOADS:
return isSetPayloads();
case FETCH_REQUEST:
return isSetFetchRequest();
case STORE_REQUEST:
return isSetStoreRequest();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof BuckCacheRequest)
return this.equals((BuckCacheRequest)that);
return false;
}
public boolean equals(BuckCacheRequest that) {
if (that == null)
return false;
boolean this_present_type = true && this.isSetType();
boolean that_present_type = true && that.isSetType();
if (this_present_type || that_present_type) {
if (!(this_present_type && that_present_type))
return false;
if (!this.type.equals(that.type))
return false;
}
boolean this_present_payloads = true && this.isSetPayloads();
boolean that_present_payloads = true && that.isSetPayloads();
if (this_present_payloads || that_present_payloads) {
if (!(this_present_payloads && that_present_payloads))
return false;
if (!this.payloads.equals(that.payloads))
return false;
}
boolean this_present_fetchRequest = true && this.isSetFetchRequest();
boolean that_present_fetchRequest = true && that.isSetFetchRequest();
if (this_present_fetchRequest || that_present_fetchRequest) {
if (!(this_present_fetchRequest && that_present_fetchRequest))
return false;
if (!this.fetchRequest.equals(that.fetchRequest))
return false;
}
boolean this_present_storeRequest = true && this.isSetStoreRequest();
boolean that_present_storeRequest = true && that.isSetStoreRequest();
if (this_present_storeRequest || that_present_storeRequest) {
if (!(this_present_storeRequest && that_present_storeRequest))
return false;
if (!this.storeRequest.equals(that.storeRequest))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_type = true && (isSetType());
list.add(present_type);
if (present_type)
list.add(type.getValue());
boolean present_payloads = true && (isSetPayloads());
list.add(present_payloads);
if (present_payloads)
list.add(payloads);
boolean present_fetchRequest = true && (isSetFetchRequest());
list.add(present_fetchRequest);
if (present_fetchRequest)
list.add(fetchRequest);
boolean present_storeRequest = true && (isSetStoreRequest());
list.add(present_storeRequest);
if (present_storeRequest)
list.add(storeRequest);
return list.hashCode();
}
@Override
public int compareTo(BuckCacheRequest other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetType()).compareTo(other.isSetType());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetType()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.type, other.type);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetPayloads()).compareTo(other.isSetPayloads());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetPayloads()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.payloads, other.payloads);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetFetchRequest()).compareTo(other.isSetFetchRequest());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetFetchRequest()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.fetchRequest, other.fetchRequest);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetStoreRequest()).compareTo(other.isSetStoreRequest());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetStoreRequest()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.storeRequest, other.storeRequest);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("BuckCacheRequest(");
boolean first = true;
if (isSetType()) {
sb.append("type:");
if (this.type == null) {
sb.append("null");
} else {
sb.append(this.type);
}
first = false;
}
if (isSetPayloads()) {
if (!first) sb.append(", ");
sb.append("payloads:");
if (this.payloads == null) {
sb.append("null");
} else {
sb.append(this.payloads);
}
first = false;
}
if (isSetFetchRequest()) {
if (!first) sb.append(", ");
sb.append("fetchRequest:");
if (this.fetchRequest == null) {
sb.append("null");
} else {
sb.append(this.fetchRequest);
}
first = false;
}
if (isSetStoreRequest()) {
if (!first) sb.append(", ");
sb.append("storeRequest:");
if (this.storeRequest == null) {
sb.append("null");
} else {
sb.append(this.storeRequest);
}
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
if (fetchRequest != null) {
fetchRequest.validate();
}
if (storeRequest != null) {
storeRequest.validate();
}
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class BuckCacheRequestStandardSchemeFactory implements SchemeFactory {
public BuckCacheRequestStandardScheme getScheme() {
return new BuckCacheRequestStandardScheme();
}
}
private static class BuckCacheRequestStandardScheme extends StandardScheme<BuckCacheRequest> {
public void read(org.apache.thrift.protocol.TProtocol iprot, BuckCacheRequest struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // TYPE
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.type = com.facebook.buck.artifact_cache.thrift.BuckCacheRequestType.findByValue(iprot.readI32());
struct.setTypeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 100: // PAYLOADS
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list42 = iprot.readListBegin();
struct.payloads = new ArrayList<PayloadInfo>(_list42.size);
PayloadInfo _elem43;
for (int _i44 = 0; _i44 < _list42.size; ++_i44)
{
_elem43 = new PayloadInfo();
_elem43.read(iprot);
struct.payloads.add(_elem43);
}
iprot.readListEnd();
}
struct.setPayloadsIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 101: // FETCH_REQUEST
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.fetchRequest = new BuckCacheFetchRequest();
struct.fetchRequest.read(iprot);
struct.setFetchRequestIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 102: // STORE_REQUEST
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.storeRequest = new BuckCacheStoreRequest();
struct.storeRequest.read(iprot);
struct.setStoreRequestIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, BuckCacheRequest struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.type != null) {
if (struct.isSetType()) {
oprot.writeFieldBegin(TYPE_FIELD_DESC);
oprot.writeI32(struct.type.getValue());
oprot.writeFieldEnd();
}
}
if (struct.payloads != null) {
if (struct.isSetPayloads()) {
oprot.writeFieldBegin(PAYLOADS_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.payloads.size()));
for (PayloadInfo _iter45 : struct.payloads)
{
_iter45.write(oprot);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
}
if (struct.fetchRequest != null) {
if (struct.isSetFetchRequest()) {
oprot.writeFieldBegin(FETCH_REQUEST_FIELD_DESC);
struct.fetchRequest.write(oprot);
oprot.writeFieldEnd();
}
}
if (struct.storeRequest != null) {
if (struct.isSetStoreRequest()) {
oprot.writeFieldBegin(STORE_REQUEST_FIELD_DESC);
struct.storeRequest.write(oprot);
oprot.writeFieldEnd();
}
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class BuckCacheRequestTupleSchemeFactory implements SchemeFactory {
public BuckCacheRequestTupleScheme getScheme() {
return new BuckCacheRequestTupleScheme();
}
}
private static class BuckCacheRequestTupleScheme extends TupleScheme<BuckCacheRequest> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, BuckCacheRequest struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetType()) {
optionals.set(0);
}
if (struct.isSetPayloads()) {
optionals.set(1);
}
if (struct.isSetFetchRequest()) {
optionals.set(2);
}
if (struct.isSetStoreRequest()) {
optionals.set(3);
}
oprot.writeBitSet(optionals, 4);
if (struct.isSetType()) {
oprot.writeI32(struct.type.getValue());
}
if (struct.isSetPayloads()) {
{
oprot.writeI32(struct.payloads.size());
for (PayloadInfo _iter46 : struct.payloads)
{
_iter46.write(oprot);
}
}
}
if (struct.isSetFetchRequest()) {
struct.fetchRequest.write(oprot);
}
if (struct.isSetStoreRequest()) {
struct.storeRequest.write(oprot);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, BuckCacheRequest struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(4);
if (incoming.get(0)) {
struct.type = com.facebook.buck.artifact_cache.thrift.BuckCacheRequestType.findByValue(iprot.readI32());
struct.setTypeIsSet(true);
}
if (incoming.get(1)) {
{
org.apache.thrift.protocol.TList _list47 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
struct.payloads = new ArrayList<PayloadInfo>(_list47.size);
PayloadInfo _elem48;
for (int _i49 = 0; _i49 < _list47.size; ++_i49)
{
_elem48 = new PayloadInfo();
_elem48.read(iprot);
struct.payloads.add(_elem48);
}
}
struct.setPayloadsIsSet(true);
}
if (incoming.get(2)) {
struct.fetchRequest = new BuckCacheFetchRequest();
struct.fetchRequest.read(iprot);
struct.setFetchRequestIsSet(true);
}
if (incoming.get(3)) {
struct.storeRequest = new BuckCacheStoreRequest();
struct.storeRequest.read(iprot);
struct.setStoreRequestIsSet(true);
}
}
}
}
| apache-2.0 |
0359xiaodong/Android-LollipopShowcase | app/src/main/java/com/mikepenz/lollipopshowcase/adapter/ApplicationAdapter.java | 2203 | package com.mikepenz.lollipopshowcase.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.mikepenz.lollipopshowcase.MainActivity;
import com.mikepenz.lollipopshowcase.R;
import com.mikepenz.lollipopshowcase.entity.AppInfo;
import java.util.List;
public class ApplicationAdapter extends RecyclerView.Adapter<ApplicationAdapter.ViewHolder> {
private List<AppInfo> applications;
private int rowLayout;
private MainActivity mAct;
public ApplicationAdapter(List<AppInfo> applications, int rowLayout, MainActivity act) {
this.applications = applications;
this.rowLayout = rowLayout;
this.mAct = act;
}
public void setApplications(List<AppInfo> applications) {
this.applications = applications;
this.notifyItemRangeInserted(0, applications.size() - 1);
}
@Override
public ViewHolder onCreateViewHolder(final ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(final ViewHolder viewHolder, int i) {
final AppInfo appInfo = applications.get(i);
viewHolder.name.setText(appInfo.getName());
viewHolder.image.setImageDrawable(appInfo.getIcon());
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAct.animateActivity(appInfo, viewHolder.image);
}
});
}
@Override
public int getItemCount() {
return applications == null ? 0 : applications.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public ImageView image;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.countryName);
image = (ImageView) itemView.findViewById(R.id.countryImage);
}
}
}
| apache-2.0 |
BrentDouglas/then | api/src/main/java/io/machinecode/then/api/OnReject.java | 1071 | /*
* Copyright 2015 Brent Douglas and other contributors
* as indicated by the @authors tag. 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 io.machinecode.then.api;
/**
* <p>Listener for a {@link Deferred} entering a {@link Deferred#REJECTED} state.</p>
*
* @see Deferred
* @author <a href="mailto:brent.n.douglas@gmail.com">Brent Douglas</a>
* @since 1.0
*/
public interface OnReject<F> {
/**
* @param fail The exception thrown by the computation represented by this promise.
*/
void reject(final F fail);
}
| apache-2.0 |
lhong375/aura | aura-impl/src/test/java/org/auraframework/impl/java/provider/TestProviderNoImplementation.java | 1191 | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.impl.java.provider;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.impl.system.DefDescriptorImpl;
import org.auraframework.system.Annotations.Provider;
/**
*/
@Provider
public class TestProviderNoImplementation {
public static DefDescriptor<ComponentDef> provide() {
// Provide a component which does not implement
// tes:test_Provider_InterfaceNoImplementation
return DefDescriptorImpl.getInstance("test:test_Provider_NoImpl", ComponentDef.class);
}
}
| apache-2.0 |
heuer/cassa | cassa-server/src/test/java/com/semagia/cassa/server/store/impl/TestDefaultGraphInfo.java | 9386 | /*
* Copyright 2011 Lars Heuer (heuer[at]semagia.com). 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.semagia.cassa.server.store.impl;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import com.semagia.cassa.common.MediaType;
import com.semagia.cassa.common.dm.impl.DefaultResource;
import com.semagia.cassa.server.store.IGraphInfo;
import junit.framework.TestCase;
/**
* Tests against {@link DefaultGraphInfo}.
*
* @author Lars Heuer (heuer[at]semagia.com) <a href="http://www.semagia.com/">Semagia</a>
*/
public class TestDefaultGraphInfo extends TestCase {
private static final URI _DEFAULT_URI = URI.create("http://www.example.org/test");
public void testMediaTypeSingleton() {
final IGraphInfo info = new DefaultGraphInfo(_DEFAULT_URI, MediaType.XTM);
assertEquals(_DEFAULT_URI, info.getURI());
assertEquals(-1, info.getLastModification());
assertEquals(1, info.getSupportedMediaTypes().size());
assertEquals(MediaType.XTM, info.getSupportedMediaTypes().get(0));
assertNull(info.getTitle());
assertNull(info.getDescription());
}
public void testMediaTypeSingletonTitle() {
final String title = "Graph";
final IGraphInfo info = new DefaultGraphInfo(_DEFAULT_URI, MediaType.XTM, -1, title);
assertEquals(_DEFAULT_URI, info.getURI());
assertEquals(-1, info.getLastModification());
assertEquals(1, info.getSupportedMediaTypes().size());
assertEquals(MediaType.XTM, info.getSupportedMediaTypes().get(0));
assertEquals(title, info.getTitle());
assertNull(info.getDescription());
}
public void testMediaTypeSingletonTitleAndDescription() {
final String title = "Graph";
final String descr = "Hi I'm a graph";
final IGraphInfo info = new DefaultGraphInfo(_DEFAULT_URI, MediaType.XTM, -1, title, descr);
assertEquals(_DEFAULT_URI, info.getURI());
assertEquals(-1, info.getLastModification());
assertEquals(1, info.getSupportedMediaTypes().size());
assertEquals(MediaType.XTM, info.getSupportedMediaTypes().get(0));
assertEquals(title, info.getTitle());
assertEquals(descr, info.getDescription());
}
public void testMediaTypeSingletonDescription() {
final String descr = "Hi I'm a graph";
final IGraphInfo info = new DefaultGraphInfo(_DEFAULT_URI, MediaType.XTM, -1, null, descr);
assertEquals(_DEFAULT_URI, info.getURI());
assertEquals(-1, info.getLastModification());
assertEquals(1, info.getSupportedMediaTypes().size());
assertEquals(MediaType.XTM, info.getSupportedMediaTypes().get(0));
assertNull(info.getTitle());
assertEquals(descr, info.getDescription());
}
public void testMediaTypeList() {
final List<MediaType> mediaTypes = new ArrayList<MediaType>();
mediaTypes.add(MediaType.XTM);
mediaTypes.add(MediaType.RDF_XML);
final IGraphInfo info = new DefaultGraphInfo(_DEFAULT_URI, mediaTypes);
assertEquals(_DEFAULT_URI, info.getURI());
assertEquals(-1, info.getLastModification());
assertEquals(2, info.getSupportedMediaTypes().size());
assertTrue(info.getSupportedMediaTypes().contains(MediaType.XTM));
assertTrue(info.getSupportedMediaTypes().contains(MediaType.RDF_XML));
assertNull(info.getTitle());
assertNull(info.getDescription());
}
public void testMediaTypeListTitle() {
final String title = "Graph";
final List<MediaType> mediaTypes = new ArrayList<MediaType>();
mediaTypes.add(MediaType.XTM);
mediaTypes.add(MediaType.RDF_XML);
final IGraphInfo info = new DefaultGraphInfo(_DEFAULT_URI, mediaTypes, -1, title);
assertEquals(_DEFAULT_URI, info.getURI());
assertEquals(-1, info.getLastModification());
assertEquals(2, info.getSupportedMediaTypes().size());
assertTrue(info.getSupportedMediaTypes().contains(MediaType.XTM));
assertTrue(info.getSupportedMediaTypes().contains(MediaType.RDF_XML));
assertEquals(title, info.getTitle());
assertNull(info.getDescription());
}
public void testMediaTypeListTitleAndDescription() {
final String title = "Graph";
final String descr = "Hi I'm a graph";
final List<MediaType> mediaTypes = new ArrayList<MediaType>();
mediaTypes.add(MediaType.XTM);
mediaTypes.add(MediaType.RDF_XML);
final IGraphInfo info = new DefaultGraphInfo(_DEFAULT_URI, mediaTypes, -1, title, descr);
assertEquals(_DEFAULT_URI, info.getURI());
assertEquals(-1, info.getLastModification());
assertEquals(2, info.getSupportedMediaTypes().size());
assertTrue(info.getSupportedMediaTypes().contains(MediaType.XTM));
assertTrue(info.getSupportedMediaTypes().contains(MediaType.RDF_XML));
assertEquals(title, info.getTitle());
assertEquals(descr, info.getDescription());
}
public void testMediaTypeListDescription() {
final String descr = "Hi I'm a graph";
final List<MediaType> mediaTypes = new ArrayList<MediaType>();
mediaTypes.add(MediaType.XTM);
mediaTypes.add(MediaType.RDF_XML);
final IGraphInfo info = new DefaultGraphInfo(_DEFAULT_URI, mediaTypes, -1, null, descr);
assertEquals(_DEFAULT_URI, info.getURI());
assertEquals(-1, info.getLastModification());
assertEquals(2, info.getSupportedMediaTypes().size());
assertTrue(info.getSupportedMediaTypes().contains(MediaType.XTM));
assertTrue(info.getSupportedMediaTypes().contains(MediaType.RDF_XML));
assertNull(info.getTitle());
assertEquals(descr, info.getDescription());
}
public void testMediaTypeListNull() {
final List<MediaType> mediaTypes = null;
try {
new DefaultGraphInfo(_DEFAULT_URI, mediaTypes);
fail("Graph accepts null as media types argument");
}
catch (IllegalArgumentException ex) {
// noop.
}
}
public void testMediaTypeNull() {
final MediaType mediaType = null;
try {
new DefaultGraphInfo(_DEFAULT_URI, mediaType);
fail("Graph accepts null as media type argument");
}
catch (IllegalArgumentException ex) {
// noop.
}
}
public void testEquals() {
final IGraphInfo info1 = new DefaultGraphInfo(_DEFAULT_URI, MediaType.CTM);
IGraphInfo info2 = new DefaultGraphInfo(_DEFAULT_URI, MediaType.CTM);
assertEquals(info1, info1);
assertEquals(info1, info2);
assertEquals(info2, info1);
assertEquals(info1.hashCode(), info2.hashCode());
info2 = new DefaultGraphInfo(_DEFAULT_URI, MediaType.RDF_XML);
assertFalse(info1.equals(info2));
assertFalse(info1.hashCode() == info2.hashCode());
}
public void testNotEquals() {
final IGraphInfo info1 = new DefaultGraphInfo(_DEFAULT_URI, MediaType.CTM);
final IGraphInfo info2 = new DefaultFragmentInfo(_DEFAULT_URI, new DefaultResource(URI.create("http://www.example.org/resource")), MediaType.CTM);
assertFalse(info1.equals(info2));
assertFalse(info2.equals(info1));
assertFalse(info1.hashCode() == info2.hashCode());
}
public void testDate() {
final long date = new Date().getTime();
final IGraphInfo info = new DefaultGraphInfo(_DEFAULT_URI, MediaType.XTM, date);
assertEquals(_DEFAULT_URI, info.getURI());
assertEquals(date, info.getLastModification());
assertEquals(1, info.getSupportedMediaTypes().size());
assertNull(info.getTitle());
assertNull(info.getDescription());
}
public void testURIIllegal() {
try {
new DefaultGraphInfo(null, MediaType.XTM);
fail("Expected an exception for URI == null");
}
catch (IllegalArgumentException ex) {
// noop.
}
try {
new DefaultGraphInfo(null, MediaType.XTM, -1);
fail("Expected an exception for URI == null");
}
catch (IllegalArgumentException ex) {
// noop.
}
try {
new DefaultGraphInfo(null, Collections.singletonList(MediaType.XTM));
fail("Expected an exception for URI == null");
}
catch (IllegalArgumentException ex) {
// noop.
}
try {
new DefaultGraphInfo(null, Collections.singletonList(MediaType.XTM), -1);
fail("Expected an exception for URI == null");
}
catch (IllegalArgumentException ex) {
// noop.
}
}
}
| apache-2.0 |
CognizantQAHub/Cognizant-Intelligent-Test-Scripter | QcConnection/src/main/java/com/cognizant/cognizantits/qcconnection/qcupdation/IHistoryRecord2.java | 521 | package com.cognizant.cognizantits.qcconnection.qcupdation;
import com4j.DISPID;
import com4j.IID;
import com4j.NativeType;
import com4j.ReturnValue;
import com4j.VTID;
@IID("{E672B813-30DA-4429-97A7-A1616F0B7D2D}")
public abstract interface IHistoryRecord2
extends IHistoryRecord
{
@DISPID(6)
@VTID(12)
@ReturnValue(type=NativeType.VARIANT)
public abstract Object oldValue();
}
/* Location: D:\Prabu\jars\QC.jar
* Qualified Name: qcupdation.IHistoryRecord2
* JD-Core Version: 0.7.0.1
*/ | apache-2.0 |
skysign/public | basic_algorithm/src/BasicAlgorithm00/src/com/tistory/skysign/BasicAlgorithm/Sort/MergeSort2.java | 1896 | package com.tistory.skysign.BasicAlgorithm.Sort;
public class MergeSort2 extends SortBase{
static public int nTmps[] = new int[MAX];
static public void MergeSort(int data[], int idxLeft, int idxRight) {
if (idxLeft < idxRight) {
int i, j, k, idxMiddle;
idxMiddle = (idxLeft + idxRight) / 2;
System.out.println("idxLeft " + idxLeft + " idxMiddle " + idxMiddle + " idxRight " + idxRight);
MergeSort(data, idxLeft, idxMiddle);
MergeSort(data, idxMiddle+1, idxRight);
for (i = idxLeft; i <= idxMiddle; ++i) {
nTmps[i] = data[i];
}
for (j = idxMiddle +1; j <= idxRight; ++j) {
nTmps[j] = data[j];
}
i = idxLeft;
j = idxMiddle +1;
for(k = idxLeft; k <= idxRight; ++k) {
if (nTmps[i] < nTmps[j]) {
data[k] = nTmps[i];
i++;
if (i > idxMiddle) {
break;
}
}
else {
data[k] = nTmps[j];
j++;
if (j > idxRight) {
break;
}
}
}
++k;
for ( ; i <= idxMiddle; ++i, ++k) {
data[k] = nTmps[i];
}
for ( ; j <= idxRight; ++j, ++k) {
data[k] = nTmps[j];
}
DisplayBuffer();
}
}
static public void mergeSort() {
MergeSort(mBuf, 0, MAX -1);
}
static public void run() {
System.out.println("MergeSort2");
makeRandomNumber();
System.out.println("Input");
DisplayBuffer();
mergeSort();
System.out.println("Result");
DisplayBuffer();
}
}
| apache-2.0 |
eBaoTech/cas | cas-server-support-saml/src/main/java/org/jasig/cas/support/saml/authentication/principal/SamlService.java | 2840 | /*
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo 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 the following location:
*
* 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.jasig.cas.support.saml.authentication.principal;
import org.jasig.cas.authentication.principal.AbstractWebApplicationService;
import org.jasig.cas.authentication.principal.DefaultResponse;
import org.jasig.cas.authentication.principal.Response;
import org.jasig.cas.support.saml.SamlProtocolConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* Class to represent that this service wants to use SAML. We use this in
* combination with the CentralAuthenticationServiceImpl to choose the right
* UniqueTicketIdGenerator.
*
* @author Scott Battaglia
* @since 3.1
*/
public final class SamlService extends AbstractWebApplicationService {
private static final Logger LOGGER = LoggerFactory.getLogger(SamlService.class);
/**
* Unique Id for serialization.
*/
private static final long serialVersionUID = -6867572626767140223L;
private String requestId;
/**
* Instantiates a new SAML service.
*
* @param id the service id
*/
protected SamlService(final String id) {
super(id, id, null);
}
/**
* Instantiates a new SAML service.
*
* @param id the service id
* @param originalUrl the original url
* @param artifactId the artifact id
* @param requestId the request id
*/
protected SamlService(final String id, final String originalUrl,
final String artifactId, final String requestId) {
super(id, originalUrl, artifactId);
this.requestId = requestId;
}
public String getRequestID() {
return this.requestId;
}
@Override
public Response getResponse(final String ticketId) {
final Map<String, String> parameters = new HashMap<>();
parameters.put(SamlProtocolConstants.CONST_PARAM_ARTIFACT, ticketId);
return DefaultResponse.getRedirectResponse(getOriginalUrl(), parameters);
}
}
| apache-2.0 |
paplorinc/intellij-community | platform/diff-impl/src/com/intellij/diff/DiffContentFactoryImpl.java | 24239 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff;
import com.intellij.codeInsight.daemon.OutsidersPsiFileSupport;
import com.intellij.diff.actions.DocumentFragmentContent;
import com.intellij.diff.contents.*;
import com.intellij.diff.tools.util.DiffNotifications;
import com.intellij.diff.util.DiffUserDataKeysEx;
import com.intellij.diff.util.DiffUtil;
import com.intellij.ide.highlighter.ArchiveFileType;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.*;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.encoding.EncodingManager;
import com.intellij.openapi.vfs.encoding.EncodingProjectManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.testFramework.BinaryLightVirtualFile;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.ui.LightColors;
import com.intellij.util.LineSeparator;
import com.intellij.util.ObjectUtils;
import com.intellij.util.PathUtil;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.datatransfer.DataFlavor;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
public class DiffContentFactoryImpl extends DiffContentFactoryEx {
private static final Logger LOG = Logger.getInstance(DiffContentFactoryImpl.class);
@NotNull
@Override
public EmptyContent createEmpty() {
return new EmptyContent();
}
@NotNull
@Override
public DocumentContent create(@NotNull String text) {
return create(null, text);
}
@NotNull
@Override
public DocumentContent create(@NotNull String text, @Nullable FileType type) {
return create(null, text, type);
}
@NotNull
@Override
public DocumentContent create(@NotNull String text, @Nullable FileType type, boolean respectLineSeparators) {
return create(null, text, type, respectLineSeparators);
}
@NotNull
@Override
public DocumentContent create(@NotNull String text, @Nullable VirtualFile highlightFile) {
return create(null, text, highlightFile);
}
@NotNull
@Override
public DocumentContent create(@NotNull String text, @Nullable DocumentContent referent) {
return create(null, text, referent);
}
@NotNull
@Override
public DocumentContent create(@Nullable Project project, @NotNull String text) {
return create(project, text, (FileType)null);
}
@NotNull
@Override
public DocumentContent create(@Nullable Project project, @NotNull String text, @Nullable FileType type) {
return create(project, text, type, true);
}
@NotNull
@Override
public DocumentContent create(@Nullable Project project, @NotNull String text, @Nullable FileType type, boolean respectLineSeparators) {
return createImpl(project, text, type, null, null, null, respectLineSeparators, true);
}
@NotNull
@Override
public DocumentContent create(@Nullable Project project, @NotNull String text, @NotNull FilePath filePath) {
return createImpl(project, text, filePath.getFileType(), filePath, filePath.getName(), filePath.getVirtualFile(), true, true);
}
@NotNull
@Override
public DocumentContent create(@Nullable Project project, @NotNull String text, @Nullable VirtualFile highlightFile) {
FileType fileType = highlightFile != null ? highlightFile.getFileType() : null;
FilePath filePath = highlightFile != null ? VcsUtil.getFilePath(highlightFile) : null;
String fileName = highlightFile != null ? highlightFile.getName() : null;
return createImpl(project, text, fileType, filePath, fileName, highlightFile, true, true);
}
@NotNull
@Override
public DocumentContent create(@Nullable Project project, @NotNull String text, @Nullable DocumentContent referent) {
if (referent == null) return create(text);
return createImpl(project, text, referent.getContentType(), null, null, referent.getHighlightFile(), false, true);
}
@NotNull
@Override
public DocumentContent createEditable(@Nullable Project project, @NotNull String text, @Nullable FileType fileType) {
return createImpl(project, text, fileType, null, null, null, false, false);
}
@NotNull
@Override
public DocumentContent create(@NotNull Document document, @Nullable DocumentContent referent) {
return create(null, document, referent);
}
@NotNull
@Override
public DocumentContent create(@Nullable Project project, @NotNull Document document) {
return create(project, document, (FileType)null);
}
@NotNull
@Override
public DocumentContent create(@Nullable Project project, @NotNull Document document, @Nullable FileType fileType) {
VirtualFile file = FileDocumentManager.getInstance().getFile(document);
if (file != null) return new FileDocumentContentImpl(project, document, file);
return new DocumentContentImpl(project, document, fileType, null, null, null, null);
}
@NotNull
@Override
public DocumentContent create(@Nullable Project project, @NotNull Document document, @Nullable VirtualFile highlightFile) {
VirtualFile file = FileDocumentManager.getInstance().getFile(document);
if (file != null && file.equals(highlightFile)) return new FileDocumentContentImpl(project, document, file);
if (highlightFile == null) return new DocumentContentImpl(document);
return new DocumentContentImpl(project, document, highlightFile.getFileType(), highlightFile, null, null, null);
}
@NotNull
@Override
public DocumentContent create(@Nullable Project project, @NotNull Document document, @Nullable DocumentContent referent) {
if (referent == null) return new DocumentContentImpl(document);
return new DocumentContentImpl(project, document, referent.getContentType(), referent.getHighlightFile(), null, null, null);
}
@NotNull
@Override
public DiffContent create(@Nullable Project project, @NotNull VirtualFile file) {
return createContentFromFile(project, file);
}
@Nullable
@Override
public DocumentContent createDocument(@Nullable Project project, @NotNull final VirtualFile file) {
return ObjectUtils.tryCast(createContentFromFile(project, file), DocumentContent.class);
}
@Nullable
@Override
public FileContent createFile(@Nullable Project project, @NotNull VirtualFile file) {
if (file.isDirectory()) return null;
return (FileContent)create(project, file);
}
@NotNull
@Override
public DocumentContent createFragment(@Nullable Project project, @NotNull Document document, @NotNull TextRange range) {
DocumentContent content = create(project, document);
return createFragment(project, content, range);
}
@NotNull
@Override
public DocumentContent createFragment(@Nullable Project project, @NotNull DocumentContent content, @NotNull TextRange range) {
return new DocumentFragmentContent(project, content, range);
}
@NotNull
@Override
public DiffContent createClipboardContent() {
return createClipboardContent(null, null);
}
@NotNull
@Override
public DocumentContent createClipboardContent(@Nullable DocumentContent referent) {
return createClipboardContent(null, referent);
}
@NotNull
@Override
public DiffContent createClipboardContent(@Nullable Project project) {
return createClipboardContent(project, null);
}
@NotNull
@Override
public DocumentContent createClipboardContent(@Nullable Project project, @Nullable DocumentContent referent) {
String text = CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor);
FileType type = referent != null ? referent.getContentType() : null;
VirtualFile highlightFile = referent != null ? referent.getHighlightFile() : null;
FilePath filePath = highlightFile != null ? VcsUtil.getFilePath(highlightFile) : null;
return createImpl(project, StringUtil.notNullize(text), type, filePath, "Clipboard.txt", highlightFile, false, false);
}
@NotNull
@Override
public DiffContent createFromBytes(@Nullable Project project,
@NotNull byte[] content,
@NotNull FilePath filePath) throws IOException {
return createFromBytes(project, content, filePath, null);
}
@NotNull
@Override
public DiffContent createFromBytes(@Nullable Project project,
@NotNull byte[] content,
@NotNull FilePath filePath,
@Nullable Charset defaultCharset) throws IOException {
if (defaultCharset == null && isBinaryContent(content, filePath.getFileType())) {
return createBinaryImpl(project, content, filePath.getFileType(), filePath, filePath.getVirtualFile());
}
return createDocumentFromBytes(project, content, filePath, defaultCharset);
}
@NotNull
@Override
public DiffContent createFromBytes(@Nullable Project project,
@NotNull byte[] content,
@NotNull FileType fileType,
@NotNull String fileName) throws IOException {
if (isBinaryContent(content, fileType)) {
return createBinaryImpl(project, content, fileType, VcsUtil.getFilePath(fileName), null);
}
return createDocumentFromBytes(project, content, fileType, fileName);
}
@NotNull
@Override
public DiffContent createFromBytes(@Nullable Project project,
@NotNull byte[] content,
@NotNull VirtualFile highlightFile) throws IOException {
if (isBinaryContent(content, highlightFile.getFileType())) {
return createBinaryImpl(project, content, highlightFile.getFileType(), VcsUtil.getFilePath(highlightFile), highlightFile);
}
return createDocumentFromBytes(project, content, highlightFile);
}
@NotNull
@Override
public DocumentContent createDocumentFromBytes(@Nullable Project project,
@NotNull byte[] content,
@NotNull FileType fileType,
@NotNull String fileName) {
Charset charset = guessCharset(project, content, fileType);
return createFromBytesImpl(project, content, fileType, null, fileName, null, charset);
}
@NotNull
@Override
public DocumentContent createDocumentFromBytes(@Nullable Project project, @NotNull byte[] content, @NotNull FilePath filePath) {
Charset charset = guessCharset(content, filePath);
return createFromBytesImpl(project, content, filePath.getFileType(), filePath, filePath.getName(), filePath.getVirtualFile(), charset);
}
@NotNull
private static DocumentContent createDocumentFromBytes(@Nullable Project project,
@NotNull byte[] content,
@NotNull FilePath filePath,
@Nullable Charset defaultCharset) {
Charset charset = guessCharset(content, filePath.getFileType(), defaultCharset != null ? defaultCharset : filePath.getCharset());
return createFromBytesImpl(project, content, filePath.getFileType(), filePath, filePath.getName(), filePath.getVirtualFile(), charset);
}
@NotNull
@Override
public DocumentContent createDocumentFromBytes(@Nullable Project project, @NotNull byte[] content, @NotNull VirtualFile highlightFile) {
Charset charset = guessCharset(content, highlightFile);
FilePath filePath = VcsUtil.getFilePath(highlightFile);
return createFromBytesImpl(project, content, highlightFile.getFileType(), filePath, highlightFile.getName(), highlightFile, charset);
}
@NotNull
@Override
public DiffContent createBinary(@Nullable Project project,
@NotNull byte[] content,
@NotNull FileType type,
@NotNull String fileName) throws IOException {
return createBinaryImpl(project, content, type, VcsUtil.getFilePath(fileName), null);
}
@NotNull
private static DiffContent createContentFromFile(@Nullable Project project,
@NotNull VirtualFile file) {
return createContentFromFile(project, file, file);
}
@NotNull
private static DiffContent createContentFromFile(@Nullable Project project,
@NotNull VirtualFile file,
@Nullable VirtualFile highlightFile) {
if (file.isDirectory()) return new DirectoryContentImpl(project, file, highlightFile);
Document document = ReadAction.compute(() -> FileDocumentManager.getInstance().getDocument(file));
if (document != null) {
// TODO: add notification if file is decompiled ?
return new FileDocumentContentImpl(project, document, file, highlightFile);
}
else {
return new FileContentImpl(project, file, highlightFile);
}
}
@NotNull
private static DiffContent createBinaryImpl(@Nullable Project project,
@NotNull byte[] content,
@NotNull FileType type,
@NotNull FilePath path,
@Nullable VirtualFile highlightFile) throws IOException {
// workaround - our JarFileSystem and decompilers can't process non-local files
boolean useTemporalFile = type instanceof ArchiveFileType || BinaryFileTypeDecompilers.INSTANCE.forFileType(type) != null;
VirtualFile file;
if (useTemporalFile) {
file = createTemporalFile(project, "tmp", path.getName(), content);
}
else {
file = new MyBinaryLightVirtualFile(path, type, content);
file.setWritable(false);
}
file.putUserData(DiffUtil.TEMP_FILE_KEY, Boolean.TRUE);
return createContentFromFile(project, file, highlightFile);
}
@NotNull
private static DocumentContent createImpl(@Nullable Project project,
@NotNull String text,
@Nullable FileType fileType,
@Nullable FilePath originalFilePath,
@Nullable String fileName,
@Nullable VirtualFile highlightFile,
boolean respectLineSeparators,
boolean readOnly) {
return createImpl(project, text, fileType, originalFilePath, fileName, highlightFile, null, null, respectLineSeparators, readOnly);
}
@NotNull
private static DocumentContent createImpl(@Nullable Project project,
@NotNull String text,
@Nullable FileType fileType,
@Nullable FilePath originalFilePath,
@Nullable String fileName,
@Nullable VirtualFile highlightFile,
@Nullable Charset charset,
@Nullable Boolean bom,
boolean respectLineSeparators,
boolean readOnly) {
if (FileTypes.UNKNOWN.equals(fileType)) fileType = PlainTextFileType.INSTANCE;
// TODO: detect invalid (different across the file) separators ?
LineSeparator separator = respectLineSeparators ? StringUtil.detectSeparators(text) : null;
String correctedContent = StringUtil.convertLineSeparators(text);
Document document = createDocument(project, correctedContent, fileType, originalFilePath, fileName, readOnly);
DocumentContent content = new DocumentContentImpl(project, document, fileType, highlightFile, separator, charset, bom);
if (fileName != null) content.putUserData(DiffUserDataKeysEx.FILE_NAME, fileName);
return content;
}
@NotNull
private static DocumentContent createFromBytesImpl(@Nullable Project project,
@NotNull byte[] content,
@NotNull FileType fileType,
@Nullable FilePath originalFilePath,
@NotNull String fileName,
@Nullable VirtualFile highlightFile,
@NotNull Charset charset) {
if (fileType.isBinary()) fileType = PlainTextFileType.INSTANCE;
boolean isBOM = CharsetToolkit.guessFromBOM(content) != null;
boolean malformedContent = false;
String text = CharsetToolkit.tryDecodeString(content, charset);
if (text == null) {
text = CharsetToolkit.decodeString(content, charset);
malformedContent = true;
}
DocumentContent documentContent = createImpl(project, text, fileType, originalFilePath, fileName, highlightFile,
charset, isBOM, true, true);
if (malformedContent) {
String notificationText = "Content was decoded with errors (using " + "'" + charset.name() + "' charset)";
DiffUtil.addNotification(DiffNotifications.createNotification(notificationText, LightColors.RED), documentContent);
}
return documentContent;
}
@NotNull
private static VirtualFile createTemporalFile(@Nullable Project project,
@NotNull String prefix,
@NotNull String suffix,
@NotNull byte[] content) throws IOException {
File tempFile = FileUtil.createTempFile(PathUtil.suggestFileName(prefix + "_", true, false),
PathUtil.suggestFileName("_" + suffix, true, false), true);
if (content.length != 0) {
FileUtil.writeToFile(tempFile, content);
}
if (!tempFile.setWritable(false, false)) LOG.warn("Can't set writable attribute of temporal file");
VirtualFile file = VfsUtil.findFileByIoFile(tempFile, true);
if (file == null) {
throw new IOException("Can't create temp file for revision content");
}
VfsUtil.markDirtyAndRefresh(true, true, true, file);
return file;
}
@NotNull
private static Document createDocument(@Nullable Project project,
@NotNull String content,
@Nullable FileType fileType,
@Nullable FilePath originalFilePath,
@Nullable String fileName,
boolean readOnly) {
if (project != null && !project.isDefault() &&
fileType != null && !fileType.isBinary() &&
Registry.is("diff.enable.psi.highlighting")) {
if (fileName == null) {
fileName = "diff." + StringUtil.defaultIfEmpty(fileType.getDefaultExtension(), "txt");
}
Document document = createPsiDocument(project, content, fileType, originalFilePath, fileName, readOnly);
if (document != null) return document;
}
Document document = EditorFactory.getInstance().createDocument(content);
document.setReadOnly(readOnly);
return document;
}
@Nullable
private static Document createPsiDocument(@NotNull Project project,
@NotNull String content,
@NotNull FileType fileType,
@Nullable FilePath originalFilePath,
@NotNull String fileName,
boolean readOnly) {
return ReadAction.compute(() -> {
LightVirtualFile file = new LightVirtualFile(fileName, fileType, content);
file.setWritable(!readOnly);
OutsidersPsiFileSupport.markFile(file, originalFilePath != null ? originalFilePath.getPath() : null);
Document document = FileDocumentManager.getInstance().getDocument(file);
if (document == null) return null;
PsiDocumentManager.getInstance(project).getPsiFile(document);
return document;
});
}
private static boolean isBinaryContent(@NotNull byte[] content, @NotNull FileType fileType) {
if (UnknownFileType.INSTANCE.equals(fileType)) {
return guessCharsetFromContent(content) == null;
}
if (fileType instanceof UIBasedFileType) {
return true;
}
return fileType.isBinary();
}
@NotNull
public static Charset guessCharset(@NotNull byte[] content, @NotNull FilePath filePath) {
return guessCharset(content, filePath.getFileType(), filePath.getCharset());
}
@NotNull
public static Charset guessCharset(@NotNull byte[] content, @NotNull VirtualFile highlightFile) {
return guessCharset(content, highlightFile.getFileType(), highlightFile.getCharset());
}
@NotNull
public static Charset guessCharset(@Nullable Project project, @NotNull byte[] content, @NotNull FileType fileType) {
EncodingManager e = project != null ? EncodingProjectManager.getInstance(project) : EncodingManager.getInstance();
return guessCharset(content, fileType, e.getDefaultCharset());
}
@NotNull
private static Charset guessCharset(@NotNull byte[] content, @NotNull FileType fileType, @NotNull Charset defaultCharset) {
Charset bomCharset = CharsetToolkit.guessFromBOM(content);
if (bomCharset != null) return bomCharset;
if (fileType.isBinary()) {
Charset guessedCharset = guessCharsetFromContent(content);
if (guessedCharset != null) return guessedCharset;
}
return defaultCharset;
}
@Nullable
private static Charset guessCharsetFromContent(@NotNull byte[] content) {
// can't use CharsetToolkit.guessEncoding here because of false-positive INVALID_UTF8
CharsetToolkit toolkit = new CharsetToolkit(content);
Charset fromBOM = toolkit.guessFromBOM();
if (fromBOM != null) return fromBOM;
CharsetToolkit.GuessedEncoding guessedEncoding = toolkit.guessFromContent(content.length);
switch (guessedEncoding) {
case SEVEN_BIT:
return Charset.forName("US-ASCII");
case VALID_UTF8:
return CharsetToolkit.UTF8_CHARSET;
default:
return null;
}
}
private static class MyBinaryLightVirtualFile extends BinaryLightVirtualFile {
private final FilePath myPath;
MyBinaryLightVirtualFile(@NotNull FilePath path, FileType type, @NotNull byte[] content) {
super(path.getName(), type, content);
myPath = path;
}
@NotNull
@Override
public String getPath() {
return myPath.getPath();
}
}
}
| apache-2.0 |
GiapIT/TuDienAnhViet | app/src/main/java/nguyengiap/vietitpro/tudienanhviet/com/ui/materialsearch/searchview/SearchAdapter.java | 6967 | package nguyengiap.vietitpro.tudienanhviet.com.ui.materialsearch.searchview;
import android.content.Context;
import android.graphics.PorterDuff;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import nguyengiap.vietitpro.tudienanhviet.com.R;
import nguyengiap.vietitpro.tudienanhviet.com.model.EVEntity;
// TODO file:///E:/Android/SearchView/sample/build/outputs/lint-results-debug.html
// TODO file:///E:/Android/SearchView/searchview/build/outputs/lint-results-debug.html
// TODO voice click result
// TODO ARROW / HAMBURGER / BEHAVIOR / SingleTask / DIVIDER BUG
// TODO E/RecyclerView: No adapter attached; skipping layout when search
// W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
/*
I'm using your SearchView library (thanks btw)
and it seems to have a problem on filters with no results.
When i type texts that don't have a match in the history, all of it is displayed as suggestions.
*/
@SuppressWarnings("WeakerAccess")
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.ResultViewHolder> implements Filterable {
protected final SearchHistoryTable mHistoryDatabase;
protected String key = " ";
protected List<EVEntity> mResultList = new ArrayList<>();
protected List<EVEntity> mSuggestionsList = new ArrayList<>();
protected OnItemClickListener mItemClickListener;
@SuppressWarnings("unused")
public SearchAdapter(Context context) {// getContext();
mHistoryDatabase = new SearchHistoryTable(context);
}
public SearchAdapter(Context context, List<EVEntity> suggestionsList) {
mSuggestionsList = suggestionsList;
mHistoryDatabase = new SearchHistoryTable(context);
}
@SuppressWarnings("unused")
public List<EVEntity> getSuggestionsList() {
return mSuggestionsList;
}
@SuppressWarnings("unused")
public void setSuggestionsList(List<EVEntity> suggestionsList) {
mSuggestionsList = suggestionsList;
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (!TextUtils.isEmpty(constraint)) {
key = constraint.toString().toLowerCase(Locale.getDefault());
List<EVEntity> results = new ArrayList<>();
List<EVEntity> history = new ArrayList<>();
if (!mHistoryDatabase.getAllItems().isEmpty()) {
history.addAll(mHistoryDatabase.getAllItems());
}
history.addAll(mSuggestionsList);
for (EVEntity str : history) {
String string = str.getWord().toLowerCase(Locale.getDefault());
if (string.contains(key)) {
results.add(str);
}
}
if (results.size() > 0) {
filterResults.values = results;
filterResults.count = results.size();
}
} else {
key = " ";
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mResultList.clear();
if (results.values != null) {
List<?> result = (ArrayList<?>) results.values;
for (Object object : result) {
if (object instanceof EVEntity) {
mResultList.add((EVEntity) object);
}
}
} else {
if (!mHistoryDatabase.getAllItems().isEmpty()) {
mResultList = mHistoryDatabase.getAllItems();
}
}
notifyDataSetChanged();
}
};
}
@Override
public ResultViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final View view = inflater.inflate(R.layout.search_item, parent, false);
return new ResultViewHolder(view);
}
@Override
public void onBindViewHolder(ResultViewHolder viewHolder, int position) {
EVEntity item = mResultList.get(position);
viewHolder.icon_left.setImageResource(R.drawable.ic_abs__ic_search);
viewHolder.icon_left.setColorFilter(SearchView.getIconColor(), PorterDuff.Mode.SRC_IN);
viewHolder.text.setTextColor(SearchView.getTextColor());
String string = item.getWord().toString().toLowerCase(Locale.getDefault());
if (string.contains(key)) {
SpannableString s = new SpannableString(string);
s.setSpan(new ForegroundColorSpan(SearchView.getTextHighlightColor()), string.indexOf(key), string.indexOf(key) + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
viewHolder.text.setText(s, TextView.BufferType.SPANNABLE);
} else {
viewHolder.text.setText(item.getWord());
}
}
@Override
public int getItemCount() {
return mResultList.size();
}
public void setOnItemClickListener(OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
class ResultViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final ImageView icon_left;
final TextView text;
ResultViewHolder(View view) {
super(view);
icon_left = (ImageView) view.findViewById(R.id.imageView_item_icon_left);
text = (TextView) view.findViewById(R.id.textView_item_text);
view.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(v, getLayoutPosition());
}
}
}
}
/*else {
s.removeSpan(new ForegroundColorSpan(SearchView.getTextColor()));
viewHolder.text.setText(s, TextView.BufferType.SPANNABLE);
}*/ | apache-2.0 |
iqrfsdk/jsimply | simply-modules/simply-iqrf-dpa22x/simply-iqrf-dpa-v22x/src/main/java/com/microrisc/simply/iqrf/dpa/v22x/services/node/write_configuration/WriteConfigurationService.java | 1234 | /*
* Copyright 2016 MICRORISC s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microrisc.simply.iqrf.dpa.v22x.services.node.write_configuration;
import com.microrisc.simply.services.Service;
import com.microrisc.simply.services.ServiceResult;
/**
* Write Configuration Service.
*
* @author Michal Konopa
*/
public interface WriteConfigurationService extends Service {
/**
* Writes configuration according to specified parameters.
*
* @param params parameters of writing configuration
* @return result
*/
ServiceResult<WriteResult, WriteConfigurationProcessingInfo> writeConfiguration(
WriteConfigurationServiceParameters params
);
}
| apache-2.0 |
springfox/springfox | swagger-contract-tests/src/main/java/springfox/test/contract/swagger/models/Bug3087.java | 579 | package springfox.test.contract.swagger.models;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel
public class Bug3087 {
@ApiModelProperty(required = true, position = 2)
private String user;
@ApiModelProperty(required = true, position = 1)
private String password;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
} | apache-2.0 |
MayerTh/RVRPSimulator | vrpsim-core/src/main/java/vrpsim/core/model/structure/driver/IDriver.java | 1026 | /**
* Copyright © 2016 Thomas Mayer (thomas.mayer@unibw.de)
*
* 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 vrpsim.core.model.structure.driver;
import vrpsim.core.model.events.IEventOwner;
import vrpsim.core.model.structure.IVRPSimulationModelStructureElement;
import vrpsim.core.model.structure.IVRPSimulationModelStructureElementMovable;
/**
* @date 19.02.2016
* @author thomas.mayer@unibw.de
*
*/
public interface IDriver extends IEventOwner, IVRPSimulationModelStructureElementMovable {
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-lexmodelsv2/src/main/java/com/amazonaws/services/lexmodelsv2/model/transform/BotRecommendationSummaryMarshaller.java | 3238 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.lexmodelsv2.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.lexmodelsv2.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* BotRecommendationSummaryMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class BotRecommendationSummaryMarshaller {
private static final MarshallingInfo<String> BOTRECOMMENDATIONSTATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("botRecommendationStatus").build();
private static final MarshallingInfo<String> BOTRECOMMENDATIONID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("botRecommendationId").build();
private static final MarshallingInfo<java.util.Date> CREATIONDATETIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("creationDateTime").timestampFormat("unixTimestamp").build();
private static final MarshallingInfo<java.util.Date> LASTUPDATEDDATETIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("lastUpdatedDateTime").timestampFormat("unixTimestamp").build();
private static final BotRecommendationSummaryMarshaller instance = new BotRecommendationSummaryMarshaller();
public static BotRecommendationSummaryMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(BotRecommendationSummary botRecommendationSummary, ProtocolMarshaller protocolMarshaller) {
if (botRecommendationSummary == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(botRecommendationSummary.getBotRecommendationStatus(), BOTRECOMMENDATIONSTATUS_BINDING);
protocolMarshaller.marshall(botRecommendationSummary.getBotRecommendationId(), BOTRECOMMENDATIONID_BINDING);
protocolMarshaller.marshall(botRecommendationSummary.getCreationDateTime(), CREATIONDATETIME_BINDING);
protocolMarshaller.marshall(botRecommendationSummary.getLastUpdatedDateTime(), LASTUPDATEDDATETIME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
metatron-app/metatron-discovery | discovery-server/src/test/java/app/metatron/discovery/domain/datasource/connection/jdbc/MySQLConnectionTest.java | 9204 | /*
* 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 app.metatron.discovery.domain.datasource.connection.jdbc;
import au.com.bytecode.opencsv.CSVReader;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.supercsv.prefs.CsvPreference;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import app.metatron.discovery.AbstractIntegrationTest;
import app.metatron.discovery.domain.dataconnection.DataConnection;
import app.metatron.discovery.domain.dataconnection.DataConnectionHelper;
import app.metatron.discovery.extension.dataconnection.jdbc.dialect.JdbcDialect;
/**
* Created by kyungtaak on 2016. 7. 2..
*/
public class MySQLConnectionTest extends AbstractIntegrationTest {
@Autowired
JdbcConnectionService jdbcConnectionService;
private Pageable pageable = new PageRequest(0, 100);
@Test
public void showMySQLDatabases() {
DataConnection connection = new DataConnection("MYSQL");
connection.setHostname("localhost");
connection.setPort(3306);
//connection.setDatabase("polaris_datasources");
connection.setUsername("polaris");
connection.setPassword("polaris");
System.out.println(jdbcConnectionService.getDatabases(connection, null, pageable));
}
@Test
public void showTiberoDatabases() {
DataConnection connection = new DataConnection("TIBERO");
connection.setHostname("localhost");
connection.setPort(3306);
//connection.setDatabase("polaris_datasources");
connection.setUsername("polaris");
connection.setPassword("polaris");
System.out.println(jdbcConnectionService.getDatabases(connection, null, pageable));
}
@Test
public void showMySQLTables() {
DataConnection connection = new DataConnection("MYSQL");
connection.setHostname("localhost");
//connection.setDatabase("polaris");
connection.setUsername("polaris");
connection.setPassword("polaris");
connection.setPort(3306);
System.out.println(new JdbcConnectionService().getDatabases(connection, null, null));
}
@Test
public void searchMysqlDatabases() {
DataConnection connection = new DataConnection("MYSQL");
connection.setHostname("localhost");
//connection.setDatabase("sample");
connection.setUsername("polaris");
connection.setPassword("polaris");
connection.setPort(3306);
PageRequest pageRequest = new PageRequest(0, 20);
String searchKeyword = "ME";
Map<String, Object> databaseList = jdbcConnectionService.getDatabases(connection, searchKeyword, pageRequest);
System.out.println(databaseList);
}
@Test
public void searchMysqlTables() {
DataConnection connection = new DataConnection("MYSQL");
connection.setHostname("localhost");
// connection.setDatabase("sample");
connection.setUsername("polaris");
connection.setPassword("polaris");
connection.setPort(3306);
PageRequest pageRequest = new PageRequest(0, 20);
String searchKeyword = "";
String schema = "metatron";
Map<String, Object> tableMap = jdbcConnectionService.getTables(connection, schema, searchKeyword, pageRequest);
List<Map<String, Object>> tableList = (List) tableMap.get("tables");
Map<String, Object> pageInfo = (Map) tableMap.get("page");
System.out.println("pageInfo = " + pageInfo);
for(Map<String, Object> tableMapObj : tableList){
System.out.println(tableMapObj);
String tableName = (String) tableMapObj.get("name");
Assert.assertTrue(StringUtils.containsIgnoreCase(tableName, searchKeyword));
}
}
@Test
public void showTableInfoMySQL() {
DataConnection connection = new DataConnection("MYSQL");
connection.setHostname("localhost");
//connection.setDatabase("sample");
connection.setUsername("polaris");
connection.setPassword("polaris");
connection.setPort(3306);
String databaseName = "sample";
String tableName = "sales";
Map<String, Object> tableDescMap = jdbcConnectionService.showTableDescription(connection, databaseName, tableName);
for(String key : tableDescMap.keySet()){
System.out.println(key + " = " + tableDescMap.get(key));
}
}
@Test
public void showTableColumnMySQL() {
DataConnection connection = new DataConnection("MYSQL");
connection.setHostname("localhost");
connection.setUsername("polaris");
connection.setPassword("polaris");
connection.setPort(3306);
String schemaName = "information_schema";
String tableName = "FILES";
String columnNamePattern = "TABLE";
schemaName = "sample";
tableName = "sales";
columnNamePattern = "";
PageRequest pageRequest = new PageRequest(0, 20);
Map<String, Object> columnMaps = jdbcConnectionService.getTableColumns(connection, schemaName, tableName, columnNamePattern, pageRequest);
List<Map> columnList = (List) columnMaps.get("columns");
Map<String, Object> pageInfo = (Map) columnMaps.get("page");
System.out.println("pageInfo = " + pageInfo);
for(Map<String, Object> columnMap : columnList){
System.out.println(columnMap);
}
columnMaps = jdbcConnectionService.getTableColumns(connection, null, tableName, columnNamePattern, pageRequest);
columnList = (List) columnMaps.get("columns");
pageInfo = (Map) columnMaps.get("page");
System.out.println("pageInfo = " + pageInfo);
for(Map<String, Object> columnMap : columnList){
System.out.println(columnMap);
}
}
@Test
public void createCSVMySQL() throws IOException{
DataConnection dataConnection = new DataConnection("MYSQL");
dataConnection.setHostname("localhost");
//dataConnection.setDatabase("sample");
dataConnection.setUsername("polaris");
dataConnection.setPassword("polaris");
dataConnection.setPort(3306);
String query = "select * from sales limit 5";
String csvFilePath = "/tmp/temp_csv001.csv";
Connection connection = DataConnectionHelper.getAccessor(dataConnection).getConnection();
JdbcCSVWriter jdbcCSVWriter = new JdbcCSVWriter(new FileWriter(csvFilePath), CsvPreference.STANDARD_PREFERENCE);
jdbcCSVWriter.setConnection(connection);
jdbcCSVWriter.setQuery(query);
jdbcCSVWriter.setFileName(csvFilePath);
jdbcCSVWriter.write();
CSVReader reader = new CSVReader(new FileReader(csvFilePath));
String[] line;
while ((line = reader.readNext()) != null) {
for(String text : line){
System.out.print(text);
}
System.out.println("");
}
}
@Test
public void changeDatabase() {
DataConnection connection = new DataConnection("MYSQL");
connection.setHostname("localhost");
connection.setUsername("polaris");
connection.setPassword("polaris");
connection.setPort(3306);
JdbcDialect dialect = DataConnectionHelper.lookupDialect(connection);
String webSocketId = "test1";
String database1 = "metatron";
String database2 = "sample";
// DataSource dataSource = WorkbenchDataSourceManager.createDataSourceInfo(connection, webSocketId, true).
// getSingleConnectionDataSource();
//
// JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
//
// jdbcConnectionService.changeDatabase(connection, database1, dataSource);
//
// List<Map<String, Object>> tables1 = jdbcTemplate.queryForList(dialect.getTableNameQuery(connection, null, null));
//
// jdbcConnectionService.changeDatabase(connection, database2, dataSource);
//
// List<Map<String, Object>> tables2 = jdbcTemplate.queryForList(dialect.getTableNameQuery(connection, null, null));
//
// System.out.println(tables1);
// System.out.println(tables2);
}
@Test
public void check() {
System.out.println(jdbcConnectionService.checkConnection(getMySQLConnection()));
}
@Test
public void checkTimeout() {
DataConnection connection = new DataConnection("MYSQL");
connection.setHostname("255.255.255.0");
connection.setUsername("polaris");
connection.setPassword("polaris");
connection.setPort(3306);
System.out.println(jdbcConnectionService.checkConnection(connection));
}
public DataConnection getMySQLConnection(){
DataConnection connection = new DataConnection();
connection.setHostname("localhost");
connection.setUsername("polaris");
connection.setPassword("polaris");
connection.setPort(3306);
connection.setImplementor("MYSQL");
return connection;
}
}
| apache-2.0 |
acartapanis/aries | blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint/spring/BlueprintNamespaceHandler.java | 10363 | /**
* 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.aries.blueprint.spring;
import java.net.URL;
import java.util.Collections;
import java.util.Properties;
import java.util.Set;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.NamespaceHandler2;
import org.apache.aries.blueprint.ParserContext;
import org.apache.aries.blueprint.PassThroughMetadata;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.apache.aries.blueprint.mutable.MutablePassThroughMetadata;
import org.apache.aries.blueprint.mutable.MutableRefMetadata;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.framework.Bundle;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.EmptyReaderEventListener;
import org.springframework.beans.factory.parsing.FailFastProblemReporter;
import org.springframework.beans.factory.parsing.NullSourceExtractor;
import org.springframework.beans.factory.parsing.ProblemReporter;
import org.springframework.beans.factory.parsing.ReaderEventListener;
import org.springframework.beans.factory.parsing.SourceExtractor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate;
import org.springframework.beans.factory.xml.NamespaceHandlerResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.beans.factory.xml.XmlReaderContext;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Blueprint NamespaceHandler wrapper for a spring NamespaceHandler
*/
public class BlueprintNamespaceHandler implements NamespaceHandler2 {
public static final String SPRING_CONTEXT_ID = "." + org.springframework.beans.factory.xml.ParserContext.class.getName();
public static final String SPRING_BEAN_PROCESSOR_ID = "." + SpringBeanProcessor.class.getName();
public static final String SPRING_APPLICATION_CONTEXT_ID = "." + ApplicationContext.class.getName();
public static final String SPRING_BEAN_FACTORY_ID = "." + BeanFactory.class.getName();
private final Bundle bundle;
private final Properties schemas;
private final org.springframework.beans.factory.xml.NamespaceHandler springHandler;
public BlueprintNamespaceHandler(Bundle bundle, Properties schemas, org.springframework.beans.factory.xml.NamespaceHandler springHandler) {
this.bundle = bundle;
this.schemas = schemas;
this.springHandler = springHandler;
springHandler.init();
}
public org.springframework.beans.factory.xml.NamespaceHandler getSpringHandler() {
return springHandler;
}
@Override
public boolean usePsvi() {
return true;
}
@Override
public URL getSchemaLocation(String s) {
if (schemas.containsKey(s)) {
return bundle.getResource(schemas.getProperty(s));
}
return null;
}
@Override
public Set<Class> getManagedClasses() {
return Collections.<Class>singleton(BeanDefinition.class);
}
@Override
public Metadata parse(Element element, ParserContext parserContext) {
try {
// Get the spring context
org.springframework.beans.factory.xml.ParserContext springContext
= getOrCreateParserContext(parserContext);
// Parse spring bean
springHandler.parse(element, springContext);
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public ComponentMetadata decorate(Node node, ComponentMetadata componentMetadata, ParserContext parserContext) {
return componentMetadata;
}
private org.springframework.beans.factory.xml.ParserContext getOrCreateParserContext(ParserContext parserContext) {
ComponentDefinitionRegistry registry = parserContext.getComponentDefinitionRegistry();
ExtendedBlueprintContainer container = getBlueprintContainer(parserContext);
// Create spring application context
SpringApplicationContext applicationContext = getPassThrough(parserContext,
SPRING_APPLICATION_CONTEXT_ID, SpringApplicationContext.class);
if (applicationContext == null) {
applicationContext = new SpringApplicationContext(container);
registry.registerComponentDefinition(createPassThrough(parserContext,
SPRING_APPLICATION_CONTEXT_ID, applicationContext
));
}
// Create registry
DefaultListableBeanFactory beanFactory = getPassThrough(parserContext,
SPRING_BEAN_FACTORY_ID, DefaultListableBeanFactory.class);
if (beanFactory == null) {
beanFactory = applicationContext.getBeanFactory();
registry.registerComponentDefinition(createPassThrough(parserContext,
SPRING_BEAN_FACTORY_ID, beanFactory
));
}
// Create spring parser context
org.springframework.beans.factory.xml.ParserContext springParserContext
= getPassThrough(parserContext, SPRING_CONTEXT_ID, org.springframework.beans.factory.xml.ParserContext.class);
if (springParserContext == null) {
// Create spring context
springParserContext = createSpringParserContext(parserContext, beanFactory);
registry.registerComponentDefinition(createPassThrough(parserContext,
SPRING_CONTEXT_ID, springParserContext
));
}
// Create processor
if (!parserContext.getComponentDefinitionRegistry().containsComponentDefinition(SPRING_BEAN_PROCESSOR_ID)) {
MutableBeanMetadata bm = parserContext.createMetadata(MutableBeanMetadata.class);
bm.setId(SPRING_BEAN_PROCESSOR_ID);
bm.setProcessor(true);
bm.setScope(BeanMetadata.SCOPE_SINGLETON);
bm.setRuntimeClass(SpringBeanProcessor.class);
bm.setActivation(BeanMetadata.ACTIVATION_EAGER);
bm.addArgument(createRef(parserContext, "blueprintBundleContext"), null, 0);
bm.addArgument(createRef(parserContext, "blueprintContainer"), null, 0);
bm.addArgument(createRef(parserContext, SPRING_APPLICATION_CONTEXT_ID), null, 0);
registry.registerComponentDefinition(bm);
}
// Add the namespace handler's bundle to the application context classloader
applicationContext.addSourceBundle(bundle);
return springParserContext;
}
private ComponentMetadata createPassThrough(ParserContext parserContext, String id, Object o) {
MutablePassThroughMetadata pt = parserContext.createMetadata(MutablePassThroughMetadata.class);
pt.setId(id);
pt.setObject(o);
return pt;
}
private Metadata createRef(ParserContext parserContext, String id) {
MutableRefMetadata ref = parserContext.createMetadata(MutableRefMetadata.class);
ref.setComponentId(id);
return ref;
}
private ExtendedBlueprintContainer getBlueprintContainer(ParserContext parserContext) {
ExtendedBlueprintContainer container = getPassThrough(parserContext, "blueprintContainer", ExtendedBlueprintContainer.class);
if (container == null) {
throw new IllegalStateException();
}
return container;
}
@SuppressWarnings("unchecked")
private <T> T getPassThrough(ParserContext parserContext, String name, Class<T> clazz) {
Metadata metadata = parserContext.getComponentDefinitionRegistry().getComponentDefinition(name);
if (metadata instanceof PassThroughMetadata) {
return (T) ((PassThroughMetadata) metadata).getObject();
} else {
return null;
}
}
private org.springframework.beans.factory.xml.ParserContext createSpringParserContext(ParserContext parserContext, DefaultListableBeanFactory registry) {
try {
XmlBeanDefinitionReader xbdr = new XmlBeanDefinitionReader(registry);
Resource resource = new UrlResource(parserContext.getSourceNode().getOwnerDocument().getDocumentURI());
ProblemReporter problemReporter = new FailFastProblemReporter();
ReaderEventListener listener = new EmptyReaderEventListener();
SourceExtractor extractor = new NullSourceExtractor();
NamespaceHandlerResolver resolver = new SpringNamespaceHandlerResolver(parserContext);
xbdr.setProblemReporter(problemReporter);
xbdr.setEventListener(listener);
xbdr.setSourceExtractor(extractor);
xbdr.setNamespaceHandlerResolver(resolver);
XmlReaderContext xmlReaderContext = xbdr.createReaderContext(resource);
BeanDefinitionParserDelegate bdpd = new BeanDefinitionParserDelegate(xmlReaderContext);
return new org.springframework.beans.factory.xml.ParserContext(xmlReaderContext, bdpd);
} catch (Exception e) {
throw new RuntimeException("Error creating spring parser context", e);
}
}
}
| apache-2.0 |
MayerTh/RVRPSimulator | vrpsim-vrprep-util-impl/src/main/java/vrpsim/vrprep/util/impl/util/VRPREPInstanceProviderUtil.java | 3400 | /**
* Copyright © 2016 Thomas Mayer (thomas.mayer@unibw.de)
*
* 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 vrpsim.vrprep.util.impl.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class VRPREPInstanceProviderUtil {
private static Logger logger = LoggerFactory.getLogger(VRPREPInstanceProviderUtil.class);
/**
* Returns a list of internal paths of files representing a VRP instances by
* the given folder. Note, plase
*
* @param folder
* @return
* @throws IOException
*/
public List<Path> getAvailablePathsToInstances(Path path) throws IOException {
List<Path> availableInstances = new ArrayList<>();
final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
if (jarFile.isFile()) {
final JarFile jar = new JarFile(jarFile);
final Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
Path pathInFile = Paths.get(entries.nextElement().getName());
if (pathInFile.startsWith(path) && pathInFile.getNameCount() - 1 == path.getNameCount()) {
availableInstances
.add(Paths.get(path.toString(), pathInFile.getName(path.getNameCount()).toString()));
}
}
jar.close();
} else {
InputStream is = VRPREPInstanceProviderUtil.class.getResourceAsStream("/" + path.toString());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String name = "";
while ((name = br.readLine()) != null) {
availableInstances.add(Paths.get(path.toString(), name));
}
}
return availableInstances;
}
/**
* Return the given instance as file.
*
* @param path
* @return
* @throws IOException
* @throws URISyntaxException
*/
public File loadInstance(Path path) throws IOException, URISyntaxException {
String pathStr = "/";
for (int i = 0; i < path.getNameCount(); i++) {
pathStr += path.getName(i);
if (i < path.getNameCount() - 1) {
pathStr += "/";
}
}
BufferedReader br = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream(pathStr)));
File file = new File("tmp_instance");
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
String line = "";
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
bw.close();
logger.debug("File {} loaded from given path={}, transformed path={}", file.toString(), path.toString(), pathStr);
return file;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-chimesdkmessaging/src/main/java/com/amazonaws/services/chimesdkmessaging/model/DescribeChannelMembershipRequest.java | 6827 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.chimesdkmessaging.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/chime-sdk-messaging-2021-05-15/DescribeChannelMembership"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeChannelMembershipRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The ARN of the channel.
* </p>
*/
private String channelArn;
/**
* <p>
* The <code>AppInstanceUserArn</code> of the member.
* </p>
*/
private String memberArn;
/**
* <p>
* The <code>AppInstanceUserArn</code> of the user that makes the API call.
* </p>
*/
private String chimeBearer;
/**
* <p>
* The ARN of the channel.
* </p>
*
* @param channelArn
* The ARN of the channel.
*/
public void setChannelArn(String channelArn) {
this.channelArn = channelArn;
}
/**
* <p>
* The ARN of the channel.
* </p>
*
* @return The ARN of the channel.
*/
public String getChannelArn() {
return this.channelArn;
}
/**
* <p>
* The ARN of the channel.
* </p>
*
* @param channelArn
* The ARN of the channel.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeChannelMembershipRequest withChannelArn(String channelArn) {
setChannelArn(channelArn);
return this;
}
/**
* <p>
* The <code>AppInstanceUserArn</code> of the member.
* </p>
*
* @param memberArn
* The <code>AppInstanceUserArn</code> of the member.
*/
public void setMemberArn(String memberArn) {
this.memberArn = memberArn;
}
/**
* <p>
* The <code>AppInstanceUserArn</code> of the member.
* </p>
*
* @return The <code>AppInstanceUserArn</code> of the member.
*/
public String getMemberArn() {
return this.memberArn;
}
/**
* <p>
* The <code>AppInstanceUserArn</code> of the member.
* </p>
*
* @param memberArn
* The <code>AppInstanceUserArn</code> of the member.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeChannelMembershipRequest withMemberArn(String memberArn) {
setMemberArn(memberArn);
return this;
}
/**
* <p>
* The <code>AppInstanceUserArn</code> of the user that makes the API call.
* </p>
*
* @param chimeBearer
* The <code>AppInstanceUserArn</code> of the user that makes the API call.
*/
public void setChimeBearer(String chimeBearer) {
this.chimeBearer = chimeBearer;
}
/**
* <p>
* The <code>AppInstanceUserArn</code> of the user that makes the API call.
* </p>
*
* @return The <code>AppInstanceUserArn</code> of the user that makes the API call.
*/
public String getChimeBearer() {
return this.chimeBearer;
}
/**
* <p>
* The <code>AppInstanceUserArn</code> of the user that makes the API call.
* </p>
*
* @param chimeBearer
* The <code>AppInstanceUserArn</code> of the user that makes the API call.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeChannelMembershipRequest withChimeBearer(String chimeBearer) {
setChimeBearer(chimeBearer);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getChannelArn() != null)
sb.append("ChannelArn: ").append(getChannelArn()).append(",");
if (getMemberArn() != null)
sb.append("MemberArn: ").append(getMemberArn()).append(",");
if (getChimeBearer() != null)
sb.append("ChimeBearer: ").append(getChimeBearer());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeChannelMembershipRequest == false)
return false;
DescribeChannelMembershipRequest other = (DescribeChannelMembershipRequest) obj;
if (other.getChannelArn() == null ^ this.getChannelArn() == null)
return false;
if (other.getChannelArn() != null && other.getChannelArn().equals(this.getChannelArn()) == false)
return false;
if (other.getMemberArn() == null ^ this.getMemberArn() == null)
return false;
if (other.getMemberArn() != null && other.getMemberArn().equals(this.getMemberArn()) == false)
return false;
if (other.getChimeBearer() == null ^ this.getChimeBearer() == null)
return false;
if (other.getChimeBearer() != null && other.getChimeBearer().equals(this.getChimeBearer()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getChannelArn() == null) ? 0 : getChannelArn().hashCode());
hashCode = prime * hashCode + ((getMemberArn() == null) ? 0 : getMemberArn().hashCode());
hashCode = prime * hashCode + ((getChimeBearer() == null) ? 0 : getChimeBearer().hashCode());
return hashCode;
}
@Override
public DescribeChannelMembershipRequest clone() {
return (DescribeChannelMembershipRequest) super.clone();
}
}
| apache-2.0 |
CLovinr/OftenPorter | Porter-Demo/src/main/java/cn/oftenporter/demo/servlet/demo1/lporter/LHelloPorter.java | 223 | package cn.oftenporter.demo.servlet.demo1.lporter;
import cn.oftenporter.porter.core.annotation.PortIn;
@PortIn
public class LHelloPorter
{
@PortIn
public Object say()
{
return "Local Hello World!";
}
}
| apache-2.0 |
pennatula/Utilities | src/swissarmyknife/VennMaker.java | 3000 | /**
*
*/
package swissarmyknife;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* @author anwesha
*
*/
public class VennMaker {
/**
* @param args
*/
public static void main(String[] args) {
File uniprotFile = new File(args[0]);
File wpFile = new File(args[1]);
File rFile = new File(args[2]);
Set<String> Uni = new HashSet<String>();
Set<String> WP = new HashSet<String>();
Set<String> WP_h = new HashSet<String>();
Set<String> Re = new HashSet<String>();
Set<String> Re_h = new HashSet<String>();
Set<String> onlyWP = new HashSet<String>();
Set<String> onlyRe = new HashSet<String>();
Set<String> WPnRe = new HashSet<String>();
/*
* Read ids
*/
try (BufferedReader br = new BufferedReader(new FileReader(uniprotFile))) {
String line;
while ((line = br.readLine()) != null) {
Uni.add(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try (BufferedReader br = new BufferedReader(new FileReader(wpFile))) {
String line;
while ((line = br.readLine()) != null) {
WP.add(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try (BufferedReader br = new BufferedReader(new FileReader(rFile))) {
String line;
while ((line = br.readLine()) != null) {
Re.add(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* Calculate
*/
if (Uni.containsAll(WP)) {
// do something if needs be
}
if (Uni.containsAll(Re)) {
// do something if needs be
}
/*
* Only
*/
Set<String> one = WP;
Set<String> two = Re;
one.removeAll(Re);
two.removeAll(WP);
// Iterator<String> itWP = WP.iterator();
// while(itWP.hasNext()) {
// if(Uni.contains(itWP.next())){
// WP_h.add(itWP.next());
// }
// }
//
// Iterator<String> itRe = Re.iterator();
// while(itRe.hasNext()) {
// if(Uni.contains(itRe.next())){
// Re_h.add(itRe.next());
// }
// }
// if(WP_h.contains(itRe.next())){
// WPnRe.add(itRe.next());
// }else{
// onlyRe.add(itRe.next());
// }
// Iterator<String> itWPonly = WP.iterator();
// while(itWPonly.hasNext()) {
// if(Re_h.contains(itWPonly.next())){
// }else{
// if(!itWPonly.next().isEmpty())
// onlyWP.add(itWPonly.next());
// }
// }
System.out.println("All human proteins = "+Uni.size());
System.out.println("All WP proteins = "+WP.size());
System.out.println("All Re proteins = "+Re.size());
System.out.println("Proteins in both WP and R = "+WPnRe.size());
System.out.println("Proteins only in WP = "+one.size());
System.out.println("Proteins only in Re = "+two.size());
}
}
| apache-2.0 |
askmon/ListaExercicio | Testes/br/usp/ime/academicdevoir/controller/DisciplinasControllerTeste.java | 2880 | package br.usp.ime.academicdevoir.controller;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import br.com.caelum.vraptor.util.test.MockResult;
import br.usp.ime.academicdevoir.dao.DisciplinaDao;
import br.usp.ime.academicdevoir.entidade.Disciplina;
import br.usp.ime.academicdevoir.entidade.Professor;
import br.usp.ime.academicdevoir.infra.Privilegio;
import br.usp.ime.academicdevoir.infra.UsuarioSession;
public class DisciplinasControllerTeste {
/**
* @uml.property name="disciplinasController"
* @uml.associationEnd
*/
private DisciplinasController disciplinasController;
/**
* @uml.property name="result"
* @uml.associationEnd
*/
private MockResult result;
/**
* @uml.property name="dao"
* @uml.associationEnd
*/
private DisciplinaDao dao;
/**
* @uml.property name="disciplina"
* @uml.associationEnd
*/
private Disciplina disciplina;
/**
* @uml.property name="disciplinas"
*/
private List<Disciplina> disciplinas;
/**
* @uml.property name="usuarioSession"
* @uml.associationEnd readOnly="true"
*/
private UsuarioSession usuarioSession;
@Before
public void SetUp() {
Professor professor = new Professor();
professor.setId(0L);
professor.setPrivilegio(Privilegio.ADMINISTRADOR);
usuarioSession = new UsuarioSession();
usuarioSession.setUsuario(professor);
dao = mock(DisciplinaDao.class);
result = spy(new MockResult());
disciplinasController = new DisciplinasController(result, dao,
usuarioSession);
disciplina = new Disciplina();
disciplina.setId(0L);
disciplinas = new ArrayList<Disciplina>();
when(dao.carrega(disciplina.getId())).thenReturn(disciplina);
when(dao.listaTudo()).thenReturn(disciplinas);
}
@Test
public void testeLista() {
disciplinasController.lista();
List<Disciplina> disciplinas = result.included("lista");
assertNotNull(disciplinas);
}
@Test
public void testeCadastra() {
disciplinasController.cadastra(disciplina);
verify(dao).salvaDisciplina(disciplina);
verify(result).redirectTo(DisciplinasController.class);
}
@Test
public void testeAltera() {
disciplinasController.altera(disciplina.getId(), "xpto");
verify(dao).atualiza(disciplina);
verify(result).redirectTo(DisciplinasController.class);
}
@Test
public void testeAlteracao() {
disciplinasController.alteracao(this.disciplina.getId());
Disciplina disciplina = result.included("disciplina");
assertNotNull(disciplina);
}
public void testaRemove() {
disciplinasController.remove(disciplina.getId());
verify(dao).remove(disciplina);
verify(result).redirectTo(DisciplinasController.class);
}
}
| apache-2.0 |
520github/enjoy-love | src/test/java/com/enjoy/love/common/encrypt/ShiroEncryptHelperTest.java | 723 | package com.enjoy.love.common.encrypt;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.enjoy.love.BaseSpringBootTest;
public class ShiroEncryptHelperTest extends BaseSpringBootTest {
@Autowired
private ShiroEncryptHelper shiroEncryptHelper;
@Test
public void encryptPwdTest() {
String password = "123qwe";
String salt = "17090137197" + "1A9AF39B50D44286A0D40C14AFDF1456";
String result = shiroEncryptHelper.encryptPwd(password, salt);
this.print("result {}, AlgorithmName {}, HashIterations {}, Encode {}",
result, shiroEncryptHelper.getAlgorithmName(), shiroEncryptHelper.getHashIterations(), shiroEncryptHelper.getEncode());
}
}
| apache-2.0 |
yan74/afplib | org.afplib/src/main/java/org/afplib/afplib/MediaFidelityStpMedEx.java | 5264 | /**
*/
package org.afplib.afplib;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Media Fidelity Stp Med Ex</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see org.afplib.afplib.AfplibPackage#getMediaFidelityStpMedEx()
* @model
* @generated
*/
public enum MediaFidelityStpMedEx implements Enumerator {
/**
* The '<em><b>Const Terminate And Hold</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #CONST_TERMINATE_AND_HOLD_VALUE
* @generated
* @ordered
*/
CONST_TERMINATE_AND_HOLD(1, "ConstTerminateAndHold", "ConstTerminateAndHold"),
/**
* The '<em><b>Const Continue</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #CONST_CONTINUE_VALUE
* @generated
* @ordered
*/
CONST_CONTINUE(2, "ConstContinue", "ConstContinue");
/**
* The '<em><b>Const Terminate And Hold</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Const Terminate And Hold</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #CONST_TERMINATE_AND_HOLD
* @model name="ConstTerminateAndHold"
* @generated
* @ordered
*/
public static final int CONST_TERMINATE_AND_HOLD_VALUE = 1;
/**
* The '<em><b>Const Continue</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Const Continue</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #CONST_CONTINUE
* @model name="ConstContinue"
* @generated
* @ordered
*/
public static final int CONST_CONTINUE_VALUE = 2;
/**
* An array of all the '<em><b>Media Fidelity Stp Med Ex</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final MediaFidelityStpMedEx[] VALUES_ARRAY =
new MediaFidelityStpMedEx[] {
CONST_TERMINATE_AND_HOLD,
CONST_CONTINUE,
};
/**
* A public read-only list of all the '<em><b>Media Fidelity Stp Med Ex</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<MediaFidelityStpMedEx> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Media Fidelity Stp Med Ex</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static MediaFidelityStpMedEx get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
MediaFidelityStpMedEx result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Media Fidelity Stp Med Ex</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static MediaFidelityStpMedEx getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
MediaFidelityStpMedEx result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Media Fidelity Stp Med Ex</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static MediaFidelityStpMedEx get(int value) {
switch (value) {
case CONST_TERMINATE_AND_HOLD_VALUE: return CONST_TERMINATE_AND_HOLD;
case CONST_CONTINUE_VALUE: return CONST_CONTINUE;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private MediaFidelityStpMedEx(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //MediaFidelityStpMedEx
| apache-2.0 |
OpenNTF/SmartNSF | designer/org.openntf.xrest.designer/src/org/openntf/xrest/designer/codeassist/ProposalParameter.java | 1241 | package org.openntf.xrest.designer.codeassist;
import java.util.List;
import org.codehaus.groovy.ast.ASTNode;
import org.eclipse.jface.resource.ImageRegistry;
import org.openntf.xrest.designer.dsl.DSLRegistry;
public class ProposalParameter<T extends ASTNode> {
private T node;
private List<ASTNode> hierarchie;
private DSLRegistry registry;
private ImageRegistry imageRegistry;
private CodeContext codeContext;
public ProposalParameter<T> add(T node) {
this.node = node;
return this;
}
public ProposalParameter<T> add(List<ASTNode> hierarchie) {
this.hierarchie = hierarchie;
return this;
}
public ProposalParameter<T> add(DSLRegistry registry) {
this.registry = registry;
return this;
}
public ProposalParameter<T> add(ImageRegistry registry) {
this.imageRegistry = registry;
return this;
}
public ProposalParameter<T> add(CodeContext context) {
this.codeContext = context;
return this;
}
public T getNode() {
return node;
}
public List<ASTNode> getHierarchie() {
return hierarchie;
}
public DSLRegistry getRegistry() {
return registry;
}
public ImageRegistry getImageRegistry() {
return imageRegistry;
}
public CodeContext getCodeContext() {
return codeContext;
}
}
| apache-2.0 |
nita22/OpenTheDoor | customview/src/main/java/com/jiazi/customview/ClearEditText.java | 4135 | package com.jiazi.customview;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import com.jiazi.customview.R;
public class ClearEditText extends EditText implements OnFocusChangeListener, TextWatcher {
/**
* 删除按钮的引用
*/
private Drawable mClearDrawable;
/**
* 控件是否有焦点
*/
private boolean hasFoucs = false;
public ClearEditText(Context context) {
this(context, null);
}
public ClearEditText(Context context, AttributeSet attrs) {
// 这里构造方法也很重要,不加这个很多属性不能再XML里面定义
this(context, attrs, android.R.attr.editTextStyle);
}
public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
// 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
mClearDrawable = getCompoundDrawables()[2];
if (mClearDrawable == null) {
// throw new
// NullPointerException("You can add drawableRight attribute in XML");
mClearDrawable = getResources().getDrawable(R.drawable.btn_clear_selector);
}
mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight());
// 默认设置隐藏图标
setClearIconVisible(false);
// 设置焦点改变的监听
setOnFocusChangeListener(this);
// 设置输入框里面内容发生改变的监听
addTextChangedListener(this);
}
/**
* 因为我们不能直接给EditText设置点击事件,所以我们用记住我们按下的位置来模拟点击事件 当我们按下的位置 在 EditText的宽度 -
* 图标到控件右边的间距 - 图标的宽度 和 EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标,竖直方向就没有考虑
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (getCompoundDrawables()[2] != null) {
boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
&& (event.getX() < ((getWidth() - getPaddingRight())));
if (touchable) {
this.setText("");
}
}
}
return super.onTouchEvent(event);
}
/**
* 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏
*/
@Override
public void onFocusChange(View v, boolean hasFocus) {
this.hasFoucs = hasFocus;
if (hasFocus) {
setClearIconVisible(getText().length() > 0);
} else {
setClearIconVisible(false);
}
}
/**
* 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去
*
* @param visible
*/
protected void setClearIconVisible(boolean visible) {
Drawable right = visible ? mClearDrawable : null;
setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
}
/**
* 当输入框里面内容发生变化的时候回调的方法
*/
@Override
public void onTextChanged(CharSequence s, int start, int count, int after) {
if (hasFoucs) {
setClearIconVisible(s.length() > 0);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
/**
* 设置晃动动画
*/
public void setShakeAnimation() {
this.setAnimation(shakeAnimation(5));
}
/**
* 晃动动画
*
* @param counts
* 1秒钟晃动多少下
* @return
*/
public static Animation shakeAnimation(int counts) {
Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
translateAnimation.setInterpolator(new CycleInterpolator(counts));
translateAnimation.setDuration(1000);
return translateAnimation;
}
}
| apache-2.0 |
dinar92/java_training | chapter_002/src/test/java/ru/job4j/profession/project/ProjectTest.java | 648 | package ru.job4j.profession.project;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**Testing class Project.*/
public class ProjectTest {
/**Testing implemented().*/
@Test
public void whenImplementedThenOutput() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
Project proj = new Project();
proj.implemented();
assertThat(out.toString(), is("Проект реализован успешно! Теперь можно просить прибавку!\n"));
}
}
| apache-2.0 |
denniskniep/zap-extensions | addOns/oast/src/main/java/org/zaproxy/addon/oast/services/callback/CallbackProxyListener.java | 4081 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2021 The ZAP Development Team
*
* 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.zaproxy.addon.oast.services.callback;
import java.util.Objects;
import org.apache.commons.httpclient.URIException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.db.DatabaseException;
import org.parosproxy.paros.network.HttpHeader;
import org.parosproxy.paros.network.HttpMalformedHeaderException;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpStatusCode;
import org.zaproxy.addon.network.server.HttpMessageHandler;
import org.zaproxy.addon.network.server.HttpMessageHandlerContext;
import org.zaproxy.addon.oast.OastRequest;
import org.zaproxy.zap.utils.ThreadUtils;
class CallbackProxyListener implements HttpMessageHandler {
private static final Logger LOGGER = LogManager.getLogger(CallbackProxyListener.class);
private static final String RESPONSE_HEADER =
HttpHeader.HTTP11
+ " "
+ HttpStatusCode.OK
+ "\r\nContent-Length: 0\r\nConnection: close";
private final CallbackService callbackService;
private final OastRequestFactory oastRequestFactory;
public CallbackProxyListener(
CallbackService callbackService, OastRequestFactory oastRequestFactory) {
this.callbackService = Objects.requireNonNull(callbackService);
this.oastRequestFactory = Objects.requireNonNull(oastRequestFactory);
}
@Override
public void handleMessage(HttpMessageHandlerContext ctx, HttpMessage msg) {
if (!ctx.isFromClient()) {
return;
}
ctx.overridden();
try {
msg.setTimeSentMillis(System.currentTimeMillis());
String path = msg.getRequestHeader().getURI().getPath();
LOGGER.debug(
"Callback received for URL : {} path : {} from {}",
msg.getRequestHeader().getURI(),
path,
msg.getRequestHeader().getSenderAddress());
msg.setResponseHeader(RESPONSE_HEADER);
String uuid = path.substring(1);
String handler = callbackService.getHandlers().get(uuid);
if (handler != null) {
callbackReceived(handler, msg);
} else {
callbackReceived(
Constant.messages.getString("oast.callback.handler.none.name"), msg);
}
} catch (URIException | HttpMalformedHeaderException e) {
LOGGER.error(e.getMessage(), e);
}
}
private void callbackReceived(String handler, HttpMessage httpMessage) {
ThreadUtils.invokeAndWaitHandled(() -> callbackReceivedHandler(handler, httpMessage));
}
private void callbackReceivedHandler(String handler, HttpMessage httpMessage) {
try {
OastRequest request =
oastRequestFactory.create(
httpMessage,
httpMessage.getRequestHeader().getSenderAddress().getHostAddress(),
handler);
callbackService.handleOastRequest(request);
} catch (HttpMalformedHeaderException | DatabaseException e) {
LOGGER.warn("Failed to persist received callback:", e);
}
}
}
| apache-2.0 |
k-a-z-u/DragTag | src/li/kazu/java/dragtag/view/listeners/ControlActionListener.java | 394 | package li.kazu.java.dragtag.view.listeners;
public interface ControlActionListener {
/** gui: button "save" has been pressed */
public void onSave();
/** gui: button "move" has been pressed */
public void onMove();
/** gui: button "close file" has been pressed */
public void onCloseFile();
/** gui: button "exit" has been pressed */
public void onExit();
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-securityhub/src/main/java/com/amazonaws/services/securityhub/model/AwsEcsTaskDefinitionProxyConfigurationProxyConfigurationPropertiesDetails.java | 5777 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.securityhub.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* A network configuration parameter to provide to the Container Network Interface (CNI) plugin.
* </p>
*
* @see <a
* href="http://docs.aws.amazon.com/goto/WebAPI/securityhub-2018-10-26/AwsEcsTaskDefinitionProxyConfigurationProxyConfigurationPropertiesDetails"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AwsEcsTaskDefinitionProxyConfigurationProxyConfigurationPropertiesDetails implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The name of the property.
* </p>
*/
private String name;
/**
* <p>
* The value of the property.
* </p>
*/
private String value;
/**
* <p>
* The name of the property.
* </p>
*
* @param name
* The name of the property.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the property.
* </p>
*
* @return The name of the property.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the property.
* </p>
*
* @param name
* The name of the property.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AwsEcsTaskDefinitionProxyConfigurationProxyConfigurationPropertiesDetails withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The value of the property.
* </p>
*
* @param value
* The value of the property.
*/
public void setValue(String value) {
this.value = value;
}
/**
* <p>
* The value of the property.
* </p>
*
* @return The value of the property.
*/
public String getValue() {
return this.value;
}
/**
* <p>
* The value of the property.
* </p>
*
* @param value
* The value of the property.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AwsEcsTaskDefinitionProxyConfigurationProxyConfigurationPropertiesDetails withValue(String value) {
setValue(value);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getValue() != null)
sb.append("Value: ").append(getValue());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof AwsEcsTaskDefinitionProxyConfigurationProxyConfigurationPropertiesDetails == false)
return false;
AwsEcsTaskDefinitionProxyConfigurationProxyConfigurationPropertiesDetails other = (AwsEcsTaskDefinitionProxyConfigurationProxyConfigurationPropertiesDetails) obj;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getValue() == null ^ this.getValue() == null)
return false;
if (other.getValue() != null && other.getValue().equals(this.getValue()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getValue() == null) ? 0 : getValue().hashCode());
return hashCode;
}
@Override
public AwsEcsTaskDefinitionProxyConfigurationProxyConfigurationPropertiesDetails clone() {
try {
return (AwsEcsTaskDefinitionProxyConfigurationProxyConfigurationPropertiesDetails) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.securityhub.model.transform.AwsEcsTaskDefinitionProxyConfigurationProxyConfigurationPropertiesDetailsMarshaller.getInstance()
.marshall(this, protocolMarshaller);
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-location/src/main/java/com/amazonaws/services/location/model/UpdateTrackerRequest.java | 26652 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.location.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/location-2020-11-19/UpdateTracker" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateTrackerRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* Updates the description for the tracker resource.
* </p>
*/
private String description;
/**
* <p>
* Updates the position filtering for the tracker resource.
* </p>
* <p>
* Valid values:
* </p>
* <ul>
* <li>
* <p>
* <code>TimeBased</code> - Location updates are evaluated against linked geofence collections, but not every
* location update is stored. If your update frequency is more often than 30 seconds, only one update per 30 seconds
* is stored for each unique device ID.
* </p>
* </li>
* <li>
* <p>
* <code>DistanceBased</code> - If the device has moved less than 30 m (98.4 ft), location updates are ignored.
* Location updates within this distance are neither evaluated against linked geofence collections, nor stored. This
* helps control costs by reducing the number of geofence evaluations and historical device positions to paginate
* through. Distance-based filtering can also reduce the effects of GPS noise when displaying device trajectories on
* a map.
* </p>
* </li>
* <li>
* <p>
* <code>AccuracyBased</code> - If the device has moved less than the measured accuracy, location updates are
* ignored. For example, if two consecutive updates from a device have a horizontal accuracy of 5 m and 10 m, the
* second update is ignored if the device has moved less than 15 m. Ignored location updates are neither evaluated
* against linked geofence collections, nor stored. This helps educe the effects of GPS noise when displaying device
* trajectories on a map, and can help control costs by reducing the number of geofence evaluations.
* </p>
* </li>
* </ul>
*/
private String positionFiltering;
/**
* <p>
* No longer used. If included, the only allowed value is <code>RequestBasedUsage</code>.
* </p>
*/
@Deprecated
private String pricingPlan;
/**
* <p>
* This parameter is no longer used.
* </p>
*/
@Deprecated
private String pricingPlanDataSource;
/**
* <p>
* The name of the tracker resource to update.
* </p>
*/
private String trackerName;
/**
* <p>
* Updates the description for the tracker resource.
* </p>
*
* @param description
* Updates the description for the tracker resource.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* Updates the description for the tracker resource.
* </p>
*
* @return Updates the description for the tracker resource.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* Updates the description for the tracker resource.
* </p>
*
* @param description
* Updates the description for the tracker resource.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateTrackerRequest withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* Updates the position filtering for the tracker resource.
* </p>
* <p>
* Valid values:
* </p>
* <ul>
* <li>
* <p>
* <code>TimeBased</code> - Location updates are evaluated against linked geofence collections, but not every
* location update is stored. If your update frequency is more often than 30 seconds, only one update per 30 seconds
* is stored for each unique device ID.
* </p>
* </li>
* <li>
* <p>
* <code>DistanceBased</code> - If the device has moved less than 30 m (98.4 ft), location updates are ignored.
* Location updates within this distance are neither evaluated against linked geofence collections, nor stored. This
* helps control costs by reducing the number of geofence evaluations and historical device positions to paginate
* through. Distance-based filtering can also reduce the effects of GPS noise when displaying device trajectories on
* a map.
* </p>
* </li>
* <li>
* <p>
* <code>AccuracyBased</code> - If the device has moved less than the measured accuracy, location updates are
* ignored. For example, if two consecutive updates from a device have a horizontal accuracy of 5 m and 10 m, the
* second update is ignored if the device has moved less than 15 m. Ignored location updates are neither evaluated
* against linked geofence collections, nor stored. This helps educe the effects of GPS noise when displaying device
* trajectories on a map, and can help control costs by reducing the number of geofence evaluations.
* </p>
* </li>
* </ul>
*
* @param positionFiltering
* Updates the position filtering for the tracker resource.</p>
* <p>
* Valid values:
* </p>
* <ul>
* <li>
* <p>
* <code>TimeBased</code> - Location updates are evaluated against linked geofence collections, but not every
* location update is stored. If your update frequency is more often than 30 seconds, only one update per 30
* seconds is stored for each unique device ID.
* </p>
* </li>
* <li>
* <p>
* <code>DistanceBased</code> - If the device has moved less than 30 m (98.4 ft), location updates are
* ignored. Location updates within this distance are neither evaluated against linked geofence collections,
* nor stored. This helps control costs by reducing the number of geofence evaluations and historical device
* positions to paginate through. Distance-based filtering can also reduce the effects of GPS noise when
* displaying device trajectories on a map.
* </p>
* </li>
* <li>
* <p>
* <code>AccuracyBased</code> - If the device has moved less than the measured accuracy, location updates are
* ignored. For example, if two consecutive updates from a device have a horizontal accuracy of 5 m and 10 m,
* the second update is ignored if the device has moved less than 15 m. Ignored location updates are neither
* evaluated against linked geofence collections, nor stored. This helps educe the effects of GPS noise when
* displaying device trajectories on a map, and can help control costs by reducing the number of geofence
* evaluations.
* </p>
* </li>
* @see PositionFiltering
*/
public void setPositionFiltering(String positionFiltering) {
this.positionFiltering = positionFiltering;
}
/**
* <p>
* Updates the position filtering for the tracker resource.
* </p>
* <p>
* Valid values:
* </p>
* <ul>
* <li>
* <p>
* <code>TimeBased</code> - Location updates are evaluated against linked geofence collections, but not every
* location update is stored. If your update frequency is more often than 30 seconds, only one update per 30 seconds
* is stored for each unique device ID.
* </p>
* </li>
* <li>
* <p>
* <code>DistanceBased</code> - If the device has moved less than 30 m (98.4 ft), location updates are ignored.
* Location updates within this distance are neither evaluated against linked geofence collections, nor stored. This
* helps control costs by reducing the number of geofence evaluations and historical device positions to paginate
* through. Distance-based filtering can also reduce the effects of GPS noise when displaying device trajectories on
* a map.
* </p>
* </li>
* <li>
* <p>
* <code>AccuracyBased</code> - If the device has moved less than the measured accuracy, location updates are
* ignored. For example, if two consecutive updates from a device have a horizontal accuracy of 5 m and 10 m, the
* second update is ignored if the device has moved less than 15 m. Ignored location updates are neither evaluated
* against linked geofence collections, nor stored. This helps educe the effects of GPS noise when displaying device
* trajectories on a map, and can help control costs by reducing the number of geofence evaluations.
* </p>
* </li>
* </ul>
*
* @return Updates the position filtering for the tracker resource.</p>
* <p>
* Valid values:
* </p>
* <ul>
* <li>
* <p>
* <code>TimeBased</code> - Location updates are evaluated against linked geofence collections, but not
* every location update is stored. If your update frequency is more often than 30 seconds, only one update
* per 30 seconds is stored for each unique device ID.
* </p>
* </li>
* <li>
* <p>
* <code>DistanceBased</code> - If the device has moved less than 30 m (98.4 ft), location updates are
* ignored. Location updates within this distance are neither evaluated against linked geofence collections,
* nor stored. This helps control costs by reducing the number of geofence evaluations and historical device
* positions to paginate through. Distance-based filtering can also reduce the effects of GPS noise when
* displaying device trajectories on a map.
* </p>
* </li>
* <li>
* <p>
* <code>AccuracyBased</code> - If the device has moved less than the measured accuracy, location updates
* are ignored. For example, if two consecutive updates from a device have a horizontal accuracy of 5 m and
* 10 m, the second update is ignored if the device has moved less than 15 m. Ignored location updates are
* neither evaluated against linked geofence collections, nor stored. This helps educe the effects of GPS
* noise when displaying device trajectories on a map, and can help control costs by reducing the number of
* geofence evaluations.
* </p>
* </li>
* @see PositionFiltering
*/
public String getPositionFiltering() {
return this.positionFiltering;
}
/**
* <p>
* Updates the position filtering for the tracker resource.
* </p>
* <p>
* Valid values:
* </p>
* <ul>
* <li>
* <p>
* <code>TimeBased</code> - Location updates are evaluated against linked geofence collections, but not every
* location update is stored. If your update frequency is more often than 30 seconds, only one update per 30 seconds
* is stored for each unique device ID.
* </p>
* </li>
* <li>
* <p>
* <code>DistanceBased</code> - If the device has moved less than 30 m (98.4 ft), location updates are ignored.
* Location updates within this distance are neither evaluated against linked geofence collections, nor stored. This
* helps control costs by reducing the number of geofence evaluations and historical device positions to paginate
* through. Distance-based filtering can also reduce the effects of GPS noise when displaying device trajectories on
* a map.
* </p>
* </li>
* <li>
* <p>
* <code>AccuracyBased</code> - If the device has moved less than the measured accuracy, location updates are
* ignored. For example, if two consecutive updates from a device have a horizontal accuracy of 5 m and 10 m, the
* second update is ignored if the device has moved less than 15 m. Ignored location updates are neither evaluated
* against linked geofence collections, nor stored. This helps educe the effects of GPS noise when displaying device
* trajectories on a map, and can help control costs by reducing the number of geofence evaluations.
* </p>
* </li>
* </ul>
*
* @param positionFiltering
* Updates the position filtering for the tracker resource.</p>
* <p>
* Valid values:
* </p>
* <ul>
* <li>
* <p>
* <code>TimeBased</code> - Location updates are evaluated against linked geofence collections, but not every
* location update is stored. If your update frequency is more often than 30 seconds, only one update per 30
* seconds is stored for each unique device ID.
* </p>
* </li>
* <li>
* <p>
* <code>DistanceBased</code> - If the device has moved less than 30 m (98.4 ft), location updates are
* ignored. Location updates within this distance are neither evaluated against linked geofence collections,
* nor stored. This helps control costs by reducing the number of geofence evaluations and historical device
* positions to paginate through. Distance-based filtering can also reduce the effects of GPS noise when
* displaying device trajectories on a map.
* </p>
* </li>
* <li>
* <p>
* <code>AccuracyBased</code> - If the device has moved less than the measured accuracy, location updates are
* ignored. For example, if two consecutive updates from a device have a horizontal accuracy of 5 m and 10 m,
* the second update is ignored if the device has moved less than 15 m. Ignored location updates are neither
* evaluated against linked geofence collections, nor stored. This helps educe the effects of GPS noise when
* displaying device trajectories on a map, and can help control costs by reducing the number of geofence
* evaluations.
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
* @see PositionFiltering
*/
public UpdateTrackerRequest withPositionFiltering(String positionFiltering) {
setPositionFiltering(positionFiltering);
return this;
}
/**
* <p>
* Updates the position filtering for the tracker resource.
* </p>
* <p>
* Valid values:
* </p>
* <ul>
* <li>
* <p>
* <code>TimeBased</code> - Location updates are evaluated against linked geofence collections, but not every
* location update is stored. If your update frequency is more often than 30 seconds, only one update per 30 seconds
* is stored for each unique device ID.
* </p>
* </li>
* <li>
* <p>
* <code>DistanceBased</code> - If the device has moved less than 30 m (98.4 ft), location updates are ignored.
* Location updates within this distance are neither evaluated against linked geofence collections, nor stored. This
* helps control costs by reducing the number of geofence evaluations and historical device positions to paginate
* through. Distance-based filtering can also reduce the effects of GPS noise when displaying device trajectories on
* a map.
* </p>
* </li>
* <li>
* <p>
* <code>AccuracyBased</code> - If the device has moved less than the measured accuracy, location updates are
* ignored. For example, if two consecutive updates from a device have a horizontal accuracy of 5 m and 10 m, the
* second update is ignored if the device has moved less than 15 m. Ignored location updates are neither evaluated
* against linked geofence collections, nor stored. This helps educe the effects of GPS noise when displaying device
* trajectories on a map, and can help control costs by reducing the number of geofence evaluations.
* </p>
* </li>
* </ul>
*
* @param positionFiltering
* Updates the position filtering for the tracker resource.</p>
* <p>
* Valid values:
* </p>
* <ul>
* <li>
* <p>
* <code>TimeBased</code> - Location updates are evaluated against linked geofence collections, but not every
* location update is stored. If your update frequency is more often than 30 seconds, only one update per 30
* seconds is stored for each unique device ID.
* </p>
* </li>
* <li>
* <p>
* <code>DistanceBased</code> - If the device has moved less than 30 m (98.4 ft), location updates are
* ignored. Location updates within this distance are neither evaluated against linked geofence collections,
* nor stored. This helps control costs by reducing the number of geofence evaluations and historical device
* positions to paginate through. Distance-based filtering can also reduce the effects of GPS noise when
* displaying device trajectories on a map.
* </p>
* </li>
* <li>
* <p>
* <code>AccuracyBased</code> - If the device has moved less than the measured accuracy, location updates are
* ignored. For example, if two consecutive updates from a device have a horizontal accuracy of 5 m and 10 m,
* the second update is ignored if the device has moved less than 15 m. Ignored location updates are neither
* evaluated against linked geofence collections, nor stored. This helps educe the effects of GPS noise when
* displaying device trajectories on a map, and can help control costs by reducing the number of geofence
* evaluations.
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
* @see PositionFiltering
*/
public UpdateTrackerRequest withPositionFiltering(PositionFiltering positionFiltering) {
this.positionFiltering = positionFiltering.toString();
return this;
}
/**
* <p>
* No longer used. If included, the only allowed value is <code>RequestBasedUsage</code>.
* </p>
*
* @param pricingPlan
* No longer used. If included, the only allowed value is <code>RequestBasedUsage</code>.
* @see PricingPlan
*/
@Deprecated
public void setPricingPlan(String pricingPlan) {
this.pricingPlan = pricingPlan;
}
/**
* <p>
* No longer used. If included, the only allowed value is <code>RequestBasedUsage</code>.
* </p>
*
* @return No longer used. If included, the only allowed value is <code>RequestBasedUsage</code>.
* @see PricingPlan
*/
@Deprecated
public String getPricingPlan() {
return this.pricingPlan;
}
/**
* <p>
* No longer used. If included, the only allowed value is <code>RequestBasedUsage</code>.
* </p>
*
* @param pricingPlan
* No longer used. If included, the only allowed value is <code>RequestBasedUsage</code>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see PricingPlan
*/
@Deprecated
public UpdateTrackerRequest withPricingPlan(String pricingPlan) {
setPricingPlan(pricingPlan);
return this;
}
/**
* <p>
* No longer used. If included, the only allowed value is <code>RequestBasedUsage</code>.
* </p>
*
* @param pricingPlan
* No longer used. If included, the only allowed value is <code>RequestBasedUsage</code>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see PricingPlan
*/
@Deprecated
public UpdateTrackerRequest withPricingPlan(PricingPlan pricingPlan) {
this.pricingPlan = pricingPlan.toString();
return this;
}
/**
* <p>
* This parameter is no longer used.
* </p>
*
* @param pricingPlanDataSource
* This parameter is no longer used.
*/
@Deprecated
public void setPricingPlanDataSource(String pricingPlanDataSource) {
this.pricingPlanDataSource = pricingPlanDataSource;
}
/**
* <p>
* This parameter is no longer used.
* </p>
*
* @return This parameter is no longer used.
*/
@Deprecated
public String getPricingPlanDataSource() {
return this.pricingPlanDataSource;
}
/**
* <p>
* This parameter is no longer used.
* </p>
*
* @param pricingPlanDataSource
* This parameter is no longer used.
* @return Returns a reference to this object so that method calls can be chained together.
*/
@Deprecated
public UpdateTrackerRequest withPricingPlanDataSource(String pricingPlanDataSource) {
setPricingPlanDataSource(pricingPlanDataSource);
return this;
}
/**
* <p>
* The name of the tracker resource to update.
* </p>
*
* @param trackerName
* The name of the tracker resource to update.
*/
public void setTrackerName(String trackerName) {
this.trackerName = trackerName;
}
/**
* <p>
* The name of the tracker resource to update.
* </p>
*
* @return The name of the tracker resource to update.
*/
public String getTrackerName() {
return this.trackerName;
}
/**
* <p>
* The name of the tracker resource to update.
* </p>
*
* @param trackerName
* The name of the tracker resource to update.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateTrackerRequest withTrackerName(String trackerName) {
setTrackerName(trackerName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getPositionFiltering() != null)
sb.append("PositionFiltering: ").append(getPositionFiltering()).append(",");
if (getPricingPlan() != null)
sb.append("PricingPlan: ").append(getPricingPlan()).append(",");
if (getPricingPlanDataSource() != null)
sb.append("PricingPlanDataSource: ").append(getPricingPlanDataSource()).append(",");
if (getTrackerName() != null)
sb.append("TrackerName: ").append(getTrackerName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UpdateTrackerRequest == false)
return false;
UpdateTrackerRequest other = (UpdateTrackerRequest) obj;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getPositionFiltering() == null ^ this.getPositionFiltering() == null)
return false;
if (other.getPositionFiltering() != null && other.getPositionFiltering().equals(this.getPositionFiltering()) == false)
return false;
if (other.getPricingPlan() == null ^ this.getPricingPlan() == null)
return false;
if (other.getPricingPlan() != null && other.getPricingPlan().equals(this.getPricingPlan()) == false)
return false;
if (other.getPricingPlanDataSource() == null ^ this.getPricingPlanDataSource() == null)
return false;
if (other.getPricingPlanDataSource() != null && other.getPricingPlanDataSource().equals(this.getPricingPlanDataSource()) == false)
return false;
if (other.getTrackerName() == null ^ this.getTrackerName() == null)
return false;
if (other.getTrackerName() != null && other.getTrackerName().equals(this.getTrackerName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getPositionFiltering() == null) ? 0 : getPositionFiltering().hashCode());
hashCode = prime * hashCode + ((getPricingPlan() == null) ? 0 : getPricingPlan().hashCode());
hashCode = prime * hashCode + ((getPricingPlanDataSource() == null) ? 0 : getPricingPlanDataSource().hashCode());
hashCode = prime * hashCode + ((getTrackerName() == null) ? 0 : getTrackerName().hashCode());
return hashCode;
}
@Override
public UpdateTrackerRequest clone() {
return (UpdateTrackerRequest) super.clone();
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-codecommit/src/main/java/com/amazonaws/services/codecommit/model/transform/ListAssociatedApprovalRuleTemplatesForRepositoryRequestMarshaller.java | 3056 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.codecommit.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.codecommit.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ListAssociatedApprovalRuleTemplatesForRepositoryRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ListAssociatedApprovalRuleTemplatesForRepositoryRequestMarshaller {
private static final MarshallingInfo<String> REPOSITORYNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("repositoryName").build();
private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("nextToken").build();
private static final MarshallingInfo<Integer> MAXRESULTS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("maxResults").build();
private static final ListAssociatedApprovalRuleTemplatesForRepositoryRequestMarshaller instance = new ListAssociatedApprovalRuleTemplatesForRepositoryRequestMarshaller();
public static ListAssociatedApprovalRuleTemplatesForRepositoryRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ListAssociatedApprovalRuleTemplatesForRepositoryRequest listAssociatedApprovalRuleTemplatesForRepositoryRequest,
ProtocolMarshaller protocolMarshaller) {
if (listAssociatedApprovalRuleTemplatesForRepositoryRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listAssociatedApprovalRuleTemplatesForRepositoryRequest.getRepositoryName(), REPOSITORYNAME_BINDING);
protocolMarshaller.marshall(listAssociatedApprovalRuleTemplatesForRepositoryRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(listAssociatedApprovalRuleTemplatesForRepositoryRequest.getMaxResults(), MAXRESULTS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
spring-projects/spring-data-examples | jpa/deferred/src/main/java/example/repo/Customer157Repository.java | 280 | package example.repo;
import example.model.Customer157;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface Customer157Repository extends CrudRepository<Customer157, Long> {
List<Customer157> findByLastName(String lastName);
}
| apache-2.0 |
agwlvssainokuni/springapp2 | galleryapp/gallery-web/src/main/java/cherry/gallery/web/applied/ex40/AppliedEx41SubFormBase.java | 4148 | /*
* Copyright 2016 agwlvssainokuni
*
* 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 cherry.gallery.web.applied.ex40;
import java.io.Serializable;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.context.MessageSourceResolvable;
import cherry.fundamental.bizerror.BizErrorUtil;
@Getter
@Setter
@EqualsAndHashCode
@ToString
@javax.annotation.Generated(value = "cherry.gradle.task.generator.GenerateForm")
public abstract class AppliedEx41SubFormBase implements Serializable {
private static final long serialVersionUID = 1L;
@org.hibernate.validator.constraints.NotEmpty(groups = { javax.validation.groups.Default.class })
@cherry.fundamental.validator.MaxLength(value = 10, groups = { javax.validation.groups.Default.class })
@cherry.fundamental.validator.CharTypeAlphaNumeric(groups = { javax.validation.groups.Default.class })
private String text10;
@cherry.fundamental.validator.MaxLength(value = 100, groups = { javax.validation.groups.Default.class })
private String text100;
@javax.validation.constraints.Min(value = -1000000000, groups = { javax.validation.groups.Default.class })
@javax.validation.constraints.Max(value = 1000000000, groups = { javax.validation.groups.Default.class })
@org.springframework.format.annotation.NumberFormat(pattern = cherry.gallery.web.FormatPattern.LONG)
private Long int64;
@javax.validation.constraints.DecimalMin(value = "-1000000000", groups = { javax.validation.groups.Default.class })
@javax.validation.constraints.DecimalMax(value = "1000000000", groups = { javax.validation.groups.Default.class })
@cherry.fundamental.validator.NumberScale(1)
@org.springframework.format.annotation.NumberFormat(pattern = cherry.gallery.web.FormatPattern.DECIMAL_1)
private java.math.BigDecimal decimal1;
@javax.validation.constraints.DecimalMin(value = "-1000000000", groups = { javax.validation.groups.Default.class })
@javax.validation.constraints.DecimalMax(value = "1000000000", groups = { javax.validation.groups.Default.class })
@cherry.fundamental.validator.NumberScale(3)
@org.springframework.format.annotation.NumberFormat(pattern = cherry.gallery.web.FormatPattern.DECIMAL_3)
private java.math.BigDecimal decimal3;
@org.springframework.format.annotation.DateTimeFormat(pattern = cherry.gallery.web.FormatPattern.DATE)
private java.time.LocalDate dt;
@org.springframework.format.annotation.DateTimeFormat(pattern = cherry.gallery.web.FormatPattern.TIME)
private java.time.LocalTime tm;
@org.springframework.format.annotation.DateTimeFormat(pattern = cherry.gallery.web.FormatPattern.DATETIME)
private java.time.LocalDateTime dtm;
private Integer lockVersion;
@Getter
public enum Prop {
Text10("text10", "appliedEx41SubForm.text10"), //
Text100("text100", "appliedEx41SubForm.text100"), //
Int64("int64", "appliedEx41SubForm.int64"), //
Decimal1("decimal1", "appliedEx41SubForm.decimal1"), //
Decimal3("decimal3", "appliedEx41SubForm.decimal3"), //
Dt("dt", "appliedEx41SubForm.dt"), //
Tm("tm", "appliedEx41SubForm.tm"), //
Dtm("dtm", "appliedEx41SubForm.dtm"), //
LockVersion("lockVersion", "appliedEx41SubForm.lockVersion"), //
DUMMY("dummy", "dummy");
private final String name;
private final String nameWithForm;
private Prop(String name, String nameWithForm) {
this.name = name;
this.nameWithForm = nameWithForm;
}
public MessageSourceResolvable resolve() {
return BizErrorUtil.resolve(nameWithForm);
}
}
}
| apache-2.0 |
sharmaak/jwt-generator | src/main/java/com/amitcodes/jwt/model/Header.java | 919 | package com.amitcodes.jwt.model;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Header {
@JsonProperty("typ")
private String type;
@JsonProperty("alg")
private String algorithm;
public Header() {
}
public String getType() {
return type;
}
public Header setType(String type) {
this.type = type;
return this;
}
public String getAlgorithm() {
return algorithm;
}
public Header setAlgorithm(String algorithm) {
this.algorithm = algorithm;
return this;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder( "Header{" );
sb.append( "type='" ).append( type ).append( '\'' );
sb.append( ", algorithm='" ).append( algorithm ).append( '\'' );
sb.append( '}' );
return sb.toString();
}
}
| apache-2.0 |
justinsb/cloudata | cloudata-files/src/main/java/com/cloudata/files/webdav/MkdirHandler.java | 1528 | package com.cloudata.files.webdav;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpResponseStatus;
import com.cloudata.files.FilesModel.InodeData;
import com.cloudata.files.fs.FsClient;
import com.cloudata.files.fs.FsPath;
import com.cloudata.files.fs.Inode;
import com.google.protobuf.ByteString;
public class MkdirHandler extends MethodHandler {
public MkdirHandler(WebdavRequestHandler requestHandler) {
super(requestHandler);
}
@Override
protected boolean shouldResolveParent() {
return true;
}
@Override
protected HttpObject doAction(FsPath parentPath) throws Exception {
WebdavRequest request = getRequest();
FsClient fsClient = getFsClient();
if (!parentPath.isFolder()) {
throw new WebdavResponseException(HttpResponseStatus.CONFLICT);
}
if (request.hasContent()) {
throw new UnsupportedOperationException();
}
String path = request.getUri();
String name = Urls.getLastPathComponent(path, true);
InodeData.Builder inode = InodeData.newBuilder();
long now = System.currentTimeMillis();
inode.setCreateTime(now);
inode.setModifiedTime(now);
int mode = Inode.S_IFDIR;
inode.setMode(mode);
boolean overwrite = false;
fsClient.createNewFolder(parentPath, ByteString.copyFromUtf8(name), inode, overwrite);
return buildFullResponse(HttpResponseStatus.CREATED);
}
}
| apache-2.0 |
michaelmarconi/oncue | oncue-tests/src/test/java/oncue/tests/strategies/JVMCapacityStrategyTest.java | 7207 | /*******************************************************************************
* Copyright 2013 Michael Marconi
*
* 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 oncue.tests.strategies;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import junit.framework.Assert;
import oncue.agent.JVMCapacityAgent;
import oncue.common.messages.EnqueueJob;
import oncue.common.messages.Job;
import oncue.common.messages.WorkResponse;
import oncue.scheduler.JVMCapacityScheduler;
import oncue.tests.base.ActorSystemTest;
import oncue.tests.workers.TestWorker;
import org.junit.Ignore;
import org.junit.Test;
import akka.actor.Actor;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActorFactory;
import akka.testkit.JavaTestKit;
import akka.testkit.TestActorRef;
/**
* Test the JVM memory capacity strategy by farming jobs of known size out to
* agents with known capacities.
*/
public class JVMCapacityStrategyTest extends ActorSystemTest {
/*-
* Jobs: J1(100), J2(200), J3(50), J4(200), J5(500)
* Agent capacity: A1(500), A2(70), A3(200)
*
* J1(100): | A2(70) | A3(200) | A1(500) |
* | x | J1 | - |
*
* J2(200): | A2(70) | A3(100) | A1(500) |
* | x | x | J2 |
*
* J3(50): | A2(70) | A3(100) | A1(300) |
* | J3 | - | - |
*
* J4(200): | A2(20) | A3(100) | A1(300) |
* | x | x | J4 |
*
* J5(500): | A2(20) | A3(100) | A1(100) |
* | x | x | x |
*
* Final allocation: A1(J2,J4)
* A2(J3)
* A3(J1)
* Job 5 unscheduled!
*/
@Test
@SuppressWarnings("serial")
@Ignore("Ignore this test until this strategy becomes necessary")
public void jvmCapacityStrategyTest() {
new JavaTestKit(system) {
{
// Create a naked JVM capacity-aware scheduler
final Props schedulerProps = new Props(new UntypedActorFactory() {
@Override
public Actor create() {
return new JVMCapacityScheduler(null);
}
});
final TestActorRef<JVMCapacityScheduler> schedulerRef = TestActorRef.create(system, schedulerProps,
settings.SCHEDULER_NAME);
final JVMCapacityScheduler scheduler = schedulerRef.underlyingActor();
// Create agent probes
final JavaTestKit agentProbe1 = createAgentProbe();
final JavaTestKit agentProbe2 = createAgentProbe();
final JavaTestKit agentProbe3 = createAgentProbe();
/*
* Create three capacity-aware agents with pre-determined
* capacity
*/
createAgent(agentProbe1, "agent1", 500);
createAgent(agentProbe2, "agent2", 70);
createAgent(agentProbe3, "agent3", 200);
// Wait for initial work response at agents
agentProbe1.expectMsgClass(WorkResponse.class);
agentProbe2.expectMsgClass(WorkResponse.class);
agentProbe3.expectMsgClass(WorkResponse.class);
/*
* Pause the scheduler, as we want the scheduler to see all
* enqueued jobs in a single batch for testing purposes
*/
scheduler.pause();
/*
* Enqueue jobs with various sizes
*/
enqueueJob(schedulerRef, getRef(), 100);
Job job1 = expectMsgClass(Job.class);
enqueueJob(schedulerRef, getRef(), 200);
Job job2 = expectMsgClass(Job.class);
enqueueJob(schedulerRef, getRef(), 50);
Job job3 = expectMsgClass(Job.class);
enqueueJob(schedulerRef, getRef(), 200);
Job job4 = expectMsgClass(Job.class);
enqueueJob(schedulerRef, getRef(), 500);
Job job5 = expectMsgClass(Job.class);
// Unpause the scheduler
scheduler.unpause();
// Expect Job 2 and Job 4 at Agent 1
WorkResponse agent1WorkResponse = agentProbe1.expectMsgClass(WorkResponse.class);
Assert.assertEquals(2, agent1WorkResponse.getJobs().size());
Job agent1Job2 = agent1WorkResponse.getJobs().get(0);
Assert.assertEquals(job2.getParams().get(JVMCapacityScheduler.JOB_SIZE),
agent1Job2.getParams().get(JVMCapacityScheduler.JOB_SIZE));
Job agent1Job4 = agent1WorkResponse.getJobs().get(0);
Assert.assertEquals(job4.getParams().get(JVMCapacityScheduler.JOB_SIZE),
agent1Job4.getParams().get(JVMCapacityScheduler.JOB_SIZE));
// Expect Job 3 at Agent 2
WorkResponse agent2WorkResponse = agentProbe2.expectMsgClass(WorkResponse.class);
Assert.assertEquals(1, agent2WorkResponse.getJobs().size());
Job agent2Job3 = agent2WorkResponse.getJobs().get(0);
Assert.assertEquals(job3.getParams().get(JVMCapacityScheduler.JOB_SIZE),
agent2Job3.getParams().get(JVMCapacityScheduler.JOB_SIZE));
// Expect Job 1 at Agent 3
WorkResponse agent3WorkResponse = agentProbe3.expectMsgClass(WorkResponse.class);
Assert.assertEquals(1, agent3WorkResponse.getJobs().size());
Job agent3Job1 = agent3WorkResponse.getJobs().get(0);
Assert.assertEquals(job1.getParams().get(JVMCapacityScheduler.JOB_SIZE),
agent3Job1.getParams().get(JVMCapacityScheduler.JOB_SIZE));
/*
* Now, Jobs 1 - 4 will complete and all the agents will ask for
* new work. Since Agent 1 is the only one big enough to fit Job
* 5, it will receive it.
*/
agent1WorkResponse = agentProbe1.expectMsgClass(duration("5 seconds"), WorkResponse.class);
Assert.assertEquals(1, agent1WorkResponse.getJobs().size());
Job agent1Job5 = agent1WorkResponse.getJobs().get(0);
Assert.assertEquals(job5.getParams().get(JVMCapacityScheduler.JOB_SIZE),
agent1Job5.getParams().get(JVMCapacityScheduler.JOB_SIZE));
}
};
}
private JavaTestKit createAgentProbe() {
return new JavaTestKit(system) {
{
new IgnoreMsg() {
@Override
protected boolean ignore(Object message) {
return !(message instanceof WorkResponse);
}
};
}
};
}
@SuppressWarnings("serial")
private void createAgent(final JavaTestKit agentProbe, String name, final int capacity) {
system.actorOf(new Props(new UntypedActorFactory() {
@Override
public Actor create() throws Exception {
JVMCapacityAgent agent = new JVMCapacityAgent(new HashSet<String>(Arrays.asList(TestWorker.class
.getName())), capacity);
agent.injectProbe(agentProbe.getRef());
return agent;
}
}), name);
}
@SuppressWarnings("serial")
private void enqueueJob(ActorRef scheduler, ActorRef testKit, final int jobSize) {
scheduler.tell(new EnqueueJob(TestWorker.class.getName(), new HashMap<String, String>() {
{
put(JVMCapacityScheduler.JOB_SIZE, new Integer(jobSize).toString());
}
}), testKit);
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-storagegateway/src/main/java/com/amazonaws/services/storagegateway/model/transform/UpdateChapCredentialsRequestMarshaller.java | 3214 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.storagegateway.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.storagegateway.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UpdateChapCredentialsRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateChapCredentialsRequestMarshaller {
private static final MarshallingInfo<String> TARGETARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("TargetARN").build();
private static final MarshallingInfo<String> SECRETTOAUTHENTICATEINITIATOR_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SecretToAuthenticateInitiator").build();
private static final MarshallingInfo<String> INITIATORNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("InitiatorName").build();
private static final MarshallingInfo<String> SECRETTOAUTHENTICATETARGET_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SecretToAuthenticateTarget").build();
private static final UpdateChapCredentialsRequestMarshaller instance = new UpdateChapCredentialsRequestMarshaller();
public static UpdateChapCredentialsRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(UpdateChapCredentialsRequest updateChapCredentialsRequest, ProtocolMarshaller protocolMarshaller) {
if (updateChapCredentialsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateChapCredentialsRequest.getTargetARN(), TARGETARN_BINDING);
protocolMarshaller.marshall(updateChapCredentialsRequest.getSecretToAuthenticateInitiator(), SECRETTOAUTHENTICATEINITIATOR_BINDING);
protocolMarshaller.marshall(updateChapCredentialsRequest.getInitiatorName(), INITIATORNAME_BINDING);
protocolMarshaller.marshall(updateChapCredentialsRequest.getSecretToAuthenticateTarget(), SECRETTOAUTHENTICATETARGET_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
marcokrikke/excelbundle | src/main/java/senselogic/excelbundle/LanguageTreeIO.java | 11956 | /*
* Copyright 2006 Senselogic
*
* 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 senselogic.excelbundle;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Class for reading and writing LanguagePacks to and from a source tree.
*
* @author Emil Eriksson
* @version $Revision$
*/
public class LanguageTreeIO
{
// Static --------------------------------------------------------
private static Pattern pattern =
Pattern.compile( "([^\\s=\\\\#!]+)\\s*=.*" );
// Attributes ----------------------------------------------------
private File root;
private String refLang;
private Set<String> languages = new HashSet<String>();
private Map<String, BundleInfo> bundles =
new LinkedHashMap<String, BundleInfo>();
private Map<String, LanguagePack> packCache =
new HashMap<String, LanguagePack>();
private Map<String, LanguageFile> fileCache =
new HashMap<String, LanguageFile>();
// Constructors --------------------------------------------------
/**
* Constructs a new LanguageTreeIO.
*
* @param root the root of the source tree to read language files from
* @param refLang the language to use as reference for searching for
* bundles
* @throws java.io.IOException
*/
public LanguageTreeIO( File root, String refLang ) throws IOException
{
this.root = root;
this.refLang = refLang;
findBundles( root );
}
// Public --------------------------------------------------------
/**
* Returns the root of this LanguageTreeIO.
*
* @return
*/
public File getRoot()
{
return root;
}
/**
* Returns a Collection of all the languages that are available in at least
* one bundle.
*
* @return
*/
public Collection<String> getAvailableLanguages()
{
return languages;
}
/**
* Returns the BundleInfo with the specified path.
*
* @param path
* @return
*/
public BundleInfo getBundle( String path )
{
return bundles.get( path );
}
/**
* Returns a Collection of BundleInfo objects describing all of the
* available bundles.
*
* @return
*/
public Collection<BundleInfo> getBundles()
{
return bundles.values();
}
/**
* Creates a LanguageFile from a file.
*
* @param bundlePath the relative logical path to the bundle, e.g.
* bla/bla/mybundle
* @param language the language of the file
* @return
* @throws java.io.IOException
*/
public LanguageFile loadLanguageFile( String bundlePath, String language )
throws IOException
{
LanguageFile langFile = fileCache.get(
LanguageFile.getFilename( bundlePath, language ) );
if (langFile != null)
return langFile;
langFile = new LanguageFile( bundlePath, language );
Properties prop = new CustomProperties();
File file = new File( root, langFile.getFilename() );
if (!file.exists())
return null;
InputStream inputStream = null;
try
{
inputStream = new BufferedInputStream(new FileInputStream( file ));
prop.load( inputStream );
} finally
{
if (inputStream != null) inputStream.close();
}
for (Map.Entry<Object, Object> entry : prop.entrySet())
langFile.setValue( (String) entry.getKey(), (String) entry.getValue() );
fileCache.put( langFile.getFilename(), langFile );
return langFile;
}
/**
* Loads all the language files associated with the specified language and
* returns them as a LanguagePack. This method caches the read file so
* subsequent calls to this method will not read the file multiple times.
*
* @param language
* @return
* @throws java.io.IOException
*/
public LanguagePack loadLanguage( String language ) throws IOException
{
LanguagePack pack = packCache.get( language );
if (pack != null)
return pack;
pack = new LanguagePack( language );
for (BundleInfo bundle : bundles.values())
{
if (!bundle.getLanguages().contains( language ))
continue;
LanguageFile langFile = loadLanguageFile( bundle.getPath(), language );
if (langFile == null)
continue;
pack.addLanguageFile( langFile );
}
packCache.put( pack.getLanguage(), pack );
return pack;
}
/**
* Writes the specified LanguageFile to the source tree.
*/
public void save( LanguageFile langFile ) throws IOException
{
File file = new File( root, langFile.getFilename() );
if (!file.exists())
{
Properties prop = new Properties();
for (LanguageFile.KeyValuePair pair : langFile.getPairs())
prop.put( pair.getKey(), pair.getValue() );
OutputStream outputStream = null;
try
{
outputStream = new BufferedOutputStream(new FileOutputStream( file ));
prop.store( outputStream, null );
} finally
{
if (outputStream != null) outputStream.close();
}
return;
}
BufferedReader in = new BufferedReader( new InputStreamReader(
new FileInputStream( file ), "ISO-8859-1" ) );
List<String> lines = new ArrayList<String>();
try
{
String line = null;
while ((line = in.readLine()) != null)
lines.add( line );
}
finally
{
in.close();
}
PrintStream out = new PrintStream(
new FileOutputStream( file ), false, "ISO-8859-1" );
try
{
//This is used to keep track of what keys remain to be written in
//the end of the file
Map<String, LanguageFile.KeyValuePair> remaining =
new LinkedHashMap<String, LanguageFile.KeyValuePair>();
for (LanguageFile.KeyValuePair pair : langFile.getPairs())
remaining.put( pair.getKey(), pair );
for (String line : lines)
{
if ((line.trim().length() == 0) ||
(line.trim().charAt( 0 ) == '#') ||
(line.trim().charAt( 0 ) == '!'))
{
out.println( line );
continue;
}
Matcher matcher = pattern.matcher( line.trim() );
if (matcher.matches())
{
String key = matcher.group( 1 );
String value = langFile.getValue( key );
if (value == null)
continue;
out.print( key );
out.print( " = " );
out.println( EscapeUtil.escape( value, false ) );
remaining.remove( key );
}
}
//Let's write the remaining keys:
for (LanguageFile.KeyValuePair pair : remaining.values())
{
out.print( pair.getKey() );
out.print( " = " );
out.println( EscapeUtil.escape( pair.getValue(), false ) );
}
}
finally
{
out.close();
}
}
/**
* Returns true if the specified LanguageFile exists in the source tree,
* that is, if it has a file with the same name as this one, not
* necessarily an identical file.
*/
public boolean exists( LanguageFile langFile )
{
return new File( root, langFile.getFilename() ).exists();
}
/**
* Updates the internal list of available bundles and the available
* languages in the bundles and clears the cache.
*/
public void update() throws IOException
{
clearCache();
bundles.clear();
findBundles( root );
}
/**
* Clears the cache.
*/
public void clearCache()
{
packCache.clear();
fileCache.clear();
}
// Private -------------------------------------------------------
private void findBundles( File dir ) throws IOException
{
for (File file : dir.listFiles())
{
if (file.isDirectory())
{
findBundles( file );
continue;
}
String bundleName = null;
String suffix = "_" + refLang + ".properties";
//We use english language files as a reference for what properties
//files actually are language files and not other stuff
if (file.getName().endsWith( suffix ) &&
!file.isDirectory())
{
String filename = file.getName();
final String bundle =
filename.substring( 0, filename.indexOf( "_" ) );
bundleName = bundle;
//Let's find all of the languages
Collection<String> bundleLangs = new ArrayList<String>();
File[] sisterFiles = dir.listFiles( new FilenameFilter()
{
public boolean accept( File path, String filename )
{
return filename.matches( bundle + ".*\\.properties" );
}
} );
for (File langFile : sisterFiles)
{
filename = langFile.getName();
String language = null;
if (filename.contains( "_" ))
{
language = filename.substring( (
bundle.length() + 1),
filename.length() - ".properties".length() );
} else // Must be default language if it conatains no "_"
language = LanguageFile.DEFAULT_LANGUAGE;
bundleLangs.add( language );
languages.add( language );
}
//Now let's add a BundleInfo
String relativePath =
dir.getCanonicalPath().substring(
root.getCanonicalPath().length() ) + File.separator;
String completePath = relativePath + bundleName;
bundles.put(
completePath,
new BundleInfo( completePath, bundleLangs ) );
}
}
}
}
| apache-2.0 |
og0815/granditeds.javafx.sample | client-tryout/src/main/java/org/graniteds/tutorial/data/client/AccountService.java | 604 | /**
* Generated by Gfx v3.0.0 (Granite Data Services).
*
* NOTE: this file is only generated if it does not exist. You may safely put
* your custom code here.
*/
package org.graniteds.tutorial.data.client;
import javax.inject.Inject;
import javax.inject.Named;
import org.granite.client.messaging.RemoteAlias;
import org.granite.client.tide.server.ServerSession;
@Named
@RemoteAlias("org.graniteds.tutorial.data.services.AccountService")
public class AccountService extends AccountServiceBase {
@Inject
public AccountService(ServerSession serverSession) {
super(serverSession);
}
}
| apache-2.0 |
trasa/aws-sdk-java | aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/model/transform/InstanceJsonMarshaller.java | 3343 | /*
* 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.elasticmapreduce.model.transform;
import static com.amazonaws.util.StringUtils.UTF8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.List;
import com.amazonaws.AmazonClientException;
import com.amazonaws.services.elasticmapreduce.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;
/**
* InstanceMarshaller
*/
public class InstanceJsonMarshaller {
/**
* Marshall the given parameter object, and output to a JSONWriter
*/
public void marshall(Instance instance, JSONWriter jsonWriter) {
if (instance == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
try {
jsonWriter.object();
if (instance.getId() != null) {
jsonWriter.key("Id").value(instance.getId());
}
if (instance.getEc2InstanceId() != null) {
jsonWriter.key("Ec2InstanceId").value(
instance.getEc2InstanceId());
}
if (instance.getPublicDnsName() != null) {
jsonWriter.key("PublicDnsName").value(
instance.getPublicDnsName());
}
if (instance.getPublicIpAddress() != null) {
jsonWriter.key("PublicIpAddress").value(
instance.getPublicIpAddress());
}
if (instance.getPrivateDnsName() != null) {
jsonWriter.key("PrivateDnsName").value(
instance.getPrivateDnsName());
}
if (instance.getPrivateIpAddress() != null) {
jsonWriter.key("PrivateIpAddress").value(
instance.getPrivateIpAddress());
}
if (instance.getStatus() != null) {
jsonWriter.key("Status");
InstanceStatusJsonMarshaller.getInstance().marshall(
instance.getStatus(), jsonWriter);
}
jsonWriter.endObject();
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
}
private static InstanceJsonMarshaller instance;
public static InstanceJsonMarshaller getInstance() {
if (instance == null)
instance = new InstanceJsonMarshaller();
return instance;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-eventbridge/src/main/java/com/amazonaws/services/eventbridge/model/transform/ListEventSourcesRequestMarshaller.java | 2658 | /*
* Copyright 2014-2019 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.eventbridge.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.eventbridge.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ListEventSourcesRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ListEventSourcesRequestMarshaller {
private static final MarshallingInfo<String> NAMEPREFIX_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("NamePrefix").build();
private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("NextToken").build();
private static final MarshallingInfo<Integer> LIMIT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Limit").build();
private static final ListEventSourcesRequestMarshaller instance = new ListEventSourcesRequestMarshaller();
public static ListEventSourcesRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ListEventSourcesRequest listEventSourcesRequest, ProtocolMarshaller protocolMarshaller) {
if (listEventSourcesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listEventSourcesRequest.getNamePrefix(), NAMEPREFIX_BINDING);
protocolMarshaller.marshall(listEventSourcesRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(listEventSourcesRequest.getLimit(), LIMIT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-lakeformation/src/main/java/com/amazonaws/services/lakeformation/model/transform/RegisterResourceRequestProtocolMarshaller.java | 2725 | /*
* Copyright 2014-2019 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.lakeformation.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.lakeformation.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* RegisterResourceRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RegisterResourceRequestProtocolMarshaller implements Marshaller<Request<RegisterResourceRequest>, RegisterResourceRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("AWSLakeFormation.RegisterResource").serviceName("AWSLakeFormation").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public RegisterResourceRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<RegisterResourceRequest> marshall(RegisterResourceRequest registerResourceRequest) {
if (registerResourceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<RegisterResourceRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
registerResourceRequest);
protocolMarshaller.startMarshalling();
RegisterResourceRequestMarshaller.getInstance().marshall(registerResourceRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/model/config/customization/ConvenienceTypeOverload.java | 3972 | /*
* Copyright 2010-2022 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.codegen.model.config.customization;
import com.amazonaws.codegen.model.intermediate.MemberModel;
import com.amazonaws.codegen.model.intermediate.ShapeModel;
/**
* Customization to allow generation of additional setter overloads for a 'convenience' type (i.e. a
* different type then what the member actually is but a more convenient representation to work
* with, I.E. String rather than ByteBuffer). Customization is configured with an adapter that knows
* how to convert the 'convenience' type to the actual member type
* <p>
* Note - This customization is not directly exposed through {@link CustomizationConfig} at the
* moment. Instead several pre-canned customizations use this under the hood but expose limited
* functionality for overloading setters. This decision was made to discourage use of overloaded
* types and instead model the member in a more natural way to begin with. In the future we may
* either decide to fully expose this customization or just add more pre-canned settings as the need
* arises
* </p>
* <p>
* Currently this does not support overloads for List or Map types but it could be easily
* implemented in the Generator.
* </p>
*/
public class ConvenienceTypeOverload {
/**
* Name of the shape this customization applies to
*/
private String shapeName;
/**
* Name of the member this customization applies to
*/
private String memberName;
/**
* Convenience type to generate an overload for
*/
private String convenienceType;
/**
* Fully qualified adapter class that can convert from the convenience type to the actual type
*/
private String typeAdapterFqcn;
public String getShapeName() {
return shapeName;
}
public void setShapeName(String shapeName) {
this.shapeName = shapeName;
}
public ConvenienceTypeOverload withShapeName(String shapeName) {
this.shapeName = shapeName;
return this;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public ConvenienceTypeOverload withMemberName(String memberName) {
this.memberName = memberName;
return this;
}
public String getConvenienceType() {
return convenienceType;
}
public void setConvenienceType(String convenienceType) {
this.convenienceType = convenienceType;
}
public ConvenienceTypeOverload withConvenienceType(String convenienceType) {
this.convenienceType = convenienceType;
return this;
}
public String getTypeAdapterFqcn() {
return typeAdapterFqcn;
}
public void setTypeAdapterFqcn(String typeAdapterFqcn) {
this.typeAdapterFqcn = typeAdapterFqcn;
}
public ConvenienceTypeOverload withTypeAdapterFqcn(String typeAdapterFqcn) {
this.typeAdapterFqcn = typeAdapterFqcn;
return this;
}
/**
* @param shape
* Current shape
* @param member
* Current member
* @return True if the {@link ConvenienceTypeOverload} applies. False otherwise
*/
public boolean accepts(ShapeModel shape, MemberModel member) {
return shape.getC2jName().equals(shapeName) && member.getC2jName().equals(memberName);
}
}
| apache-2.0 |
kevinearls/camel | components/camel-soap/src/main/java/org/apache/camel/dataformat/soap/SoapJaxbDataFormat.java | 13243 | /**
* 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.dataformat.soap;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.JAXBIntrospector;
import javax.xml.namespace.QName;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.bean.BeanInvocation;
import org.apache.camel.converter.jaxb.JaxbDataFormat;
import org.apache.camel.dataformat.soap.name.ElementNameStrategy;
import org.apache.camel.dataformat.soap.name.ServiceInterfaceStrategy;
import org.apache.camel.dataformat.soap.name.TypeNameStrategy;
/**
* Data format supporting SOAP 1.1 and 1.2.
*/
public class SoapJaxbDataFormat extends JaxbDataFormat {
public static final String SOAP_UNMARSHALLED_HEADER_LIST = "org.apache.camel.dataformat.soap.UNMARSHALLED_HEADER_LIST";
private SoapDataFormatAdapter adapter;
private ElementNameStrategy elementNameStrategy;
private String elementNameStrategyRef;
private boolean ignoreUnmarshalledHeaders;
private String version;
/**
* Remember to set the context path when using this constructor
*/
public SoapJaxbDataFormat() {
}
/**
* Initialize with JAXB context path
*/
public SoapJaxbDataFormat(String contextPath) {
super(contextPath);
}
/**
* Initialize the data format. The serviceInterface is necessary to
* determine the element name and namespace of the element inside the soap
* body when marshalling
*/
public SoapJaxbDataFormat(String contextPath, ElementNameStrategy elementNameStrategy) {
this(contextPath);
this.elementNameStrategy = elementNameStrategy;
}
/**
* Initialize the data format. The serviceInterface is necessary to
* determine the element name and namespace of the element inside the soap
* body when marshalling
*/
public SoapJaxbDataFormat(String contextPath, String elementNameStrategyRef) {
this(contextPath);
this.elementNameStrategyRef = elementNameStrategyRef;
}
@Override
public String getDataFormatName() {
return "soapjaxb";
}
@Override
protected void doStart() throws Exception {
if ("1.2".equals(version)) {
log.debug("Using SOAP 1.2 adapter");
adapter = new Soap12DataFormatAdapter(this);
} else {
log.debug("Using SOAP 1.1 adapter");
adapter = new Soap11DataFormatAdapter(this);
}
super.doStart();
}
protected void checkElementNameStrategy(Exchange exchange) {
if (elementNameStrategy == null) {
synchronized (this) {
if (elementNameStrategy != null) {
return;
} else {
if (elementNameStrategyRef != null) {
elementNameStrategy = exchange.getContext().getRegistry().lookupByNameAndType(elementNameStrategyRef,
ElementNameStrategy.class);
} else {
elementNameStrategy = new TypeNameStrategy();
}
}
}
}
}
/**
* Marshal inputObjects to SOAP xml. If the exchange or message has an
* EXCEPTION_CAUGTH property or header then instead of the object the
* exception is marshaled.
*
* To determine the name of the top level xml elements the elementNameStrategy
* is used.
*/
public void marshal(Exchange exchange, Object inputObject, OutputStream stream) throws IOException {
checkElementNameStrategy(exchange);
String soapAction = getSoapActionFromExchange(exchange);
if (soapAction == null && inputObject instanceof BeanInvocation) {
BeanInvocation beanInvocation = (BeanInvocation) inputObject;
WebMethod webMethod = beanInvocation.getMethod().getAnnotation(WebMethod.class);
if (webMethod != null && webMethod.action() != null) {
soapAction = webMethod.action();
}
}
Object envelope = adapter.doMarshal(exchange, inputObject, stream, soapAction);
// and continue in super
super.marshal(exchange, envelope, stream);
}
/**
* Create body content from a non Exception object. If the inputObject is a
* BeanInvocation the following should be considered: The first parameter
* will be used for the SOAP body. BeanInvocations with more than one
* parameter are not supported. So the interface should be in doc lit bare
* style.
*
* @param inputObject
* object to be put into the SOAP body
* @param soapAction
* for name resolution
* @param headerElements
* in/out parameter used to capture header content if present
*
* @return JAXBElement for the body content
*/
protected List<Object> createContentFromObject(final Object inputObject, String soapAction,
List<Object> headerElements) {
List<Object> bodyParts = new ArrayList<>();
List<Object> headerParts = new ArrayList<>();
if (inputObject instanceof BeanInvocation) {
BeanInvocation bi = (BeanInvocation)inputObject;
Annotation[][] annotations = bi.getMethod().getParameterAnnotations();
List<WebParam> webParams = new ArrayList<>();
for (Annotation[] singleParameterAnnotations : annotations) {
for (Annotation annotation : singleParameterAnnotations) {
if (annotation instanceof WebParam) {
webParams.add((WebParam)annotation);
}
}
}
if (webParams.size() > 0) {
if (webParams.size() == bi.getArgs().length) {
int index = -1;
for (Object o : bi.getArgs()) {
if (webParams.get(++index).header()) {
headerParts.add(o);
} else {
bodyParts.add(o);
}
}
} else {
throw new RuntimeCamelException("The number of bean invocation parameters does not "
+ "match the number of parameters annotated with @WebParam for the method [ "
+ bi.getMethod().getName() + "].");
}
} else {
// try to map all objects for the body
for (Object o : bi.getArgs()) {
bodyParts.add(o);
}
}
} else {
bodyParts.add(inputObject);
}
List<Object> bodyElements = new ArrayList<>();
for (Object bodyObj : bodyParts) {
QName name = elementNameStrategy.findQNameForSoapActionOrType(soapAction, bodyObj.getClass());
if (name == null) {
log.warn("Could not find QName for class {}", bodyObj.getClass().getName());
continue;
} else {
bodyElements.add(getElement(bodyObj, name));
}
}
for (Object headerObj : headerParts) {
QName name = elementNameStrategy.findQNameForSoapActionOrType(soapAction, headerObj.getClass());
if (name == null) {
log.warn("Could not find QName for class {}", headerObj.getClass().getName());
continue;
} else {
JAXBElement<?> headerElem = getElement(headerObj, name);
if (null != headerElem) {
headerElements.add(headerElem);
}
}
}
return bodyElements;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private JAXBElement<?> getElement(Object fromObj, QName name) {
Object value = null;
// In the case of a parameter, the class of the value of the holder class
// is used for the mapping rather than the holder class itself.
if (fromObj instanceof javax.xml.ws.Holder) {
javax.xml.ws.Holder holder = (javax.xml.ws.Holder) fromObj;
value = holder.value;
if (null == value) {
return null;
}
} else {
value = fromObj;
}
return new JAXBElement(name, value.getClass(), value);
}
/**
* Unmarshal a given SOAP xml stream and return the content of the SOAP body
*/
public Object unmarshal(Exchange exchange, InputStream stream) throws IOException {
checkElementNameStrategy(exchange);
String soapAction = getSoapActionFromExchange(exchange);
// Determine the method name for an eventual BeanProcessor in the route
if (soapAction != null && elementNameStrategy instanceof ServiceInterfaceStrategy) {
ServiceInterfaceStrategy strategy = (ServiceInterfaceStrategy) elementNameStrategy;
String methodName = strategy.getMethodForSoapAction(soapAction);
exchange.getOut().setHeader(Exchange.BEAN_METHOD_NAME, methodName);
}
// Store soap action for an eventual later marshal step.
// This is necessary as the soap action in the message may get lost on the way
if (soapAction != null) {
exchange.setProperty(Exchange.SOAP_ACTION, soapAction);
}
Object unmarshalledObject = super.unmarshal(exchange, stream);
Object rootObject = JAXBIntrospector.getValue(unmarshalledObject);
return adapter.doUnmarshal(exchange, stream, rootObject);
}
private String getSoapActionFromExchange(Exchange exchange) {
Message inMessage = exchange.getIn();
String soapAction = inMessage .getHeader(Exchange.SOAP_ACTION, String.class);
if (soapAction == null) {
soapAction = inMessage.getHeader("SOAPAction", String.class);
if (soapAction != null && soapAction.startsWith("\"")) {
soapAction = soapAction.substring(1, soapAction.length() - 1);
}
}
if (soapAction == null) {
soapAction = exchange.getProperty(Exchange.SOAP_ACTION, String.class);
}
return soapAction;
}
/**
* Added the generated SOAP package to the JAXB context so Soap datatypes
* are available
*/
@Override
protected JAXBContext createContext() throws JAXBException {
if (getContextPath() != null) {
return JAXBContext.newInstance(adapter.getSoapPackageName() + ":" + getContextPath());
} else {
return JAXBContext.newInstance();
}
}
public ElementNameStrategy getElementNameStrategy() {
return elementNameStrategy;
}
public void setElementNameStrategy(Object nameStrategy) {
if (nameStrategy == null) {
this.elementNameStrategy = null;
} else if (nameStrategy instanceof ElementNameStrategy) {
this.elementNameStrategy = (ElementNameStrategy) nameStrategy;
} else {
throw new IllegalArgumentException("The argument for setElementNameStrategy should be subClass of "
+ ElementNameStrategy.class.getName());
}
}
public String getElementNameStrategyRef() {
return elementNameStrategyRef;
}
public void setElementNameStrategyRef(String elementNameStrategyRef) {
this.elementNameStrategyRef = elementNameStrategyRef;
}
public boolean isIgnoreUnmarshalledHeaders() {
return ignoreUnmarshalledHeaders;
}
public void setIgnoreUnmarshalledHeaders(boolean ignoreUnmarshalledHeaders) {
this.ignoreUnmarshalledHeaders = ignoreUnmarshalledHeaders;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
| apache-2.0 |
leafclick/intellij-community | java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveMembersHandler.java | 2964 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.move.moveMembers;
import com.intellij.lang.Language;
import com.intellij.lang.jvm.JvmLanguage;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.move.MoveCallback;
import com.intellij.refactoring.move.MoveHandlerDelegate;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class MoveMembersHandler extends MoveHandlerDelegate {
@Override
public boolean canMove(final PsiElement[] elements, @Nullable final PsiElement targetContainer, @Nullable PsiReference reference) {
for(PsiElement element: elements) {
if (!isFieldOrStaticMethod(element)) return false;
}
return targetContainer == null || super.canMove(elements, targetContainer, reference);
}
@Override
public boolean isValidTarget(final PsiElement targetElement, PsiElement[] sources) {
return targetElement instanceof PsiClass && !(targetElement instanceof PsiAnonymousClass);
}
@Override
public void doMove(final Project project, final PsiElement[] elements, final PsiElement targetContainer, final MoveCallback callback) {
MoveMembersImpl.doMove(project, elements, targetContainer, callback);
}
@Override
public boolean tryToMove(final PsiElement element, final Project project, final DataContext dataContext, final PsiReference reference,
final Editor editor) {
if (isFieldOrStaticMethod(element)) {
MoveMembersImpl.doMove(project, new PsiElement[]{element}, null, null);
return true;
}
return false;
}
private static boolean isFieldOrStaticMethod(final PsiElement element) {
if (element instanceof PsiField) return true;
if (element instanceof PsiMethod) {
if (element instanceof SyntheticElement) return false;
return ((PsiMethod) element).hasModifierProperty(PsiModifier.STATIC);
}
return false;
}
@Nullable
@Override
public String getActionName(PsiElement @NotNull [] elements) {
return RefactoringBundle.message("move.members.action.name");
}
@Override
public boolean supportsLanguage(@NotNull Language language) {
return language instanceof JvmLanguage;
}
}
| apache-2.0 |
dukechain/Qassandra | src/java/org/apache/cassandra/db/DefinitionsUpdateVerbHandler.java | 2177 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.concurrent.Stage;
import org.apache.cassandra.concurrent.StageManager;
import org.apache.cassandra.net.IVerbHandler;
import org.apache.cassandra.net.MessageIn;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.utils.WrappedRunnable;
/**
* Called when node receives updated schema state from the schema migration coordinator node.
* Such happens when user makes local schema migration on one of the nodes in the ring
* (which is going to act as coordinator) and that node sends (pushes) it's updated schema state
* (in form of row mutations) to all the alive nodes in the cluster.
*/
public class DefinitionsUpdateVerbHandler implements IVerbHandler<Collection<RowMutation>>
{
private static final Logger logger = LoggerFactory.getLogger(DefinitionsUpdateVerbHandler.class);
public void doVerb(final MessageIn<Collection<RowMutation>> message, int id)
{
logger.debug("Received schema mutation push from " + message.from);
StageManager.getStage(Stage.MIGRATION).submit(new WrappedRunnable()
{
public void runMayThrow() throws Exception
{
DefsTable.mergeSchema(message.payload);
}
});
}
} | apache-2.0 |